kadina
kadina

Reputation: 5376

Why some strings are getting converted to numbers while others a not in javascript

I am new to java script. In console of web browser, I observed the below things.

"" - 1 + 0 = -1
"4" - 2 = 2
"4px" - 2 = NaN
" -9\n" - 5 = -14

I understood that strings will be converted to numbers while performing mathematical operations except addition. In 3rd operation, "4px" is not a valid number because of "px". So the result turned out to be NaN. But I didn't understand how " -9\n" is converted to -9 even though "\n' exists.

This might be a simple question. But I am unable to understand the reason. Can any one please let me know if I am missing any thing?

Upvotes: 1

Views: 100

Answers (3)

Soveu
Soveu

Reputation: 19

The '\n' in a string is understood by many programming languages (if not all) as a new line character.

What that means? If you put a \n into your string like for example:

var fruits = "apple \nbanana \norange"

The final result printed by console.log(fruits) would look like this:

apple
banana
orange

You can find most escape sequences on this article on Wikipedia (do not worry about title it mostly works in other languages too)

Upvotes: 0

Stephen Gheysens
Stephen Gheysens

Reputation: 303

I think that you just happened across an escape character sequence that allows "-9\n" to be automatically converted to a Number. The character sequence "\n" represents a newline in most languages (Javascript included), and therefore treated like whitespace. This also means that that "\t" for tabs and "\r" for returns/newlines are similarly ignored.

> "-2\n" - 2
-4
> "-2\t" - 2
-4
> "-2\r" - 2
-4

But as soon as you test with a letter that isn't an escape sequence for whitespace (tabs, newlines, etc), or remove the escaping backslash, it's recognized as a letter and is evaluated to being NaN.

> "-2\a" - 2
NaN
> "-2n" - 2
NaN

Upvotes: 3

Max
Max

Reputation: 1345

\n is the escape sequence for the newline character. That's the one you get when you press the "Enter" key.

For example, there's a \n between the cat and the dog below.

cat
dog

If you do " 9 " + 0 you will get 9 because JavaScript will ignore the surrounding spaces when converted to a number. The same occurs here because the newline is considered whitespace.

Upvotes: 3

Related Questions