Why doesn't a ReferenceError link occur if a variable is used before it is declared?

I am trying to wrap my head around the behavior of referenced errors created in JavaScript.

In the following example, a is ReferenceErrorthrown into the second line, and execution is aborted:

var obj = {};
obj.func1 = func2;

alert('Completed');

In this example, the code succeeds, although it obj.func1remains undefined:

var obj = {};
obj.func1 = func2;

var func2 = function() {
    alert('func2');
};

alert('Completed');

My guess was that the second line would have the same error, and when it wasn’t, Id expected it obj.func1to refer to correctly func2, but Ive been double blind. So what exactly is going on here?

+4
source share
3 answers

var ; . , :

var obj;
var func2;

obj = {};
obj.func1 = func2;
func2 = function() {
    alert('func2');
}

alert('Completed');

, , func2 , undefined. , ReferenceError.

+3

Javascript "hoisting".

, var, , Reference Error. , , , . , :

var func2;
var obj = {};
obj.func1 = func2;

func2 = function() {
    alert('func2');
};

alert('Completed');

, , obj.func1. , undefined obj.func1. func2 .

+4

Your func2 variable is not displayed. This is why obj.func1 remains undefined.

var obj = {};
var func2 = function() {
    alert('func2');
    return "Test";
};
    
obj.func1 = func2;
   
alert('Completed');
Run codeHide result
+1
source

Source: https://habr.com/ru/post/1629306/


All Articles