Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between var x=10 and x=10 when typed in browser console?

In browser console if I type var x=10 it shows undefined while if i type x=10 it shows 10. Both perform the same task then what is the difference? I am not asking difference between using var and not using var?

like image 536
Nitin9791 Avatar asked Feb 05 '16 05:02

Nitin9791


Video Answer


2 Answers

You are in browser console, so you are alerady in global scope, and with or without var make no difference on how the variable was stored:

Prove

However, = is a operator which returns the value you assigned, so a = 1 will evaluate to 1, and you see a 2 when you typed b = 2. var don't return anything, it is a statement not an expression.

like image 75
maowtm Avatar answered Sep 19 '22 00:09

maowtm


EXPLANATION

case x = 10:

This creates a variable in the Global scope named x with value 10. Additionally, this is an expression, which returns the value 10. This is useful in order to be able to do things like var x = y = 10; which sets both x and y to the value 10

case var x = 10:

This creates a variable in the current scope, which just so happens to be the global scope, named x with value 10. Because it is created with the syntax var, it cannot be evaluated as an expression, therefore it returns undefined, which is printed to the console.

SUMMARY

There is no difference in effect of writing var x = 10 vs x = 10 from the console, although there will be in other places. The latter is also not allowed in strict mode. However the first returns undefined because when run, there is no output, however the second returns 10 because x=10 is an expression.

EXAMPLE

You can see what is happening a little better if you use eval

var output = eval('x = 10');  
console.log(output)           // 10

vs

var output = eval('var x = 10');  
console.log(output)           // undefined
like image 35
Mobius Avatar answered Sep 21 '22 00:09

Mobius