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?
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:
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With