1659

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alex
  • 75,813
  • 86
  • 255
  • 348
  • 6
    When chaining var declarations, does putting a newline after a comma affects the behavior? var x=1, y=2, [return]z=3; – Alfabravo Nov 20 '11 at 04:35
  • 6
    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: http://stackoverflow.com/questions/16704014/why-do-chrome-and-firefox-handle-javascript-variable-set-inside-jquery-ajax-ca – Scott C Wilson May 23 '13 at 15:49
  • 7
    @Ray Toal's meloncard blog post (definitely worth a read) has moved to http://blog.safeshepherd.com/23/how-one-missing-var-ruined-our-launch/ – Hephaestus Mar 02 '14 at 17:57
  • 2
    I'd never imagined a poem could inspire me consideration for a programmatic problem – Félix Adriyel Gagnon-Grenier Mar 15 '15 at 08:22
  • 2
    Use `const` and `let` instead! `var` is not modern JS – Gibolt Aug 15 '17 at 18:54
  • 3
    @Gibolt 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. – Andre Figueiredo Mar 16 '18 at 03:53
  • 1
    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 answer – Gibolt Mar 16 '18 at 04:12
  • 1
    Note that in modern JavaScript you should usually use [`let` instead of `var`](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var) (due to the differences in how `let` and `var` behave). – Quentin Dec 19 '19 at 17:36

19 Answers19

1408

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
AmericanUmlaut
  • 2,817
  • 2
  • 17
  • 27
Greg
  • 316,276
  • 54
  • 369
  • 333
  • 34
    Is "not really much difference" == "No Difference"? – Alex Sep 24 '09 at 08:56
  • 69
    Well, actually yes, there's difference :) Whether that difference is important is another question. See my answer further down: http://stackoverflow.com/questions/1470488/difference-between-using-var-and-not-using-var-in-javascript#answer-1471738 – kangax Sep 25 '09 at 04:11
  • 6
    I think that may be Alex's point, which is why he's written it using the "is equal to" operator! – James Bedford Sep 13 '12 at 17:52
  • 19
    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... – Albus Dumbledore Feb 24 '13 at 12:33
  • 9
    _If you're in the global scope then there's no difference._ >> there is a difference which is explained in the answer below – Max Koretskyi Sep 13 '13 at 11:39
  • 3
    @Alex 0 == false, so yes "not really much difference" == "No Difference" however "not really much difference" !== "No Difference" – Math chiller Nov 14 '13 at 13:51
  • 1
    If in strict mode, even in the global scope, you'll need `var` to declare it. – Ruan Mendes Nov 15 '13 at 19:37
  • if you 'use strict';, then you should use var. – WarFox Mar 24 '14 at 05:07
  • 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. – ferr Sep 10 '14 at 17:18
  • 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. – brettwhiteman Feb 04 '15 at 18:56
  • what do you mean by "Creating a Closure"? – NuWin Jul 31 '16 at 02:27
  • 1
    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*. – RobG Nov 06 '17 at 22:47
  • See also https://stackoverflow.com/questions/38270470/javascript-scope-when-importing-modules for an interesting example of a more subtle difference between the two declarations. – Mihai Târnovan Sep 28 '18 at 18:14
  • 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? – xakepp35 Oct 21 '18 at 00:06
  • For C++ code `int i=1; { cout< – xakepp35 Oct 21 '18 at 00:15
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.

Massimiliano Kraus
  • 3,638
  • 5
  • 27
  • 47
kangax
  • 38,898
  • 13
  • 99
  • 135
  • 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. – Tower Jun 30 '11 at 14:51
  • 3
    @Mageek He might be taking about eval-declared variables which are deletable. I wrote a [blog post about this](http://perfectionkills.com/understanding-delete/) once. – kangax Jun 20 '12 at 11:06
  • 1
    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 block – mac Oct 01 '12 at 11:16
  • @kangax 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? – snapfractalpop Nov 28 '12 at 00:43
  • 1
    The spec name for what @kangax calls the _DontDelete_ flag is _configurable (= `false`)_, you can read about this in regards to [`Object.defineProperty`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty) and [`Object.getOwnPropertyDescriptor`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor) – Paul S. Jan 08 '14 at 14:55
  • in some IE versions there's a bug allowing you to delete a variable declaration in the global scope – Shiala Dec 19 '14 at 02:19
  • @Shiala I recall something like that. I think only with variables that "shadow" (have same name as) global built-ins, but I'm not sure. – kangax Dec 19 '14 at 12:51
  • 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. – Shiala Dec 19 '14 at 18:06
  • It would be nice to see an additional update to this answer that details how `let` factors into the OPs question. – Snekse Sep 23 '15 at 22:36
  • @Snekse `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. – kangax Sep 29 '15 at 17:26
  • @kangax 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. – Snekse Sep 29 '15 at 18:29
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;
    }
}
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
  • 4
    Isn't the nearest scope `outer` where you define `var global = false;`? – Snekse Apr 19 '13 at 13:33
  • 1
    @Snekse: 'nearest' doesn't apply when var global = false; 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(). – Mitch Sep 18 '15 at 02:56
  • 1
    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. – Snekse Sep 23 '15 at 22:34
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
thealtus
  • 3
  • 3
