Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between if (x) { foo(); } and x ? foo() : 0;

Tags:

javascript

Snippet 1:

if ( x ) { 
    foo();
}

Snippet 2:

x ? foo() : 0;  

What are the differences between those two snippets?

Edit: Corrected the syntax error.

Update: btw, it seems that there is an even shorter notation:

x && foo();
like image 652
Šime Vidas Avatar asked Dec 17 '22 19:12

Šime Vidas


1 Answers

Snippet #2 is an invalid ECMAScript expression since it lacks the required : blah in order to make it a ternary.

EDIT: There isn't really a difference between the two snippets, they both invoke foo if x is truthy. If x is falsy (undefined/false/empty string/0/) then first snippet wouldn't evaluate to anything, latter snippet would evaluate to 0 but that 0 really has no impact on the script.

like image 103
meder omuraliev Avatar answered Jan 03 '23 04:01

meder omuraliev