Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript "If" - Why does it not fail?

I'm implementing mocha tests in nodejs app application and once again I made a mistake.

Instead of writing it('should ...' , function(done){}); I wrote if('should ...

if ('should implment rest style "destroy" method', function(done){
        request(app)
            .del('/restLike/41')
            .expect(200, '<h1>Rest Like Destroy: 41</h1>')
            .end(done);
    });

Stupid mistake, if instead of it. But why does it not fail, why nodes v8 compiles it?

like image 698
irla Avatar asked Dec 02 '25 05:12

irla


1 Answers

It's valid JavaScript!

It is an if statement whose condition is an expression with the comma operator and whose body is the empty statement (;).

The comma operator is defined here. The left-hand operand of the comma operator here is a string, and the right-hand operand is a function expression. The result of the comma-operator expression (which is the function expression) happens to be truthy and the empty body is executed but does nothing.

It may look strange, but it parses -- and executes -- just fine.

like image 63
Ray Toal Avatar answered Dec 03 '25 17:12

Ray Toal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!