What is the purpose of the var keyword and when should I use it (or omit it)?
Asked Answered
D

19

1661

NOTE: This question was asked from the viewpoint of ECMAScript version 3 or 5. The answers might become outdated with the introduction of new features in the release of ECMAScript 6.

What exactly is the function of the var keyword in JavaScript, and what is the difference between

var someNumber = 2;
var someFunction = function() { doSomething; }
var someObject = { }
var someObject.someProperty = 5;

and

someNumber = 2;
someFunction = function() { doSomething; }
someObject = { }
someObject.someProperty = 5;

?

When would you use either one, and why/what does it do?

Drunken answered 24/9, 2009 at 8:54 Comment(8)
When chaining var declarations, does putting a newline after a comma affects the behavior? var x=1, y=2, [return]z=3;Nose
Failing to use "var" also leaves you exposed in case the variable name you chose happens to be a previously defined global variable. See my journey of grief here: #16704514Healing
@Ray Toal's meloncard blog post (definitely worth a read) has moved to blog.safeshepherd.com/23/how-one-missing-var-ruined-our-launchKaisership
I'd never imagined a poem could inspire me consideration for a programmatic problemAlmsgiver
Use const and let instead! var is not modern JSGuanaco
@Guanaco but look at the question date, it's a kinda unfair summon a 2009 question to tell that. Even though, it's still valid as in current date for maintainability, there are out there a bunch of not "modern JS" code.Oleg
The hope is that someone reading my comment who is new to JS (likely if searching for this) will learn early. Just because "non-modern" code exists, doesn't mean we should keep pushing it as the correct answerGuanaco
Note that in modern JavaScript you should usually use let instead of var (due to the differences in how let and var behave).Accrete
F
1409

If you're in the global scope then there's not much difference. Read Kangax's answer for explanation

If you're in a function then var will create a local variable, "no var" will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it):

// These are both globals
var foo = 1;
bar = 2;

function()
{
    var foo = 1; // Local
    bar = 2;     // Global

    // Execute an anonymous function
    (function()
    {
        var wibble = 1; // Local
        foo = 2; // Inherits from scope above (creating a closure)
        moo = 3; // Global
    }())
}

If you're not doing an assignment then you need to use var:

var x; // Declare x
Foofaraw answered 24/9, 2009 at 8:55 Comment(15)
Is "not really much difference" == "No Difference"?Drunken
Well, actually yes, there's difference :) Whether that difference is important is another question. See my answer further down: #1470988Nashner
I think that may be Alex's point, which is why he's written it using the "is equal to" operator!Crunode
It's like shooting oneself with a railgun... Forget to put a 'var' before one's variable, and end up modifying a variable somewhere in the scope chain... Try convincing a Java/C/Python/etc. developer that JavaScript is worthwhile. Ha! C/C++ pitfalls look nice by contrast. Imagine having to debug JavaScript... And some people do that, of course. And there's so much code (and not simple code, mind you) written in JavaScript...Florenceflorencia
If you're in the global scope then there's no difference. >> there is a difference which is explained in the answer belowCarman
@Drunken 0 == false, so yes "not really much difference" == "No Difference" however "not really much difference" !== "No Difference"Cheltenham
If in strict mode, even in the global scope, you'll need var to declare it.Ligetti
if you 'use strict';, then you should use var.Mucoviscidosis
this is important if you want to keep with the public api / private members of the module pattern. understanding that var will place objects in the local scope of the module is essential. thanks for the explanation. also of note if i'm correct, function x() is equivalent to var x = function() and differs from x = function() with regard to scoping.Leadsman
Thank you so much. I have been struggling with this for ages, then I read this line: 'If you're in a function then "var" will create a local variable, "no var" will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it)' - perfect explanation, thanks.Glazunov
what do you mean by "Creating a Closure"?Bangle
This is a big difference: variables declared with var exist before execution commences, those that aren't don't exist until the statement that creates them is executed. Also, those declared with var are not deletable, whereas those that aren't are deletable properties of the global object. Also, the anonymous function creates closures to all the outer variables, not just the global ones (i.e. it has a closure to foo, bar and moo.Scatology
See also #38270970 for an interesting example of a more subtle difference between the two declarations.Ashjian
Phrase "...at which point it will create it" has very ambiguous wording - my question is still unsolved. Is that point related to logic flow? (e.g. "not found anywhere, so created.. locally") Or is point related to the scope, at which variable is created? (e.g "variable searched up to global scope, not found even there, so created there"). Could you reword it a bit, please?Energize
For C++ code int i=1; { cout<<i; int i=2; cout<<i; } cout<<i; output would be: 121. Is it a var- or var-less behavior?Energize
N
773

