Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expecting undefined in Javascript

Tags:

javascript

I was seeing some Javascript code and I stumbled upon something like this:

function() {
    if(true) {
        var a = 5;
    }
    alert(a);
}

I was pretty sure this would output undefined but it didn't ? Can someone tell me why?

like image 762
John Doherty Avatar asked Jun 05 '14 15:06

John Doherty


People also ask

What is an undefined in JavaScript?

A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .

Does undefined exist in JavaScript?

An undefined variable or anything without a value will always return "undefined" in JavaScript. This is not the same as null, despite the fact that both imply an empty state. You'll typically assign a value to a variable after you declare it, but this is not always the case.

Is undefined or null JavaScript?

Definition: Null: It is the intentional absence of the value. It is one of the primitive values of JavaScript. Undefined: It means the value does not exist in the compiler.


2 Answers

JavaScript has function level scope, not block level scope.

The var statement is hoisted so your code is equivalent to:

function() {
    var a;
    if(true) {
        a = 5;
    }
    alert(a);
}

If JavaScript had block level scope, then it still wouldn't output undefined. Since a would be undeclared in the alert statement, you would trigger a reference error.

like image 161
Quentin Avatar answered Nov 16 '22 01:11

Quentin


The reason this works is a result of what is called hoisting. Hoisting moves the declaration of the variable to the top of the scope. So your function really looks like this:

function() {
 var a;
 if(true) {
  a = 5;
 }
 alert(a);
}

"Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behaviour is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code." - var MDN

like image 41
Travis J Avatar answered Nov 16 '22 03:11

Travis J