Is checking a string against a number good style?

Which one of these to JS snippets are better in terms of style?

var answer = Number(prompt('What is the value of 2 + 2?'));

if (answer === 4) {
    // do something
}

vs.

var answer = prompt('What is the value of 2 + 2?');

if (answer == 4) {
    // do something
}

I'd say the first one is better because it is more explicit (and no type coercion will happen).

Answers


It depends on what you want to do with answer. If the only thing you want to do is compare it, you don't need to convert the type:

var answer = prompt('What is the value of 2 + 2?');

if (answer === "4") {
    // do something
}

If you want to end up with a number for comparison and then further processing, Number or the unary plus operator + will convert the output string to a numeric value, or NaN if it is not a valid base 10 number.

var answer = +prompt('What is the value of 2 + 2?');

if (answer === 4) {
    // do something
}

There is a difference between parseInt(x, 10) and Number(x) - the former will ignore non-numeric characters at the end.

parseInt("4Hello World"); // 4
Number("4Hello World"); //NaN
+"4Hello World"; //NaN

They are both wrong, because you should use parseInt(XX, 10) for this. And remember, every time you use == Jesus kills a puppy. So always use ===, and therefore: always check against the correct type.


Need Your Help

Php - how to read similar string from text file?

php

how can I read string from text file and check if exists or similar text exists with IF statement? (if string extist, dont update text file in case that the new information is the same as inside the

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.