There's a difference.

var x = 1 declares variable x in current scope (aka execution context). If the declaration appears in a function - a local variable is declared; if it's in global scope - a global variable is declared.

x = 1, on the other hand, is merely a property assignment. It first tries to resolve x against scope chain. If it finds it anywhere in that scope chain, it performs assignment; if it doesn't find x, only then does it creates x property on a global object (which is a top level object in a scope chain).

Now, notice that it doesn't declare a global variable, it creates a global property.

The difference between the two is subtle and might be confusing unless you understand that variable declarations also create properties (only on a Variable Object) and that every property in Javascript (well, ECMAScript) have certain flags that describe their properties - ReadOnly, DontEnum and DontDelete.

Since variable declaration creates property with the DontDelete flag, the difference between var x = 1 and x = 1 (when executed in global scope) is that the former one - variable declaration - creates the DontDelete'able property, and latter one doesn't. As a consequence, the property created via this implicit assignment can then be deleted from the global object, and the former one - the one created via variable declaration - cannot be deleted.

But this is just theory of course, and in practice there are even more differences between the two, due to various bugs in implementations (such as those from IE).

Hope it all makes sense : )


[Update 2010/12/16]

In ES5 (ECMAScript 5; recently standardized, 5th edition of the language) there's a so-called "strict mode" — an opt-in language mode, which slightly changes the behavior of undeclared assignments. In strict mode, assignment to an undeclared identifier is a ReferenceError. The rationale for this was to catch accidental assignments, preventing creation of undesired global properties. Some of the newer browsers have already started rolling support for strict mode. See, for example, my compat table.

Nashner answered 24/9, 2009 at 13:38 Comment(11)
If I recall correctly, I think I once found a way to be able to delete a var-declared variable with some eval hack. If I remember the exact trick I'll post here.Actinia
@Mageek He might be taking about eval-declared variables which are deletable. I wrote a blog post about this once.Nashner
Little bit out of topic, but mentioning it here for reference. "let" is very similar to "var" and is supported in Mozilla. The main difference is that the scope of a var variable is the entire enclosing function where as "let" is restricted to its blockAlienable
@Nashner what if the last two lines of Alex's examples were mixed: var someObject = {} and someObject.someProperty = 5 ? Would someProperty become global, while the object it is a property of remains local?Damask
The spec name for what @Nashner calls the DontDelete flag is configurable (= false), you can read about this in regards to Object.defineProperty and Object.getOwnPropertyDescriptorNebulosity
in some IE versions there's a bug allowing you to delete a variable declaration in the global scopeVastha
@Vastha I recall something like that. I think only with variables that "shadow" (have same name as) global built-ins, but I'm not sure.Nashner
I am not near a computer now, but if memory serves me right I tried it with var x = 0; and IE didn't stop me from deleting it.Vastha
It would be nice to see an additional update to this answer that details how let factors into the OPs question.Fedak
@Fedak let doesn't affect x = 1 part of the answer so the only difference is in var x = 1 vs. let x = 1. This has been documented many times in many places but the 2 main differences are that let is block-scoped and creates TDZ (temporal dead zone), meaning that you can't use or even reference it before declaration.Nashner
@Nashner I get that. I'm just saying that if someone who has never even heard of let comes across this answer, it would be good to just mention let and link off to another source of information so they can read up.Fedak
S
142

Saying it's the difference between "local and global" isn't entirely accurate.

It might be better to think of it as the difference between "local and nearest". The nearest can surely be global, but that won't always be the case.

/* global scope */
var local = true;
var global = true;

