Why if (true && false); {foo (); } valid?

This is one unpleasant mistake that took me half an hour. The compiler considers this to be valid code, and when it evaluates the statement, it still calls foo ():

if(true && false);{ foo(); }

Why is this really and why is foo () still being called?

+3
source share
8 answers

Well, you didn’t ask a question, but I feel obligated to tell you why the compiler is right and the code is valid (sorry, SO people):

if (true && false);

This is just an empty statement that is executed if the condition is met (in this case, it is not fulfilled due to && false, therefore, nothing happens (but nothing happens in any case)). The statement is empty because the closing bracket is immediately followed by a semicolon.

{ foo(); }

, . if, if. , . if.

+22

. if .

if:

:

if (true && false) { foo(); }

, .

, , , , , , , .

+8

, . ;, if .

if (true && false);

//...

{ foo(); }
+5

) {

+2
if (true && false) {

foo();

}

, , .

if(true && false);

if-statement ; :

foo();

.

+2
if(true && false);

; ( ) if foo();

 if(true && false)
    { foo(); }
+1

, , , . , ; if, , .

, .

+1

, , : jslint, .

For example, here is the javascript buffer in emacs, flymake-for-javascript - emacs' on-the-fly validation syntax - included:

enter image description here

(ps: this image also uses flymake-cursor.el to automatically display the error message below)

JSLint can be run from the command line, it can be included in the automatic build process, or it can be integrated into a development tool. If you have not verified this, do so. You will learn some good Javascript coding habits.

-1
source

All Articles