17

I want to know why after running the third line of code the result of a is 5?

a = 10;
b = 5;
a =+ b;
2
  • 2
    the correct syntax is a+=b; a=+b; is not correct. it is simply assigning b value to a. Commented Apr 15, 2012 at 9:42
  • Possible duplicate of What is the purpose of a plus symbol before a variable? Commented Dec 17, 2018 at 12:40

2 Answers 2

50

Awkward formatting:

a =+ b;

is equivalent to:

a = +b;

And +b is just a fancy way of casting b to number, like here:

var str = "123";
var num = +str;

You probably wanted:

a += b;

being equivalent to:

a = a + b;
Sign up to request clarification or add additional context in comments.

3 Comments

...while a += b is a shortcut for a = a + b, which is probably what you want
@fritzfromlondon: Thanks for pointing that out, I allowed myself to add your comment to an answer to better stand out
The + in a = +b; is called the unary + operator: es5.github.com/#x11.4.6
2

The + sign before the function, actually called Unary plus and is part of a group called a Unary Operators and (the Unary Plus) is used to convert string and other representations to numbers (integers or floats).

A unary operation is an operation with only one operand, i.e. a single input. This is in contrast to binary operations, which use two operands.

Basic Uses:

const x = "1";
const y = "-1";
const n = "7.77";

console.log(+x);
// expected output: 1

console.log(+n);
// expected output: 7.77

console.log(+y);
// expected output: -1

console.log(+'');
// expected output: 0

console.log(+true);
// expected output: 1

console.log(+false);
// expected output: 0

console.log(+'hello');
// expected output: NaN

When the + sign is positioned before a variable, function or any returned string representations the output will be converted to integer or float; the unary operator (+) converts as well the non-string values true, false, and null.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.