function outer() {
    /* local scope */
    var local = true;
    var global = false;

    /* nearest scope = outer */
    local = !global;

    function inner() {
        /* nearest scope = outer */
        local = false;
        global = false;

        /* nearest scope = undefined */
        /* defaults to defining a global */
        public = global;
    }
}
Shaunna answered 24/9, 2009 at 9:50 Comment(3)
Isn't the nearest scope outer where you define var global = false;?Fedak
@Snekse: 'nearest' doesn't apply when <code>var global = false;</code> is declared. In that declaration, 'global' is placed in the scope of outer() because 'var' is used in the declaration. Because 'var' is not used in inner(), it will change the value in the next level up, which is outer().Vie
I wonder if you comment would change if you changed that line to var global = local; in which case the nears scope of local would be the "local" outer scope that is actively being defined. Though it gets strange if you would change that same line to var global = global in which case the nearest scope when searching for the value of global would be up a level at the global window scope.Fedak
M
85

When Javascript is executed in a browser, all your code is surrounded by a with statement, like so:

with (window) {
    //Your code
}

More info on with - MDN

Since var declares a variable in the current scope , there is no difference between declaring var inside window and not declaring it at all.

The difference comes when you're not directly inside the window, e.g. inside a function or inside a block.

Using var lets you hide external variables that have the same name. In this way you can simulate a "private" variable, but that's another topic.

A rule of thumb is to always use var, because otherwise you run the risk of introducing subtle bugs.

EDIT: After the critiques I received, I would like to emphasize the following:

  • var declares a variable in the current scope
  • The global scope is window
  • Not using var implicitly declares var in the global scope (window)
  • Declaring a variable in the global scope (window) using var is the same as omitting it.
  • Declaring a variable in scopes different from window using var is not the same thing as declaring a variable without var
  • Always declare var explicitly because it's good practice
Marika answered 24/9, 2009 at 9:17 Comment(6)
I didn't downvote you, but scope is probably a better word than window. You're whole explanation is a bit obtuse.Matos
I simply call things with it's name, you want to call it "global scope", it's ok, but client-side, by convention, is the window object, that is the last element of the scope chain, that why you can call every function and every object in window without write "window."Marika
+1 this is a really nice explanation--i have not heard the var/no var issue framed (no pun intended) like this before.Linoel
Most of this answer is deprecated with let in ES6.Borras
@EvanCarroll This answer is also technically incorrect since omitting var doesn't declare any variable, instead it creates a deletable property on the global object, besides with ES5 "use strict" mode most of the answer is obviously not correct, also let wasn't even considered in this answer since at the time of the question there wasn't any reference to the javascript version (added yesterday) which imply that the standard of reference (at that time) was ECMA 262 3rd Edition.Marika
The statement "all your code is surrounded by a with statement" is plain wrong. If that were true, variable names would be resolved on the window object before the local scope.Scatology
P
51

Always use the var keyword to declare variables. Why? Good coding practice should be enough of a reason in itself, but omitting it means it is declared in the global scope (a variable like this is called an "implied" global). Douglas Crockford recommends never using implied globals, and according to the Apple JavaScript Coding Guidelines:

Any variable created without the var keyword is created at the global scope and is not garbage collected when the function returns (because it doesn’t go out of scope), presenting the opportunity for a memory leak.

Patriliny answered 24/9, 2009 at 9:52 Comment(3)
"Good coding practice" should never be sufficient reason in itself. It amounts to "some guys on the internet said this is how my code should look". That's even less valid than "my teacher said", unless one at least vaguely understands the reason behind the rule.Kcal
@Kcal I think good coding practice is always sufficient reason if it's a recommended best practice, which this is and by several Javascript authors.Glide
@ChrisS: No, "good coding practice" is not reason in itself. The reason it's considered good practice is what matters. Unless those authors tell you why they recommend it, their recommendation should carry no weight whatsoever. If you don't agree with the reasons, then you are free to consider it bad advice. And if you follow it without ever asking why, that is how cargo cultism starts.Kcal
G
33

Here's quite a good example of how you can get caught out from not declaring local variables with var:

<script>
one();

function one()
{
    for (i = 0;i < 10;i++)
    {
        two();
        alert(i);
    }
}

function two()
{
    i = 1;
}
</script>

