When I write this in the console it's log undefined.
var obj = { first: 'lorem' };
But when I write this in the console it's log object.
var obj = { first: 'lorem' };
obj = { second: 'ipsum' };
Why is this happening?
When I write this in the console it's log undefined.
var obj = { first: 'lorem' };
But when I write this in the console it's log object.
var obj = { first: 'lorem' };
obj = { second: 'ipsum' };
Why is this happening?
The value you see being printed is the return
value of the line of code you executed.
var obj = {first: 'lorem'};
returns undefined
, whereas
obj = {second: 'ipsum'};
will return the object assigned to obj
, hence {second: 'ipsum'}
is printed.
This is why you can do things such as:
var a = b = 2;
Here the assignment of b = 2
will set b
equal to 2, whilst also returning 2
, thus setting a
to 2
Anything you execute in the console, it will display the return value of it. When declaring and assigning variables, it will return undefined. When only assigning values to variables, that value is returned.