user1334297
user1334297

Reputation: 179

Difference between += and =+ in javascript

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

a = 10;
b = 5;
a =+ b;

Upvotes: 17

Views: 21787

Answers (2)

Fattech
Fattech

Reputation: 21

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.

Upvotes: 2

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340723

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;

Upvotes: 50

Related Questions