Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does 0.-5 evaluate to -5?

Suppose I write 0.5 as 0.-5 in unexpected way, but it can still run. What does 0. in 0.-5 do so that it can still run and evaluates to -5?

I also tried alert(0.-5+1) which prints -4, does JavaScript ignore 0. in 0.-5?

like image 761
ocomfd Avatar asked Feb 25 '19 03:02

ocomfd


3 Answers

Trailing digits after a . are optional:

console.log(0. === 0); // true

So

0.-5

evalutes to

0 - 5

which is just -5. Similarly,

0.-5+1

is

0 - 5 + 1

which is

-5 + 1

or -4.

like image 179
CertainPerformance Avatar answered Nov 17 '22 04:11

CertainPerformance


0.-5 could be successfully parsed as 0.[1], - and 5. Below is the abstract syntax tree for the expression generated by AST explorer:

Parse tree generated by AST explorer

This (in an unexpected way) is valid JavaScript and evaluates to -5.


[1] According to the grammar for numeric literals the decimal digits and exponent parts are optional:

NumericLiteral ::
  DecimalLiteral
  [...]

DecimalLiteral ::
  DecimalIntegerLiteral . DecimalDigitsopt ExponentPartopt

like image 26
Salman A Avatar answered Nov 17 '22 05:11

Salman A


In JS you can express a number with optional decimal point.

x = 5.;    //5
x = 5. + 6.   //11

And as of Tvde1's comment, any Number method can be applied too.

5..toString()

This syntax let us run the Number functions without parentheses.

5.toString() //error
(5).toString() //good
5..toString() //good
5 .toString() // awesome

See this question to find out why.

like image 40
Charlie Avatar answered Nov 17 '22 04:11

Charlie