Omitting the Second Expression When Using the If-Else Shorthand

Omitting the second expression when using the if-else shorthand

This is also an option:

x==2 && dosomething();

dosomething() will only be called if x==2 is evaluated to true. This is called Short-circuiting.

It is not commonly used in cases like this and you really shouldn't write code like this. I encourage this simpler approach:

if(x==2) dosomething();

You should write readable code at all times; if you are worried about file size, just create a minified version of it with help of one of the many JS compressors. (e.g Google's Closure Compiler)

JavaScript shorthand if statement, without the else portion

you can use && operator - second operand expression is executed only if first is true

direction == "right" && slideOffset += $(".range-slide").width()

in my opinion if(conditon) expression is more readable than condition && expression

Python equivalent of omitting second part of ternary operator (a if a else b)

You can use or here as an empty string evaluates as a Falsey value:

result = myFunc() or False

Refer to Truth Value Testing

Python shorthand using only if, excluding the else part

Perhaps you can use:

found_target = (qo_cplId == cpl_id)

It gives you the same boolean output though, True/False.

php if else with function shorthand

You don't use the if keyword when writing a ternary expression.

($abc != '') ? msg($abc) : msg('nope');

or

msg($abc != '' ? $abc : 'nope');

How to use echo along with shorthand IF, ELSEIF and ELSE

Check the variable again if the statement is false and you need to add parenthesis around the entire else block

echo ($gender == 'male') ? 'M' : (($gender == 'female') ? 'F' : 'undefined');


Related Topics



Leave a reply



Submit