How to use call(), apply(), bind() in JavaScript?

In JavaScript objects have their own properties and methods. With every function we have three methods: call(), apply() and bind().

Before moving into this concept, first lets have a recap on this in functions. This keyword determines how a function is called (runtime binding).

There is a feature in JavaScript which allows to use the methods of some other objects to another object without redefining them. This way of borrowing is done through call(), apply(), bind() methods.

Call(), apply(), and bind() methods are used to set the this keyword independent of function call. Useful in callbacks.

Call():

Call method sets the this inside function and immediately executes the function. Here you can pass arguments as a list.

Syntax:

function.call(thisArg, arg1, arg2, …)

function – function that needs to be invoked with different this object.

thisArg – value that needs to be replaced with this keyword present inside this function.

arg1,arg2,… – arguments passed for invoking function with this.

Example:
 function test(arg1, arg2){
   console.log(this.num, arg1, arg2); // 100, 10, 20
}

test.call({num: 100}, 10, 20);
Output:

100,10,20

apply()

apply() method binds the this value to the function and executes the function. Here  you can pass argument as an array.

Syntax:
function.apply(this, [argumentsArray])

It returns the result of the function which is invoked by this.

function test(...args){
  console.log(this.num, args);//100, [1,2,3]
}
test.apply({num: 100}, [1,2,3]);
Output:

100, [1,2,3]

Bind()

Bind() function binds this value to the function and returns new function. We need to invoke the returned function separately.

Syntax:
function.bind(this,arg1,arg2,arg3,...)

Bind returns a copy of function with this and arguments.

function test(arg){

 console.log(this.number, arg);

}

let bindedFn = test.bind({number: 1}, "Abaython");

bindedFn();
Output:

1 Abaython

Differences : call() vs apply() vs bind()

call()apply()bind()
DefinitionCall method is a predefined javascript method. With call an object can use a method belonging to another object. Here we supply list of argumentsSimilar to call(). But here we supply array of argumentsBind() helps in creating another function and execute later with new this function
ExecutionAt time of bindingAt time of bindingAt time when we execute the return function
Return?Yes it returns and calls the same function at time of bindingYes it returns and calls the same function at time of bindingYes it returns a new function of copy of function which can be used later.
ParameterList of argumentsArray of argumentsArray and any number of arguments

Key points to note:

  • call: binds the this value, invokes the function, and allows you to pass a list of arguments.
  • apply: binds the this value, invokes the function, and allows you to pass arguments as an array.
  • bind: binds the this value, returns a new function, and allows you to pass in a list of arguments.

How to destructure arrays and objects in JavaScript?

Before getting into destructuring, lets have a quick recap on arrays and objects.

  • Objects allows us to create a single entity that gather data items by key.

const emp = {

  name: “Anna”,

  id: “101”,

};

  • Array allows us to gather data items into an ordered list.

const emp = [“Anna”,”Tina”,”Tim”];

Destructuring introduced in ES6 allows us to unpack elements in an array or elements. It extracts multiple properties, items and values from an array or object into a separate variable.

Object Destructuring:

Syntax:
let { var1,var2} ={var1:val1, var2:val2}

To destruct object we use curly braces { }

Consider you have a student object with properties firstname and lastname.

let student = {

    firstname: "Anna",

    lastname: "Hills"

};
Prior to ES6:

For assigning properties and values to variables we have,

let student = {

    firstname: “Anna”,

    lastname: “Hills”

};

let firstName = student.firstname;

let lastName = student.lastname;

console.log(firstName);

console.log(lastName);

From ES6:
// assigning object attributes to variables
let student = {
    firstname: "Anna",
    lastname: "Hills"
};
// destructuring assignment
let { firstname, lastname} = student;
console.log(firstname); // Anna
console.log(lastname); // Hills
In the above example we have used the same variable names.
How to assign new variable name?
// assigning object attributes to variables
let student = {
    firstname: "Anna",
    lastname: "Hills"
};
// destructuring assignment to new variable
let { firstname:fname, lastname:lname} = student;
console.log(fname); // Anna
console.log(lname); // Hills

The order of the name in the object is not important we can also write as,

let {lastname, firstname} = student;
How to assign default values?

We can pass default values as follows,

let student = {
    firstname: "Anna",
    lastname: "Hills"
};
let { firstname, lastname, age = 22} = student;
console.log(age); //22
Output:

22

How to assign multiple object properties to single variable?
const student = {
    firstname: 'Anna',
    lastname: 'Hills',
    age: 25,
    gender: 'female'    
}
// destructuring assignment
// assigning remaining properties to rest
let { firstname, ...details } = student;

console.log(firstname); // Anna
console.log(details); // {lastname: 'Hills', age: 25, gender: 'female'}
Output:

Anna

{ lastname: ‘Hills’, age: 25, gender: ‘female’ }

Nested destructuring in objects:

In order to execute the nested destructuring assignment for objects, you have to enclose the variables in an object structure (by enclosing inside {}).

const student = {
    name: 'Anna',
    age: 26,
    details: {
        course: 'Javascript',
        fee: 2500
    }
}
// nested destructuring 
const {name, details: {course, fee}} = student;
console.log(name); // Anna
console.log(course); // Javascript
console.log(fee); // 2500
Output:

Anna

Javascript

2500

Array destructuring:

To destruct arrays we use square brackets [ ].

