Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is "" in JavaScript really?

Tags:

javascript

This one says false, meaning the "" is a number:

alert(isNaN("")); 

This one says NaN, meaning the "" is not a number and cannot be converted:

alert(parseFloat(""));

I was expecting the second code to convert "" to 0 since "" is a number when tested in IsNaN but I was wrong! Am I getting crazy or I just missed something?

like image 203
dpp Avatar asked Jun 07 '12 05:06

dpp


People also ask

What JavaScript actually do?

JavaScript is a scripting or programming language that allows you to implement complex features on web pages — every time a web page does more than just sit there and display static information for you to look at — displaying timely content updates, interactive maps, animated 2D/3D graphics, scrolling video jukeboxes, ...

Is JavaScript real coding?

JavaScript was developed at Netscape. It was originally called LiveScript, but that name wasn't confusing enough. The -Script suffix suggests that it is not a real programming language, that a scripting language is less than a programming language. But it is really a matter of specialization.

What is JavaScript made of?

Chrome's Javascript engine, V8, is written in C++. From the project page: V8 is written in C++ and is used in Google Chrome, the open source browser from Google.


1 Answers

parseFloat tries to parse a number from string where as isNaN converts the argument to number before checking it:

Number("") //0 http://ecma-international.org/ecma-262/5.1/#sec-9.3.1
parseFloat("") //NaN http://ecma-international.org/ecma-262/5.1/#sec-15.1.2.3

Apparently this is "broken" or "confusing", so from the specs:

A reliable way for ECMAScript code to test if a value X is a NaN is an expression of the form X !== X. The result will be true if and only if X is a NaN.

0 !== 0 // false
NaN !== NaN //true

function isExactlyNaN(x) {
    return x !== x;
}
like image 190
Esailija Avatar answered Sep 20 '22 05:09

Esailija