Javascript variables - what is the difference between var someNumber = 2 and someNumber = 2?
Javascript, CSS

Javascript. What is the difference between:

var someNumber = 2

var someFunction = function() { function doing something }

var someObject = { }

var someObject.someProperty = 5

and

someNumber = 2 ?

someFunction = function() { function doing something }

someObject = { }

someObject.someProperty = 5

 

The answer is that in the Global Scope, there is no difference. You've declared a Global Variable that is accessible everywhere while you're Javascript program is running. But when you define a variable in a Local Scope, the var feature (temporarily) creates a Local Variable that (while your local function is running) overrides the global variable with that name - (if any have been defined). Afterwards, the variable returns to its Global Value.

var someNumber = 2

document.write( someNumber )  ==>  [ 2 ] (global scope)

someFunction() {

    someNumber = 5000

    document.write( someNumber ) ==> [ 5000 ] (local scope)

}

document.write( someNumber ) ==> [ 2 ] (global scope)

 

But, then you might ask, what happens if I define a variable within the local scope of a function, without using "var"?

In that case, WITHOUT the 'var' declaration, you will (permanently) OVER-WRITE the global variable with that name (if any is defined).

var someNumber = 2

document.write( someNumber )  ==>  [ 2 ] (global scope)

someFunction() {

    someNumber = 5000

    document.write( someNumber ) ==> [ 5000 ] (local scope)

}

document.write( someNumber ) ==> [ 5000 ] (global scope)

 

Why does this happen? Because the Javascript var x = something declares a variable in the scope it's in, and the x = something variant is really a property assigner. It's really used more for assigning values to already existing variables. But if the variable doesn't yet exist, then it creates it. 

 

| Back

Footerfull