Skip to content

The Javascript “var” Keyword

As all dynamic languages, javascript lets you set a value to a variable anywhere in code, without having to declare the variable. But there are two ways to do this, with the var keyword, or without the var keyword. Like this:

var myVar = 5;
myOtherVar = "hello";

Both are valid statements in Javascript… so what is the difference? As usual, thank to StackOverflow where all questions are answered.

When we use the var keyword, we are creating a local variable in the local scope. If there are variables with the same name in enclosing scopes, these variables are masked. If you don’t use the var keyword, the interpreter searches for a variable with the same name in all enclosing scopes, and if it doesn’t find one, it creates one in the global scope. For example:

x1 = 5; // global variable
x2 = 8; // global variable

function() {
  x1 = 7 // Overrides the previous value of x1
  var x2 = 8 // Creates a new local variable called x2, and masks the global x2
  x3 = 7 // Creates a new global variable called x3
}

Just writing this down to store it in my long-term memory.

Published inProgramming

Be First to Comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.