15

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

a = 10;
b = 5;
a =+ b;
user1334297
  • 159
  • 1
  • 1
  • 3
  • 2
    the correct syntax is a+=b; a=+b; is not correct. it is simply assigning b value to a. – Anil Apr 15 '12 at 09:42
  • Possible duplicate of [What is the purpose of a plus symbol before a variable?](https://stackoverflow.com/questions/6682997/what-is-the-purpose-of-a-plus-symbol-before-a-variable) – Ivar Dec 17 '18 at 12:40

2 Answers2

49

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;
Eric
  • 95,302
  • 53
  • 242
  • 374
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
1

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.

Fattech
  • 11
  • 3