0

When I write this in the console it's log undefined.

var obj = { first: 'lorem' };

enter image description here

But when I write this in the console it's log object.

var obj = { first: 'lorem' };
obj = { second: 'ipsum' };

enter image description here

Why is this happening?

black
  • 703
  • 2
  • 7
  • 16
  • 4
    When you execute something in the console, the return value is displayed below your input. For example if you execute `1 + 2`, the console will display `3` since that's the result. Shortly put, the result of a variable declaration is `undefined`, the result of assignment is the assigned value. – Etheryte Feb 24 '19 at 12:46

2 Answers2

1

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

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
0

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.

Sagar Agrawal
  • 639
  • 1
  • 7
  • 17