0

I have small doubt in difference of local variable and global variable in browser console, when i type var a = 5 and hit enter in chrome browser console it returns undefined but when i type a = 5 not returning anything.

0

2 Answers 2

4

This has nothing to do with local vs. global variables. It's just that what the console shows you is the result of the statement. var statements don't have a result, so you see undefined. Assignment statements1 do have a result (the assigned value), so you see that value.

If you did

var a = 5; a 

...you'd see undefined followed by 5.


1 Technically, it's an expression statement containing an assignment expression.

Sign up to request clarification or add additional context in comments.

Comments

0

In my understanding when you write a=5, this will create a global variable. So it would be a part of window object. Hence you get its value.

When you do var a = 5, a new variable(reference) will be created, and then value will be set. Hence, you will get undefined.

You can even try following code for testing.

var a = {}; a.b = 5; 

This will return 5 and not undefined.

2 Comments

I have doubt here, So first new reference variable will create after that it will returns undefined after value will assign to reference variable
Sort of. So since compiler will have to create a new reference, it will create it and return its value and make setting value action as async

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.