manjum2050
manjum2050

Reputation: 43

why do i get "Uncaught ReferenceError" even though variable is declared without "var" keyword?

I have come across the following code snippet:

(function() {
    bar = 5;
    var bar = 10;
    console.log("value of bar inside the self invoking function = " + bar);
})();
console.log("value of bar out of function scope " + bar);

When I execute the above code, I get:

"Uncaught ReferenceError"

for the second console

Upvotes: 1

Views: 125

Answers (2)

Hardik Modha
Hardik Modha

Reputation: 12736

All variables declared with var are hoisted to the top of the function in which they are declared, So if the variable is defined inside the function it will be moved to the top of the function and if it is defined in global scope, it will be moved to the top of the global context.

(function() {
    bar = 5;
    var bar = 10;
    console.log("value of bar inside the self invoking function = " + bar);
})();

Here, in your case you have defined variable inside the anonymous function, so it will be moved to the top of this function and after hoisting it will be something like

(function() {
    var bar;
    bar = 5;
    bar = 10;
    //...rest of the code
})();

But this variable is available only in that function's local scope, it won't be available in the global scope. That's why you are getting Uncaught ReferenceError when you are trying to access it in global scope.

Here is the nice article explaining variable scope and variable hoisting in JavaScript. http://javascriptissexy.com/javascript-variable-scope-and-hoisting-explained/

One thing to note is that only the variables declared using var are hoisted. If you are using ES6 let keyword to declare a variable then it will not be hoisted. So

(function() {
    bar = 5;
    let bar = 10;
    console.log("value of bar inside the self invoking function = " + bar);
})();

won't work and you'll get the same error. You can read more about it here

Upvotes: 0

Karl-Johan Sjögren
Karl-Johan Sjögren

Reputation: 17522

This is due to "variable hoisting". Variables are declared when the javascript is parsed so when it comes to execution the engine already knows all variables that will be available within a scope and can thus assign to them. After the hoisting process is done your function actually looks like this.

(function() {
    var bar;
    bar = 5;
    bar = 10;
    console.log("value of bar inside the self invoking function = " + bar);
})();

console.log("value of bar out of function scope " + bar);

You can read more about it on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting

Upvotes: 6

Related Questions