(i is reset at every iteration of the loop, as it's not declared locally in the for loop but globally) eventually resulting in infinite loop

Glide answered 24/9, 2009 at 9:31 Comment(4)
Yikes! I can just imagine all the bugs that could be caused by that typo.Theatheaceous
i'm curious, why you are passing i as an argument to two()? (inside the for loop) is that redundant?Destructor
The argument is ignored in two() function encapsulated in one() function, since the function two() was defined without an parameter. You are quite correct, It is not needed since it plays not role.Cervicitis
Bug or feature?Demur
P
17

I would say it's better to use var in most situations.

Local variables are always faster than the variables in global scope.

If you do not use var to declare a variable, the variable will be in global scope.

For more information, you can search "scope chain JavaScript" in Google.

Perform answered 24/9, 2009 at 9:2 Comment(3)
If you declare a variable by using var keyword, it will be created at runtime so shouldnt it be slower ? Because other one is created at parsed time.Cherri
@RyuKaplan - hey, is that true? I tried googling and couldn't get any info on the subject! Do you have a source authority for that assertion? ThxBreaststroke
@RyuKaplan Parsing/compiling is different from actually running the code.Excitement
G
13

Don't use var!

var was the pre-ES6 way to declare a variable. We are now in the future, and you should be coding as such.

Use const and let

const should be used for ~95% of cases. It makes it so the variable reference can't change, thus array, object, and DOM node properties can change and should likely be const.

let should be be used for any variable expecting to be reassigned. This includes within a for loop. If you ever write varName = beyond the initialization, use let.

Both have block level scoping, as expected in most other languages.

Guanaco answered 15/8, 2017 at 18:49 Comment(4)
Replace all you 'var' by 'const' (replace all). You will quickly notice where are your re-assigned variables. If you have too many of them, you probably code anti-patternly: most reassignable variables can be embedded in closures or as object-properties. If you have a few: use 'let' for them. Finally, if some variables where not delared at all with 'var', they will stay undeclared, and are still present in the global space, beware. About @Guanaco comment 'within a for loop', it is also recommended to avoid such loops in "95% of cases" ;-): array methods are great.Mariande
By saying that const should be used in 95% of cases, it seems like we are going away from good practice and into dogma.Lyingin
Having a big, bold, "Don't use var" on a question where the alternative is to use no keyword whatsoever is a dangerous way to structure and format your answer. Don't underestimate a person's disinterest in reading your second paragraph. Some people may be in a lazy mood or in a hurry and may get the wrong idea from this answer just because of the way it is structured and formatted. You don't explicitly mention that you're not advocating putting variables in the global scope.Morlee
@Lyingin Does “dogma” refer to the “constant purism” debate, i.e. the argument that const shall only be used for “mathematical” constants such as π, or magic numbers or strings? If so: programming is derived from math, including some of the terminology, but it’s still distinct from it. In JS, the const keyword creates zero or more immutable bindings (if no error occurs). A binding is a link between an identifier and a value. The binding is the “constant”, not the value. In real code, in 95 % of cases, there just won’t be an intention to reassign a variable, so const does make sense.Creepy
N
12

another difference e.g

var a = a || [] ; // works 

while

a = a || [] ; // a is undefined error.
Nerva answered 9/8, 2013 at 22:11 Comment(3)
Could You explain why it works in case of variable defined with 'var' and variable not defined with var? Is variable created before evaluation of right side of assignment in case of var?Cilia
@Lucek because var a is hoisted to the top of the scope and set to null which declares but does not initialize the variable, then in assignment you have a reference to an undefined null variable which evaluates to false, and set the assignment to []. In the latter, you have an assignment to the property a of the property a. You can assign to a property that does not exist -- creating it on assignment, but you can't read from a property that does not exist without a getting a ReferenceError thrown at you.Borras
@EvanCarroll : it gets hoisted to top of scope and gets set to undefined instead of null.Harberd
B
11

Without var - global variable.

Strongly recommended to ALWAYS use var statement, because init global variable in local context - is evil. But, if you need this dirty trick, you should write comment at start of page:

/* global: varname1, varname2... */
Baeza answered 24/9, 2009 at 9:4 Comment(0)
R
11

Using var is always a good idea to prevent variables from cluttering the global scope and variables from conflicting with each other, causing unwanted overwriting.

Robinette answered 4/4, 2011 at 23:14 Comment(0)
C
6

This is example code I have written for you to understand this concept:

var foo = 5; 
bar = 2;     
fooba = 3;

