Cloudboy22
Cloudboy22

Reputation: 1514

JavaScript ignores extra spaces?

In this JavaScript quiz at WsCube Tech there was a question whether JavaScript ignores extra spaces. The correct answer was “False”.

7. JavaScript ignores extra spaces: ◉ True ✗ — ⭕ False ✓

Isn’t JavaScript white-space independent? I have read in many blogs that it is. So why is my answer wrong?

Upvotes: 2

Views: 12498

Answers (2)

Sebastian Simon
Sebastian Simon

Reputation: 19485

I seriously wouldn’t trust that site…

Directly conflicting answers

That’s the short, sufficient answer I could give, but I’d like to say two other things:

Firstly, JavaScript doesn’t ignore spaces within strings:

var str = "Hello                World";

This string has 16 spaces and they won’t get ignored just like that. However, in-between some operators, keywords and tokens, JavaScript does ignore spaces:

var   test  = [ 0 , 1  ,     3    ]       .  slice  (      2  )      ;

This line is parsed as

var test=[0,1,3].slice(2);

Still, the space between var and test isn’t ignored. Not all spaces are equal. This quiz question cannot be answered in its current form — well, or two forms…

Secondly, that quiz has a lot of inconsistencies, false information, outdated information and promotes bad practice. I’ve just sent them a huge list of things wrong with the quiz…

It’s much safer to stick to a more “trusted” site like the Mozilla Developer Network.

Upvotes: 3

Thilo
Thilo

Reputation: 262504

For one thing, you can terminate expressions by a new line.

var x = 1  // no semicolon
console.info(x)

Also look at this (which returns undefined):

return
   12

Upvotes: 1

Related Questions