Functions help us to write less code and stop us from repeating our code.
In Javascript functions are first class citizens. As traditional programming languages are built around classes, Javascriptis built around functions.
Javascript functions are described with function keywords. There are mainly two ways in which we use function – declaration and expression.
Below are the ways we use functions in JavaScript.
This way is the common way to declare a function and is also used in other traditional languages like C, C++ and Java.
function addNum(a, b) { return a + b; } var sum = addNum(3, 5); console.log(sum); //8
Here, we declare a function addNum, which returns the sum of the two parameters passed.
Later we can call the function with any parameters and it will return their sum. We are storing the returned sum value in a variable called sum and in next line printing it.
Javascript functions can be defined in a different way and it is called function expressions. A function expression is stored in a variable and in it, we use an anonymous function(without a name) in it. We will refactor the function declaration to function expression.
var addNum = function (a, b) { return a + b; } var sum = addNum(3, 5); console.log(sum); //8
Javascript functions can also be defined with the built-in constructor called Function(). We will refactor the function declaration to function constructor.
var addNum = new Function ("a", "b", "return a + b"); var sum = addNum(3, 5); console.log(sum); //8
Hosting means we can use a variable even before declaring it. When the compiler runs and finds all the var declaration, it moves them to the top of the file.
Let’s consider this below example. Here we are assigning values to name, age and profession without declaring them first. They are declared on line 8, 9, 10 and yet the interpreter doesn’t throw a runtime error. It is because it doesn’t matter where the variables are declared. They are always hoisted to the top by when the compiler makes the first pass.
name = "Thomas"; age = 45; profession = "Engineering Manager"; console.log(`${name} aged ${age} is ${profession}`); //Thomas aged 45 is Engineering Manager var name; var age; var profession;
This is also true for a function declaration, as the compiler also treats function declaration as a variable declaration as in JS all function declaration are object declaration. But the same is not true for function expression and it will give reference error.
console.log(funcDeclaration()); //Function declaration console.log(funcExpression()); //ReferenceError function funcDeclaration() { console.log('Function declaration'); } let funcExpression = function() { console.log('Function expression'); } /* Exception: ReferenceError: can't access lexical declaration `funcExpression' before initialization @Scratchpad/7:2:1 */
Javascript IIFE (Immediately Invoked Function Expression) is nothing but a function expression, but it is defined and invoked at the same time. Here we had got rid of the addNum name itself and calling it also at the same time. Notice, that we are passing 2,3 immediately after the anonymous function is declared.
console.log((function(a, b) { return a + b; })(2, 3)); //5
When we look into the typeof of a function. It will return a function as shown in the below code.
function addNum(a, b) { return a + b; } console.log(typeof addNum); //function
But actually, everything is an object in JavaScript, including Objects. Functions are a type of object with two special properties, name and code. A function can be named or anonymous. If it’s named then the name will be stored in name property and the code we want to execute will be stored in code. When we try to invoke a function, Javascript will try to execute the code segment in the code property.
We can check the above function addNum in the console and it shows a special property name with value “addNum”.
Arrow functions were introduced in ES6 and provide a short syntax to write function expressions.
You don’t need the function keyword, the return keyword and also the curly brackets {}.
Note that the curly brackets and return statement are required if your function has more than one statement.
Also if there is only one parameter passed, we can omit the normal brackets().
Below are some of the example of old ES5 syntax and new ES6 syntax with an arrow function.
//ES5 var addNum = function (a, b) { return a + b; } //ES6 var addNum = (a, b) => a + b; //ES5 var printNum = function (a) { console.log('a is ', a); } //ES6 var printNum = a => console.log('a is ', a); //ES5 var multiplyNum = function () { var a = 10; var b = 20; return a * b; } //ES6 var multiplyNum = () => { var a = 10; var b = 20; return a * b; }
Javascript is a loosely typed language, so a function doesn’t perform any checking on the parameter values(arguments).
Let’s understand what is the difference between function parameters and arguments.
Function parameters are the names listed in the function definition. In the below example parameters are a and b listed in addNum.
Function arguments are the real values received by the function. In the below example we call addNum with 3 and 5 and it’s gets passed to the function. They are arguments in this case.
function addNum(a, b) { return a + b; } var sum = addNum(3, 5); console.log(sum); //8
In most programming languages like C, C++ and Java, function definitions specify the data type for parameters but not in JavaScript.
Similarly, Javascript functions do not perform type checking on the passed arguments and also the functions do not check the number of arguments received.
//C++ function int addNum(int a, int b) { return a + b; } //JS function function addNum(a, b) { return a + b; }
Parameter Default or Default parameters are the parameters, which are used if we don’t pass the value to that argument in a function while calling it.
Earlier to ES6, it was a bit difficult to handle a situation like this. In the below example if the user didn’t supply a value to an argument, we check inside the function “add” if “a” has a value or assign 0 to it. Same is done for “b”.
So, now we can handle all three situations successfully like when we pass no arguments, or pass the only the value of ‘a’ or pass only value of ‘b’.
var add = function(a, b) { a = a || 0; b = b || 0; return a + b; } //Passing no argument console.log(add()); //0 //Passing argument 'a' console.log(add(1)); //1 //Passing argument 'b' console.log(add(undefined, 2)); //2
The same can be done in ES6 by changing the parameter to contain the default value. Re-writing the above with ES6 default parameters.
var add = function(a=0, b=0) { return a + b; } //Passing no argument console.log(add()); //0 //Passing argument 'a' console.log(add(1)); //1 //Passing argument 'b' console.log(add(undefined, 2)); //2
Javascript functions have a built-in object called the argument object. The argument is an array like object, which contains all the arguments passed to the function.
It is very useful if we don’t know in advance the number of arguments passed to the function.
We will refactor our addNum function to add any number of arguments passed
function addNum() { var sum = 0; for (var i = 0; i < arguments.length; i++) { sum += arguments[i]; } return sum; } console.log(addNum(1,2)); //3 console.log(addNum(1,2,3)); //6 console.log(addNum(1,2,3,4)); //10
As told earlier the argument is an array like object and not array. So, it doesn’t have all advanced array method like reduce, filter and map. If we want to use those methods, we have to convert the arguments object to an array.
We convert it by taking an empty array and use its slice method. Then call it through call, by passing the argument Object. Then we can use reduce on it.
Below is the refactor of the above addNum code.
function addNum() { var arr = [].slice.call(arguments); return arr.reduce((curr, acc) => curr + acc); } console.log(addNum(1,2)); //3 console.log(addNum(1,2,3)); //6 console.log(addNum(1,2,3,4)); //10
Javascript functions are called in different ways. The code inside the function is executed when the function is invoked.
The most common way to call a function. We have been seeing it before in the course also.
An example is below and the line addNum(1,2) is where the function is invoked.
function addNum() { var sum = 0; for (var i = 0; i < arguments.length; i++) { sum += arguments[i]; } return sum; } console.log(addNum(1,2)); //3
Javascript“this” keyword simply means that whatever scope you are inside, it belongs to that. Now the scope can be a function or Object. Although, there are some exceptions to this rule, we can have “this” in various contexts. Let’s go through them.
“this” in a simple function
In a normal JS function like below, the “this” refers to the global window object.
function foo() { console.log(this); console.log(this === window); } foo();
Running the above code will give.
There is a special case with strict mode.
In strict mode “this” to be undefined, as global object refers to undefined instead of the window object.
function foo() { 'use strict'; console.log(this); console.log(this === window); } foo();
In Javascript, you can have functions as object properties. Check the below example, where we have a function fullDesc inside the object myObj.
var myObj = { firstName:"Harry", lastName: "Potter", occupation: "Wizard", fullDesc: function () { return this.firstName + " " + this.lastName + "- " + this.occupation; } } console.log(myObj.fullDesc()); //Harry Potter- Wizard
The fullDesc method is a function. The function belongs to the object myObj and it is the owner of the function.
The value of this is the object that "owns" the Javascript code. In this case, the value of this is myObj.
Let’s confirm the same by inserting a console log inside the function as shown below to check the value of this.
var myObj = { firstName:"Harry", lastName: "Potter", occupation: "Wizard", fullDesc: function () { console.log(this); return this.firstName + " " + this.lastName + "- " + this.occupation; } } console.log(myObj.fullDesc()); //Output - //Object { firstName: "Harry", lastName: "Potter", occupation: "Wizard", fullDesc: fullDesc() } //Harry Potter- Wizard
Let’s first understand what are Constructor functions. They are basically a Javascript way to implement the concept of Classes.
Let’s consider the example below, where we have a “Car” constructor function. In it, we have a “model”, which we are also returning by getModel(). Now we can create a new instance of it by using the “new” keyword. Each instance will have its own “this” and have its own getModel().
let Car = function(model) { this.model = model; this.getModel = function() { return this.model; } } let harryCar = new Car('toyota'); console.log(harryCar.getModel()); //toyota let maryCar = new Car('nissan'); console.log(maryCar.getModel()); //Nissan
“this” with constructor function
When a function is called with “new” keyword, it is known as a constructor function. And the value of “this” refers to the newly created instance.
Let’s confirm the same by inserting a console log inside the function as shown below to check the value of this.
let Car = function(model) { this.model = model; this.getModel = function() { console.log(this); return this.model; } } let harryCar = new Car('toyota'); console.log(harryCar.getModel()); //Output- //Object { model: "toyota", getModel: getModel() } //toyota
Every Javascript function has access to the call method. This method can be used to set the custom value of “this” to the execution context of the function.
Let’s say that we have an object called obj. It only has one property called num, which has a value of 3. Let’s also make a function called addNumbers.
Now, in addNumbers we have this.num. But how do we pass the value obj.num to it? We need to pass it a context, which means the value of “this”. We will do this my call method by passing the first argument as obj, so the “this” is the obj now.
let Car = function(model) { this.model = model; this.getModel = function() { console.log(this); return this.model; } } let harryCar = new Car('toyota'); console.log(harryCar.getModel()); //Output- //Object { model: "toyota", getModel: getModel() } //toyota
One of the main uses of “call” is to change an array-like object to array.
There is an array-like object arguments available for every normal function(not arrow function). It is very useful in functions, as we can get the number of arguments passed to it. Let’s convert the arguments into an array, because arrays have a lot of functionality.
Consider the example below, where we console log arguments. If we expand it in dev console, it shows it’s not an array and its __proto__ doesn’t have array functionalities.
let sumNumbers = function() { console.log(arguments); } sumNumbers(1, 2, 3, 4);
Now to convert it we will take an empty array and use its slice method. Then call it through call, by passing the argument Object. Now it is converted into an array and the __proto__ have all array functionalities. So, we are using the array reduce method available to do the sum of the number of arguments passed to it.
let sumNumbers = function() { const argsToArray = [].slice.call(arguments); console.log(argsToArray); return argsToArray.reduce((acc, curr) => acc + curr); } console.log(sumNumbers(1, 2, 3, 4)); //10 console.log(sumNumbers(1, 2, 3)); //6
The second application of call is in inheritance, using constructor functions.
Consider the below example. Here in the Cat function, we called its parent Mammal using the call method with “this” of Cat.
let Mammal = function(legs) { this.legs = legs; } let Cat = function(legs, isDomesticated) { Mammal.call(this, legs); this.isDomesticated = isDomesticated; } let tiger = new Cat(4, false); let homeCat = new Cat(4, true); console.log(tiger); // { legs: 4, isDomesticated: false } console.log(homeCat); // { legs: 4, isDomesticated: true }
Every Javascript functions also have access to the apply method. This method can be used to set the custom value of “this” to the execution context of the function.
It is quite similar to the “call” method, but the only difference is that we can pass an array as the second argument. We will use the same code to apply also. But now we have an arr, to be passed as the second argument.
let obj = {num: 3}; let addNumbers = function(a, b, c){ return this.num + a + b + c; }; let arr = [7, 3, 8]; console.log(addNumbers.apply(obj, arr)); //21
One of the practical uses of apply is to pass an array to a function, which expects arguments only.
Consider the case of Math.max, which gives the maximum of the arguments passed. So, now to pass an array like below code, we convert it through apply. Note the first argument is null because we are not passing any Object for “this” binding.
let arr = [20, 6, 29, 12]; console.log(Math.max(20, 6, 29, 12)); // 29 console.log(Math.max.apply(null, arr)); // 29
Every Javascript Closures are everywhere. Closures are basically, the inner function having access to the variables in the outer function scope, even after the outer function has returned. To use a closure, simply define a function inside another function and expose it. To expose a function, return it.
Consider the below code. The variable b has a scope in outer function i.e. from line 4 to line 10. So, at line 13 when we call the outer function, it can access the value of b, but at line 14 there is no outer function.
So, how does the innerFn() access the value of b? This is where the JS feature of Closures comes into play.
When the “var inner” is created at line 6, the JS engine not only stores the function object information but also its scope information. So, it stores a scope of variable b inside the inner function object.
Now it doesn’t matter where you call inner, whether in this file or some third-party file. It will always remember the value of a and b as if a snapshot has been taken.
var a = 10; function outer() { var b = 20; var inner = function() { console.log(a); console.log(b); }; return inner; } var innerFn = outer(); innerFn(); //Output //10 //20
I have learned many things from this article. It is beneficial for me. Thank you!
Nice example for beginners.. I m a beginner so this is very helpful for me ... so plz give this type of beginners example..
This is a great introduction to variables in JavaScript! As a beginner to JavaScript, I found this guide very helpful in understanding the basics of variables and how they are used in JavaScript.
Thanks for sharing the information, it is very helpful, I hope to get more such beautiful blogs from you.
You have shared great information with me i appreciate your work!
Build various types of web applications,command-line application,etc....
Introduction: Angular (What is Angular?)Angular was formerly introdu...
Leave a Reply
Your email address will not be published. Required fields are marked *