miir miir - 3 months ago 16
Javascript Question

How to construct Date object instance and invoke its function on the same line?

I would like to construct a

Date
object and invoke the
getTimeZoneOffset()
function in the same line. However, chrome is giving me an error.

> new Date().getTimeZoneOffset();

x Uncaught TypeError: (intermediate value).getTimeZoneOffset is not a function(…)


I created a random test object, and was able to instantiate the test object and call its function in the same line.

Why am I unable to do this with the Date object?

Answer

The function is getTimezoneOffset, not getTimeZoneOffset. So, it just works:

new Date().getTimezoneOffset()

Of course, not needed in this case, but in cases when you want something to run first then use its return to call another function, you could use an Immediately-Invoked Function Expression (IIFE), like this:

(function () { return new Date() })().getTimezoneOffset()

And with ES6 arrow functions:

(() => new Date())().getTimezoneOffset()
Comments