Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does browser returns undefined? [duplicate]

Tags:

javascript

I have found a phenomenon that confused me when I run simple javascript code from the browser console(Chrome & Firefox).

When I typed say

>var a = "a"

The browser will return a string

>"undefined"

but if I just typed

>a = "a"

The browser will return the string

>"a"

Why is this case?

like image 781
Frank Tian Avatar asked Mar 20 '23 17:03

Frank Tian


1 Answers

If you write

alert(var a = 'a')

You get a syntax error, var is part of the javascript syntax, it doesn't return anything.

The a = 'a' portion, however, does return something.

You can do var a = b = c = d = 'e';

And the d = 'e' returns e, which gets fed into the c=d which is really c = 'e', etc. Once you get to the var it stops returning the value.

If you type var a; you get undefined. var a = 'b' is essentially just shorthand for var a; a = b;

like image 115
dave Avatar answered Apr 02 '23 17:04

dave