简体   繁体   中英

JavaScript Output of it “1” - - “1” is 2 how?

JavaScript : "1" - - "1" give us 2 in output whereas if I'll write like "1"--"1" getting

Uncaught ReferenceError: Invalid left-hand side expression in postfix operation

The one that works ie "1" - - "1"

 console.log("1" - - "1") 

The one that doesn't works ie "1"--"1"

 console.log("1"--"1"); 

It is totally weird for me.

The - operator casts the string "1" to a number.

So, "1" - - "1" is equivalent to:

1 - (-1)

So: 2!

Whereas, "1"--"1" would fail because operator -- expects only one operand. "1"--"1" just doesn't make sense. In the first case you had an additional space between the - minuses - which made them two different operators.

When the two - symbols are joined together, they form the unary -- operator . That operator needs a variable to act on, and since "1" is not a variable, you get an error.

When the two - are apart, then the first of the two is the subtraction operator , and the second is the unary negation . This is valid syntax and yields 2.

-- and - - are not the same.

-- is the Postfix Decrement Operator . foo-- means "Take the value of the variable foo , subtract 1 from it, assign it back to foo . A string literal is not a variable so this causes an error when you try "a string"-- .

- can either be the Unary - Operator or the Subtraction Operator depending on context.

In the case of "1" - - "1" , you have one of each.

The second - is a Unary - Operator and converts the "1" to its right to -1 . The other is the subtraction operator.

If you subtract "negative one" from "one" you get "two".

Its simple algebra and Javascript type logic here...

So the algebra part:

The statement evaluates to 1-(-1) which is 2 .

Its like you have 1 dollar and you subtract 1 doller you own to a friend. Which gives you 2 dollars because you don't have to give him the dollar back (this is technically, you don't really get another dollar).

The Javascript part:

This works because Javascript can calculate string if they are numbers. So Javascript can convert "1" to 1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM