1

Why I am getting undefined for this below statement in console?

var someDate=new Date(1337986800000);  

enter image description here

But with out assigning to a variable it works fine

  new Date(1337986800000);

enter image description here

Why is it so?

Murali Murugesan
  • 22,423
  • 17
  • 73
  • 120

2 Answers2

2

Just type this:

var someDate=new Date(1337986800000); someDate;

It is how the console works.

When you are doing just new Date(1337986800000);, the constructor is returning the object which is printed in the screen.

but when you assign it to a variable, the variable holds the return value, so the console has nothing to do but print undefined. So you'll need to explicitly call the variable to get the output which you are expecting

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
0

What you do is create a new Date instance. In the first example you store the instance in a variable; you get undefined because the constructor function itself doesn't explicitly return anything. In the second example you ask the console to evaluate an expression, which is calling the date constructor, so it just returns you the resulting instance.

Andrei Nemes
  • 3,062
  • 1
  • 16
  • 22