Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Output of it "1" - - "1" is 2 how?

Tags:

javascript

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 i.e. "1" - - "1"

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

The one that doesn't works i.e. "1"--"1"

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

It is totally weird for me.

like image 292
Yogesh Yadav Avatar asked Oct 26 '25 14:10

Yogesh Yadav


1 Answers

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.

like image 174
Nisarg Shah Avatar answered Oct 29 '25 03:10

Nisarg Shah