Today I Learned - Rocky Kev

TIL that you can chain if/else using ternary conditionals

POSTED ON:

TAGS:

Today I learned that the ternary operator is right-associative, which means it can be "chained" in the following way, similar to an if … else if … else if … else chain.

function example() {
return condition1 ? value1
: condition2 ? value2
: condition3 ? value3
: value4;
}

// Equivalent to:

function example() {
if (condition1) { return value1; }
else if (condition2) { return value2; }
else if (condition3) { return value3; }
else { return value4; }
}

REFERENCE:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator#conditional_chains


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.