// Execute an anonymous function
(function() {    
    bar = 100;             //overwrites global scope bar
    var foo = 4;           //a new foo variable is created in this' function's scope
    var fooba = 900;       //same as above
    document.write(foo);   //prints 4
    document.write(bar);   //prints 100
    document.write(fooba); //prints 900
})();

document.write('<br/>');
document.write('<br/>');
document.write(foo);       //prints 5
document.write(bar);       //prints 100
document.write(fooba);     //prints 3
Churlish answered 24/9, 2009 at 8:54 Comment(2)
The function is by no means "anonymous". In fact, it is about as visibly named as it can possibly be.Congregation
Thank you for editing your answer, in response to Ingo Bürk's comment, to make the "anonymous function" actually anonymous.Ivetteivetts
P
6

@Chris S gave a nice example showcasing the practical difference (and danger) between var and no var. Here's another one, I find this one particularly dangerous because the difference is only visible in an asynchronous environment so it can easily slip by during testing.

As you'd expect the following snippet outputs ["text"]:

function var_fun() {
  let array = []
  array.push('text')
  return array
}

console.log(var_fun())

So does the following snippet (note the missing let before array):

function var_fun() {
  array = []
  array.push('text')
  return array
}

console.log(var_fun())

Executing the data manipulation asynchronously still produces the same result with a single executor:

function var_fun() {
  array = [];
  return new Promise(resolve => resolve()).then(() => {
    array.push('text')
    return array
  })
}

var_fun().then(result => {console.log(result)})

But behaves differently with multiple ones:

function var_fun() {
  array = [];
  return new Promise(resolve => resolve()).then(() => {
    array.push('text')
    return array
  })
}

[1,2,3].forEach(i => {
  var_fun().then(result => {console.log(result)})
})

Using let however:

function var_fun() {
  let array = [];
  return new Promise(resolve => resolve()).then(() => {
    array.push('text')
    return array
  })
}

[1,2,3].forEach(i => {
  var_fun().then(result => {console.log(result)})
})
Paratrooper answered 29/12, 2017 at 0:46 Comment(1)
Thanks for the example @thisismydesign! In regard to the last two examples, why does the penultimate example log an array of 3 elements with text written thrice whereas the ultimate example only logs "text" once per element within the array? (I understand that the last one declares "array" as a variable and is therefore in the local scope, whereas the penultimate example omits this, making "array" a part of the implied global scope.) But, why how does this affect the output? Is it because the forEach "i" iterates over the function and all global variables?Doorn
B
5

As someeone trying to learn this this is how I see it. The above examples were maybe a bit overly complicated for a beginner.

If you run this code:

var local = true;
var global = true;


function test(){
  var local = false;
  var global = false;
  console.log(local)
  console.log(global)
}

test();

console.log(local);
console.log(global);

The output will read as: false, false, true, true

Because it sees the variables in the function as seperate from those outside of it, hence the term local variable and this was because we used var in the assignment. If you take away the var in the function so it now reads like this:

var local = true;
var global = true;


function test(){
  local = false;
  global = false;
  console.log(local)
  console.log(global)
}

test();

console.log(local);
console.log(global);

The output is false, false, false, false

This is because rather than creating a new variable in the local scope or function it simply uses the global variables and reassigns them to false.

Berbera answered 1/10, 2016 at 3:14 Comment(0)
G
5

I see people are confused when declaring variables with or without var and inside or outside the function. Here is a deep example that will walk you through these steps:

See the script below in action here at jsfiddle

a = 1;// Defined outside the function without var
var b = 1;// Defined outside the function with var
alert("Starting outside of all functions... \n \n a, b defined but c, d not defined yet: \n a:" + a + "\n b:" + b + "\n \n (If I try to show the value of the undefined c or d, console.log would throw 'Uncaught ReferenceError: c is not defined' error and script would stop running!)");

