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 because normal function call.

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 calculateAge because it is function expression.

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

Javascript module

JavaScript Modules (ES6) let you split code into multiple files and reuse code cleanly. Main keywords: export → make something available...