Is parsing javascript executed from top to bottom?

First, the declaration takes precedence

js is executed line by line from top to bottom, which is not entirely correct, consider the following code:

a = 2;

var a;

console.log(a);

What is the input result? is not undefined, the output is 2

==============

Consider the following code:

console.log(a);

var a = 2;

This code you might think will throw the exception ReferenceError? However, the output is undefined

===============

The js engine has two steps, compiling and running. The correct thinking is that all declarations, including variables and functions, will be processed first when any code is executed.

So the first code snippet is actually handled as follows:

var a;

a = 2;

console.log(a);

The second code snippet is actually the following flow:

var a;

console.log(a);

a = 2;

==================

Function declarations are hoisted, but function expressions are not:

foo(); // TypeError exception

var foo = function(){

    //dosomething...

}

2. Function priority

Both function declarations and variable declarations are hoisted, but function declarations are hoisted first, followed by variable declarations. The following code:

foo();

var foo;

function foo(){

    console.log(1)

}

foo = function(){

    console.log(2);

}

The result will output 1 instead of 2. The js engine understands this code as follows:

function foo(){

    console.log(1);

}

foo();

foo = function(){

    console.log(2);

}

Note: Although var foo appears before the declaration of function foo()..., it is a duplicate declaration and is ignored here because the function declaration comes before the variable declaration

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325527699&siteId=291194637