Master JavaScript Functions: From Basics to Advanced Patterns
This article provides a comprehensive guide to JavaScript functions, covering basic definitions, anonymous functions, default parameters, the arguments object, IIFE, nested functions, constructor functions, and best practices for using the new keyword, all illustrated with clear code examples.
This article aims to give web developers all the essential knowledge about JavaScript functions.
Functions are not a fantasy for software developers; if you write code, you create or modify functions daily.
In short, a function is a set of statements that perform an operation, may accept input parameters, and optionally return a value.
JavaScript functions share these traits but are also objects, meaning they can have properties and methods.
Below is a typical JavaScript function definition:
function myNotSoGreatFunc(visitor) {
console.log("Welcome to Code Morning Mr. " + visitor);
}The function logs a welcome message for a visitor. Function definitions start with the function keyword, followed by the name and parentheses for parameters, with the code block inside curly braces. The return statement is optional; if omitted, the function returns undefined.
Example call:
myNotSoGreatFunc("Bob Martin"); // Output: Welcome to Code Morning Mr. Bob Martin.Anonymous Functions
JavaScript functions can be anonymous, meaning they have no name and are stored in a variable.
var addNumbers = function (x, y) {
return x + y;
};The variable addNumbers acts as the function name. You can call it like this: var sum = addNumbers(2, 3); Anonymous functions are useful for passing functions as arguments:
var add = function (first, second) { return first + second; };
var multiply = function (first, second) { return first * second; };
function calculate(fun, a, b) {
return fun(a, b);
}
var sum = calculate(add, 2, 3); // sum = 5
var multiplication = calculate(multiply, 2, 3); // multiplication = 6This pattern is heavily used in AJAX callbacks.
More About Parameters
JavaScript is flexible with function parameters.
Missing Parameters
If fewer arguments are passed than declared, the missing ones become undefined.
function callMe(a, b, c) {
console.log("c is " + typeof c);
}
callMe("Code", "Morning"); // c is undefined
callMe("Learn", "JavaScript", "Functions"); // c is stringArguments Object
All functions have an arguments object that holds the passed arguments.
function callMe() {
for (var i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
}
console.log("Total arguments passed: " + arguments.length);
}
callMe("Code", "Morning", "Mr. Programmer");You can access each argument via arguments[index] and get the count with arguments.length.
Default Parameters
Since ES6, functions can have default parameter values.
function greetMyVisitors(name, profession = "The cool programmer") {
alert("Welcome Mr. " + name + ", " + profession);
}
greetMyVisitors("Justin Bieber", "The singer"); // Shows "Welcome Mr. Justin Bieber, The singer"
greetMyVisitors("Bob Martin"); // Shows "Welcome Mr. Bob Martin, The cool programmer"
greetMyVisitors("John Papa", undefined); // Shows "Welcome Mr. John Papa, The cool programmer"Nested Functions
Functions can contain other functions, creating a hierarchy.
function wakeUpAndCode() {
function wakeUp() {
console.log("I just woke up");
}
function code() {
console.log("I am ready to code now");
}
wakeUp();
code();
}
wakeUpAndCode(); // Outputs both messagesInner functions can access outer variables and form closures.
Immediately Invoked Function Expressions (IIFE)
An IIFE is an anonymous function that runs as soon as it is defined.
(function(){
// Your awesome code here
}()); (function(){
console.log("I run on my own.");
}());IIFEs create a local scope, protecting variables from the global environment.
Constructor Functions
Functions can act as constructors to create objects, enabling object‑oriented patterns.
function Programmer(name, company, expertise) {
this.name = name;
this.company = company;
this.expertise = expertise;
this.writeCode = function() { console.log("Writing some public static thing.."); };
this.makeSkypeCall = function() { console.log("Making skype call.."); };
this.doSalsa = function() { console.log("I'm a programmer, I can only do Gangnam style.."); };
this.canWriteJavaScript = function() { return expertise === "JavaScript"; };
}
var javaProgrammer = new Programmer("Mohit Srivastava", "Infosys", "Java");
var dotnetProgrammer = new Programmer("Atul Mishra", "Prowareness", ".NET");Always use the new keyword; omitting it adds properties to the global window object.
var jsProgrammer = Programmer("Douglas Crockford", "Yahoo", "JavaScript"); // Missing new – pollutes global scopeA safe constructor checks the instance:
function Programmer(name, company, expertise) {
if (!(this instanceof Programmer)) {
return new Programmer(name, company, expertise);
}
this.name = name;
this.company = company;
this.expertise = expertise;
this.writeCode = function() { console.log("Writing some public static thing.."); };
}In strict mode, the above pattern is required because this defaults to undefined instead of the global object.
'use strict';
function doSomething() { /* ... */ }The article has covered almost everything about functions in JavaScript, emphasizing that functions are first‑class citizens and essential for mastering the language.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
ITFLY8 Architecture Home
ITFLY8 Architecture Home - focused on architecture knowledge sharing and exchange, covering project management and product design. Includes large-scale distributed website architecture (high performance, high availability, caching, message queues...), design patterns, architecture patterns, big data, project management (SCRUM, PMP, Prince2), product design, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