Syntax:
const [var1,var2,…] = arrayName;
Example:
const arrValue = ['Anna', 'Tina', 'Lena'];

// destructuring assignment in arrays
const [x, y, z] = arrValue;

console.log(x); 
console.log(y); 
console.log(z); 
Output:

Anna

Tina

Lena

How to assign default values?
let arr1 = [20];
// assigning default value 5 and 7
let [x = 10,  y = 9] = arr1;
console.log(x); // 20
console.log(y); // 9

In the above array we have one element so when we assign default values only y=9 is assigned and x=20 remains the same.

Output:

20

9

How to swap variables using destructuring assignment?
// program to swap variables
let x = 10;
let y = 20;
// swapping variables
[x, y] = [y, x];
console.log(x); // 20
console.log(y); // 10
Output:

20

10

How to skip assigning unwanted items in an array?

We can skip assigning unwanted items in an array to a local variable using comma ( , )

const arr1 = ['one', 'two', 'three'];
// destructuring assignment in arrays
const [x, , z] = arr1;
console.log(x); // one
console.log(z); // three
Output:

one

three

How to assign multiple elements to a single variable?

We can assign multiple elements to a single variable using spread syntax …

const arr1 = ['one', 'two', 'three', 'four'];
// destructuring assignment in arrays
// assigning remaining elements to y
const [x, ...y] = arr1;
console.log(x); // one
console.log(y); // ["two", "three", "four"]
Output:

one

[ ‘two’, ‘three’, ‘four’ ]

one is assigned to x variable. Rest of the elements are assigned to y variable.

Nested Destructuring Assignment in arrays:

In order to execute the nested destructuring assignment, you have to enclose the variables in an array structure (by enclosing inside []).

Nested destructuring in arrays is

// nested array elements
const arr1 = ['one', ['two', 'three', 'four']];
// nested destructuring assignment in arrays
const [a, [b, c, d]] = arr1;
console.log(a); // one
console.log(b); // two
console.log(c); // three
console.log(d); // four
Output:

one

two

three

four

Destructuring allows for instantly mapping an object or array to many variables.

Array Data Structure – What you should know?

Already in previous post we have seen about the Data Strucutres in JavaScript. Now we will jump into the creation and implementation of arrays.

As you already know, array represents collection of similar data items. It is an object that stores multiple data items.

 Array Declaration:

By array literal

Simplest way to create an array is by using array literal [ ].

Syntax:

               let arrayname = [value1, value2, value3,….]

By new keyword
Syntax:

               let arrayname = new Array();

//creates an array with 6 elements using array literal
var arr1 = [2,3,1,4,5,7];
//create array using new keyword
var arr2 = new Array(1,3,5,7,9,0);
//create an array with undefined elements
var arr3 = new Array();
//provide elements in arr3
arr3[0] = "Apple";
arr3[1] = "Orange";
arr3[2] = "Banana";
//create an array with 2 elements
var arr4 = new Array("Tom","Paul");
console.log(arr1);
console.log(arr2);
console.log(arr3);
console.log(arr4);
Output:
Accessing arrays:

Elements of an array are accessed using indexes.

var arr1 = [2,3,1,4,5,7];
//first element
console.log(arr1[0]);
//fourth element
console.log(arr1[3]);
Output:

2

4

Adding elements to an array:

We use push() and unshift( ) methods to add elements to an array.

push() method adds elements to the end of an array.

unshift() method adds elements to the start of an array.

let fruits = ["apple","orange"];
//using push() method
fruits.push("banana");
//using unshift() method
fruits.unshift("grapes");
console.log(fruits);
Output:

Now what will happen to the above array fruits if we try to add an element at index 5 rather than index 4?

Let’s see,

let fruits = ["grapes","apple","orange","banana"];
//add element at index 5
fruits[5]="strawberry";
console.log(fruits);
Output:

So index 4 will be undefined.

Remove an element from an array:

Here also we can remove from start or end using pop() and shift() methods.

pop() removes the last element

shift() removes the first element

let fruits = ["grapes","apple","orange","banana"];
//pop() method
frutis.pop();
console.log(fruits);
//shift() method
console.log(fruits);
Output:
How to find the length of an array?

It is done by length property. Returns the number of elements in an array.

let fruits = ["grapes","apple","orange","banana"];
console.log(fruits.length);
Output:

4

Methods in an array data structure:

In JavaScript arrays there are various methods available.

MethodsDescription
concat()joins two or more arrays and returns a result
indexOf()searches an element of an array and returns its position
find()returns the first value of an array element that passes a test
findIndex()returns the first index of an array element that passes a test
forEach()calls a function for each element
includes()checks if an array contains a specified element
push()adds a new element to the end of an array and returns the new length of an array
unshift()adds a new element to the beginning of an array and returns the new length of an array
pop()removes the last element of an array and returns the removed element
shift()removes the first element of an array and returns the removed element
sort()sorts the elements alphabetically in strings and in ascending order
slice()selects the part of an array and returns the new array
splice()removes or replaces existing elements and/or adds new elements
let fruits = ["grapes","apple","orange","banana"];
//sort in alphabetical order
fruits.sort();
console.log(fruits);
//find the index position
const pos = fruits.indexOf("apple");
console.log(pos);
//slicing array
const frutis1 = fruits.slice(2)
console.log(fruits1);
//concat two arrays
const frutis2 = frutis.concat(fruits1);
Output: