paige
paige

Reputation: 105

Why do I get a syntax error for 2e + 2?

I read a style guide that said to put spaces around operators like +. But when I try to write a number in exponent notation, I get

Uncaught SyntaxError: Invalid or unexpected token

Why?

Here's what I typed into the Chrome console:

a = 2e + 2;a ++

Here's a screenshot of the error:

enter image description here

Here's snippet:

a = 2e + 2;a ++;

Upvotes: 1

Views: 223

Answers (2)

Barmar
Barmar

Reputation: 781096

A number has to be a single token, you can't put spaces in it. So you have to write:

2e+2

2e by itself is not valid syntax for any data type, so you get an error.

Regarding your comment on the question:

I read a js-style-guide which says you should put space before and after "+"

That's good advice when you're using + as an operator (addition or string concatenation). But in 2e+2, + isn't an operator, it's part of the number literal.

Upvotes: 2

nilobarp
nilobarp

Reputation: 4084

The representation is wrong because there mustn't be spaces before and after e it should be var a = 2e+2; a++;

Upvotes: 0

Related Questions