Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why + + on strings gives strange result

I was working on appending the element dynamically using jQuery and found that when using + + it shows NaN and the next text is not added.

I can guess that somehow + + works here as Arithmetic plus operator and returns NaN.

This is not Increment operator as there is space between the two +.

My Question is

  1. What is actually happening here so it returns NaN
  2. Why + here does not work as concatenation operator when it is surrounded by strings.

$('#message').html('<span>' + + ' new message</span>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="message"></div>

The same behaviour can be seen in Node.js

> 'a' + + 'b' // aNaN

Note: I know that I've added an extra + here and removing that will work for me.

like image 834
Tushar Avatar asked Nov 28 '22 13:11

Tushar


1 Answers

The reason is because by placing the + character before a string you're attempting to convert the 'b' string to a number, which results in NaN. The code in your question is equivalent to this:

'a' + Number('b')

Hence Number('b') returns NaN which is then coerced to a string and appended to a. This behaviour is intrinsic to JS, so the library being used (whether jQuery, node or any other) is irrelevant.

like image 135
Rory McCrossan Avatar answered Nov 30 '22 22:11

Rory McCrossan