kentaromiura
  • 6,459
  • 2
  • 21
  • 15
  • 3
    I didn't downvote you, but scope is probably a better word than window. You're whole explanation is a bit obtuse. – Robert Harvey Sep 24 '09 at 23:12
  • 6
    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." – kentaromiura Sep 25 '09 at 05:19
  • 4
    +1 this is a really nice explanation--i have not heard the var/no var issue framed (no pun intended) like this before. – doug Apr 09 '12 at 23:49
  • 2
    Most of this answer is deprecated with `let` in ES6. – Evan Carroll Jan 20 '14 at 21:12
  • 5
    @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. – kentaromiura Jan 22 '14 at 15:30
  • 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. – RobG Nov 06 '17 at 22:55
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.

Camille Goudeseune
  • 2,934
  • 2
  • 35
  • 56
Steve Harrison
  • 121,227
  • 16
  • 87
  • 72
  • 20
    "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. – cHao May 24 '13 at 04:34
  • @cHao I think `good coding practice` is always sufficient reason if it's a recommended best practice, which this is and by several Javascript authors. – Chris S Jan 03 '14 at 13:58
  • 11
    @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. – cHao Jan 03 '14 at 18:16
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

mehulmpt
  • 15,861
  • 12
  • 48
  • 88
Chris S
  • 64,770
  • 52
  • 221
  • 239
  • 1
    Yikes! I can just imagine all the bugs that could be caused by that typo. – BonsaiOak Oct 12 '14 at 20:07
  • 3
    i'm curious, why you are passing i as an argument to two()? (inside the for loop) is that redundant? – kalin Oct 03 '16 at 03:03
  • 1
    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. – KK. Feb 24 '17 at 06:54
  • 1
    Bug or feature? – TheMaster Aug 24 '19 at 23:07
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.

Waqar
  • 8,558
  • 4
  • 35
  • 43
Billy
  • 15,516
  • 28
  • 70
  • 101
  • 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. – Barış Velioğlu Aug 14 '12 at 01:12
  • @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? Thx – mike rodent Apr 12 '13 at 17:24
  • @RyuKaplan Parsing/compiling is different from actually running the code. – gcampbell Jul 08 '16 at 10:19
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.

Gibolt
  • 42,564
  • 15
  • 187
  • 127
  • 3
    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 @Gibolt comment 'within a for loop', it is also recommended to avoid such loops in "95% of cases" ;-): array methods are great. – allez l'OM Oct 21 '18 at 13:40
  • By saying that const should be used in 95% of cases, it seems like we are going away from good practice and into dogma. – Agamemnus Dec 28 '18 at 04:48
  • 2
    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. – Wyck Nov 25 '21 at 04:43
  • @Agamemnus 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. – Sebastian Simon Nov 27 '22 at 10:28
12

another difference e.g

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

while

a = a || [] ; // a is undefined error.
Pranay Warke
  • 129
  • 1
  • 3
  • 1
    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`? – matt Dec 05 '13 at 13:11
  • 6
    @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. – Evan Carroll Jan 20 '14 at 19:43
  • 1
    @EvanCarroll : it gets hoisted to top of scope and gets set to undefined instead of null. – Mithun Satheesh Sep 25 '14 at 07:40
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... */
Waqar
  • 8,558
  • 4
  • 35
  • 43
Anatoliy
  • 29,485
  • 5
  • 46
  • 45
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.

Kevin Ji
  • 10,479
  • 4
  • 40
  • 63
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
darijan
  • 9,725
  • 25
  • 38
newday
  • 3,842
  • 10
  • 54
  • 79
  • 3
    The function is by no means "anonymous". In fact, it is about as visibly named as it can possibly be. – Ingo Bürk Jan 22 '14 at 22:12
  • 1
    Thank you for editing your answer, in response to Ingo Bürk's comment, to make the "anonymous function" actually anonymous. – Dave Burton Sep 09 '16 at 04:58
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)})
})
thisismydesign
  • 21,553
  • 9
  • 123
  • 126
  • 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? – Brad Ahrens Sep 22 '19 at 11:12
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.

Danrex
  • 1,657
  • 4
  • 31
  • 44
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.
Tarik
  • 4,270
  • 38
  • 35
  • 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!)"); – Sankofa Oct 11 '18 at 16:05
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 */
}
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";
deathangel908
  • 8,601
  • 8
  • 47
  • 81
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.).

umut
  • 1,016
  • 1
  • 12
  • 25
  • 1
    `my_var;` is actually a valid expression statement. – lexicore Nov 27 '14 at 13:23
  • It is valid statement if variable is defined before. Otherwise it throw an error "... is not defined". – umut Nov 27 '14 at 13:31
  • 3
    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. – lexicore Nov 27 '14 at 14:37
  • I am confused about it. What is valid statement? And can you give me an invalid statement example? – umut Nov 27 '14 at 14:59
  • I'll have to apologize - too much ECMAScript grammar lately. `my_var;` is a valid [expression statement](http://ecma-international.org/ecma-262/5.1/#sec-12.4). `/my_var;` would be a invalid statement. But as I said, this is grammar casuistics, I apologize, my comment was actually not appropriate. – lexicore Nov 27 '14 at 15:05
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

systemdebt
  • 4,589
  • 10
  • 55
  • 116