Tuesday, August 24, 2021

What is hoisting in javascript?

 The javascript function and variable are available in execution context before execution is know as hoisting.

Ex:

function calculateAge(year){

    console.log(2021-year);

}

calculateAge(1989);

Here we declare a function the we call it .it works fine.

but what if we call the function before define it -

calculateAge(1989);

function calculateAge(year){

    console.log(2021-year);

}

it will work too because of hoisting . In the creation phase of execution context the function declaration is stored in the variable object ,In this case global execution context .

Hoisting will not work for function expression-

Ex:

calculateAge(1989);

var calculateAge=function (year){

    console.log(2021-year);

}

it will show error.

Hoisting in variable.

console.log(age);

var age=32;

console.log(age);

output will be:

undefined

32

because in the creation phase of variable object the code is scanned for variable declaration and set them to undefined.

No comments:

Post a Comment

Fluent interface pattern

 public class UserConfigurationManager {     private String userName;     private String password;     private UserConfigurationManager() { ...