Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does JavaScript evaluate plus with string and int differently?

Why does JavaScript evaluate plus with a string and integers differently depending on the place of the string?

An example:

console.log("1" + 2 + 3);
console.log(2 + 5 + "8");

The first line prints 123 and the second prints 78.

like image 685
Nirgn Avatar asked Jul 15 '15 07:07

Nirgn


People also ask

Can string and number be compared in JavaScript?

When comparing a string with a number, JavaScript will convert the string to a number when doing the comparison. An empty string converts to 0. A non-numeric string converts to NaN which is always false . When comparing two strings, "2" will be greater than "12", because (alphabetically) 1 is less than 2.

What happens when we add number and string in JavaScript?

In javascript , we can add a number and a number but if we try to add a number and a string then, as addition is not possible, 'concatenation' takes place. In the following example, variables a,b,c and d are taken. For variable 'a', two numbers(5, 5) are added therefore it returned a number(10).

When operator is used with a string and a number JavaScript converts the numeric value to a string and performs concatenation?

In JavaScript when the + operator is used with strings, it concatenates them. This is why console. log("5"+1) returns "51". 1 is converted to a string and then, "5" + "1" are concatenated together.

What is returned when a string is added to a number in JavaScript?

Pass each string to the Number object to convert it to a number. Use the addition (+) operator, e.g. Number('1') + Number('2') . The addition operator will return the sum of the numbers.


1 Answers

  1. JavaScript does automatic type conversion
  2. The expression is evaluated left to right and therefore:

    "1" + 2 + 3 -> "12" + 3 -> "123"
    
    2 + 5 + "8" -> 7 + "8" -> "78"
    
like image 99
Amir Popovich Avatar answered Sep 20 '22 20:09

Amir Popovich