function testVar1(){
    c = 1;// Defined inside the function without var
    var d = 1;// Defined inside the function with var
    alert("Now inside the 1. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);

    a = a + 5;
    b = b + 5;
    c = c + 5;
    d = d + 5;

    alert("After added values inside the 1. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
};


testVar1();
alert("Run the 1. function again...");
testVar1();

function testVar2(){
    var d = 1;// Defined inside the function with var
    alert("Now inside the 2. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);

    a = a + 5;
    b = b + 5;
    c = c + 5;
    d = d + 5;

    alert("After added values inside the 2. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
};

testVar2();

alert("Now outside of all functions... \n \n Final Values: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n You will not be able to see d here because then the value is requested, console.log would throw error 'Uncaught ReferenceError: d is not defined' and script would stop. \n ");
alert("**************\n Conclusion \n ************** \n \n 1. No matter declared with or without var (like a, b) if they get their value outside the function, they will preserve their value and also any other values that are added inside various functions through the script are preserved.\n 2. If the variable is declared without var inside a function (like c), it will act like the previous rule, it will preserve its value across all functions from now on. Either it got its first value in function testVar1() it still preserves the value and get additional value in function testVar2() \n 3. If the variable is declared with var inside a function only (like d in testVar1 or testVar2) it will will be undefined whenever the function ends. So it will be temporary variable in a function.");
alert("Now check console.log for the error when value d is requested next:");
alert(d);

Conclusion

  1. No matter declared with or without var (like a, b) if they get their value outside the function, they will preserve their value and also any other values that are added inside various functions through the script are preserved.
  2. If the variable is declared without var inside a function (like c), it will act like the previous rule, it will preserve its value across all functions from now on. Either it got its first value in function testVar1() it still preserves the value and get additional value in function testVar2()
  3. If the variable is declared with var inside a function only (like d in testVar1 or testVar2) it will will be undefined whenever the function ends. So it will be temporary variable in a function.
Gust answered 20/11, 2016 at 6:50 Comment(1)
Thanks for taking the time to create an example to demonstrate this topic. The code above is missing the part below so you might want to edit your answer: a = 1;// Defined outside the function without var var b = 1;// Defined outside the function with var alert("Starting outside of all functions... \n \n a, b defined but c, d not defined yet: \n a:" + a + "\n b:" + b + "\n \n (If I try to show the value of the undefined c or d, console.log would throw 'Uncaught ReferenceError: c is not defined' error and script would stop running!)");Advice
P
4

Inside a code you if you use a variable without using var, then what happens is the automatically var var_name is placed in the global scope eg:

someFunction() {
    var a = some_value; /*a has local scope and it cannot be accessed when this
    function is not active*/
    b = a; /*here it places "var b" at top of script i.e. gives b global scope or
    uses already defined global variable b */
}
Phosphorus answered 13/8, 2013 at 23:0 Comment(0)
E
4

Besides scopes issue, some folks also mention hoisting, but no one gave an example. Here's one for global scope:

console.log(noErrorCase);
var noErrorCase = "you will reach that point";

console.log(runTimeError);
runTimeError = "you won't reach that point";
Extrusive answered 5/9, 2019 at 10:24 Comment(0)
I
3

Without using "var" variables can only define when set a value. In example:

my_var;

cannot work in global scope or any other scope. It should be with value like:

my_var = "value";

On the other hand you can define a vaiable like;

var my_var;

Its value is undefined ( Its value is not null and it is not equal to null interestingly.).

Imagine answered 27/4, 2014 at 4:28 Comment(5)
my_var; is actually a valid expression statement.Masquer
It is valid statement if variable is defined before. Otherwise it throw an error "... is not defined".Imagine
It is a valid statement regardless of if a variable was defined before or not. :) A valid statement can throw an eror it does not make the statement invalid.Masquer
I am confused about it. What is valid statement? And can you give me an invalid statement example?Imagine
I'll have to apologize - too much ECMAScript grammar lately. my_var; is a valid expression statement. /my_var; would be a invalid statement. But as I said, this is grammar casuistics, I apologize, my comment was actually not appropriate.Masquer
Y
3

You should use var keyword unless you intend to have the variable attached to window object in browser. Here's a link that explains scoping and difference between glocal scoping and local scoping with and wihtout var keyword.

When variables get defined without the use of var keyword, what it looks like is a simple “assignment” operation.

When the value is assigned to a variable in javascript, the interpreter first tries to find the “variable declaration” in the same context/scope as that of assignment. When the interpreter executes dummyVariable = 20, it looks up for the declaration of dummyVariable at beginning of the function. (Since all Variable declarations are moved to the beginning of the context by javascript interpreter and this is called hoisting)

You may also want to look at hoisting in javascript

Yehudi answered 12/12, 2016 at 4:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.