What is the difference between a = 1 and a = + a?

What's the difference between

a *= 1; 

and

 a = +a; 

in javascript?

Both convert a string to number (int or float). They behave differently than parseInt and parseFloat . But is there a difference between the two lines?

+5
source share
4 answers

There is no difference. Both are converted to numbers using ToNumber . And numerical multiplication by 1 and the unary operation plus keep the values ​​the same.

+4
source

What's the difference between

 a *= 1 

This is the purpose of multiplication, you accept and multiply it by 1.

  a = +a 

This is a simple assignment using the unary plus operator. It evaluates a and converts it to a number.

The main difference between the unary plus operator and parseInt or parseFloat is that unary can convert string representations of both integers and float, as well as non-line values ​​true, false, and null. Where, since parseInt and parseFloat can only convert a string to int and float respectively.

Also, the parseInt method allows you to set up a basic system (basic / mathematical numerical system). i.e.

 parseInt(a, 10); //decimal numeral system 
+3
source

There is no difference, both are trying to convert the value to a number and assign either a multiplication value or the result is unary plus + .

When starting with an empty string, both results return NaN if a string number or just a number, the result is a number in both cases.

 var a, b; a *= 1; b = +b; console.log(a, b); a = 'foo'; b = 'foo'; a *= 1; b = +b; console.log(a, b); a = ''; b = ''; a *= 1; b = +b; console.log(a, b); a = '7'; b = '7'; a *= 1; b = +b; console.log(a, b); a = 42; b = 42; a *= 1; b = +b; console.log(a, b); 
+3
source

In a technical sense, there is no difference. But using the unary plus operator, which converts a string to a number, can definitely be more obvious in this case, making your code more readable.

+2
source

Source: https://habr.com/ru/post/1275818/


All Articles