hoisting

作者: Time_Notes | 来源:发表于2023-08-02 14:00 被阅读0次

https://www.freecodecamp.org/news/javascript-execution-context-and-hoisting/

Hoisting is the process whereby the interpreter moves the declaration of functions, variables, or classes to the top of their scope, prior to execution of the code.

https://www.freecodecamp.org/news/javascript-execution-context-and-hoisting/

So let's understand Hoisting using the concept of the Execution Context.


function fn(){

    console.log(a); //undefined;

    var a = 1;

}

fn();

declaration hoisting

const a=1

console.log(a)// 1

var b

console.log(b)// undefined

b=2 

console.log(c)// undefined

var c=3

console.log(d)// Error

let d=2

1. Straightforward as a is 1

2. b is declared but not initialized so it prints undefined

3. JavaScript only hoists declarations, not initializations! This means that initialization doesn't happen until the associated line of code is executed. Hence, JS knows that c exists but its undefined at the point of printing its value

4. Variables declared with let and const are also hoisted but, unlike var, are not initialized with a default value. Accessing the variable before the declaration results in a ReferenceError. Read more about Temporal Dead Zone

1.var,let and const are hoisted.

2.var is declared and initialized as undefined during hoisting

3.let is declared but not initialized. accessing the uninitialized variable gives reference error

4. const must be initialized


Variable Hoisting in JavaScript

Please have a look at the example below and guess the output:

console.log(name);

var name;

I'm sure you guessed it already. It's the following:

undefined

However, the question is why? Suppose we use similar code in some other programming language. In that case, we may get an error saying the variable name is not declared, and we are trying to access it well before that. The answer lies in the execution context.

In the creation phase,

The memory gets allocated for the variable name, and

A special value undefined is assigned to the variable.

In the execution phase,

The console.log(name) statement will execute.

This mechanism of allocating memory for variables and initializing with the value undefined at the execution context's creation phase is called Variable Hoisting.

The special value undefined means that a variable is declared but no value is assigned.

If we assign the variable a value like this:

name='freeCodeCamp';

The execution phase will assign this value to the variable.


Function Hoisting in JavaScript

Now let's talk about Function Hoisting. It follows the same pattern as Variable Hoisting.

The creation phase of the execution context puts the function declaration into the memory, and the execution phase executes it. Please have a look at the example below:

// Invoke the function functionA

functionA();

// Declare the function functionA

function functionA(){

console.log('Function A');

// Invoke the function FunctionB    

functionB();

}

// Declare the function FunctionB

function functionB(){console.log('Function B');}

The output is the following:

Function A

Function B

The execution context creates the memory for the function and puts the entire function declaration of functionA in it.

The functions create their own execution context. So a similar thing happens for functionB as well.

Next, the functions get executed in their execution context respectively.

Putting the entire function declaration ahead into the memory at the creation phase is called Function Hoisting.


Hoisting is only for function declaration, not initialization. Here is an example of function initialization where the code execution will break.

logMe();

var logMe=function(){console.log('Logging...');}

The code execution will break because with function initialization, the variable logMe will be hoisted as a variable, not as function. So with variable hoisting, memory allocation will happen with the initialization with undefined. That's the reason we will get the error:

Error in hoisting a function initialization

Suppose we try to access a variable ahead of declaration and use the let and const keywords to declare it later. In that case, they will be hoisted but not assigned with the default undefined. Accessing such variables will result in the ReferenceError. Here is an example:

console.log(name);

let name;

It will throw the error:

Error with hoisting variable declared with let and const keywords

The same code will run without a problem if we use var instead of let and const. This error is a safeguard mechanism from the JavaScript language as we have discussed already, as accidental hoisting may cause unnecessary troubles.

函数声明提升,函数表达式不提升 函数优先提升

在上下文creation stage,函数先于变量之前创建;并且如果上下文中一个变量名称的属性名已经存在,就会忽略掉这个变量声明。


在for、if、while等语句内部的声明的var变量与在外部声明是一样的,在这些语句外部也可以访问和修改这些变量的值。

function fun(){

    if(0<2){

        var name ="jeri";

    }   

    console.log(name); //输出:jeri

    name ="change";

    console.log(name);// 输出:change

  }

fun();


if(false){

    var num=123;

}

console.log(num);//undefined

相关文章

网友评论

      本文标题:hoisting

      本文链接:https://www.haomeiwen.com/subject/njpvldtx.html