Maiya
Maiya

Reputation: 980

JavaScript Number Constructor Methods in Global Scope. Why are they working?

I am trying to understand the structure of the javaScript language.

Can someone please tell me:

I understand that isNaN() is a method on the Number constructor.

So, how is it that the following two examples are able to work?

console.log(isNaN(3));

or

if(isNaN(3)) {
    console.log(`3 is *not* a number`);
} else {
    console.log(`3 is a number`);
}

There is no isNaN() function on the window --> i.e. window.isNaN() does not exist.

And you are not writing 3.isNaN() or Number.isNaN(3)

How is it that just writing the isNaN() function (or any other Number method) on its own, you are able to access the Number constructor?

For contrast:

When you implement a String method, you dot it off of an actual string, so the String methods are inherited by this string method. Example:

let littleString = 'I am a string'.toLowerCase();

You can't write:

toLowerCase('I am a little string');

or you will get an error:

ReferenceError: Can't find variable: toLowerCase

So, why can you do this with numbers?

Thanks!

Upvotes: 0

Views: 61

Answers (2)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85575

The global functions — functions which are called globally rather than on an object—directly return their results to the caller.

isNaN is a global function but toLowerCase is not.

See the global functions:

eval()
uneval() // not standardized
isFinite()
isNaN()
parseFloat()
parseInt()
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape() // deprecated
unescape() // deprecated

Since, toLowerCase() is a prototype of String constructor, you need to call this method on string.

In fact, isNaN is defined globally (inherited from window object) and also in Number constructor.

Upvotes: 2

Bergi
Bergi

Reputation: 664990

I understand that isNaN() is a method on the Number constructor, and there is no isNaN() function on the window

No. There are in fact two isNaN functions (and they even work differently):

Upvotes: 3

Related Questions