Member-only story
JavaScript has grown from a simple scripting language to a robust programming platform powering complex web applications. With its flexibility and ubiquity, it’s a must-know for every developer today. However, JavaScript has its quirks and obscure facets that aren’t immediately obvious.
Here are some top JavaScript tricks that can help you write cleaner, more efficient code:
Short-Circuit Evaluation
JavaScript evaluators use short-circuit evaluation when evaluating logical expressions. This means they stop evaluating as soon as they can determine the overall result. You can use this behavior to simplify conditional checks:
// If x is truthy, function won't be called
function(x) x || executeFunction();
// If x is already defined, value won't be set again
const value = x ?? setValue();
Ternary Operator
The ternary operator provides a concise syntax for basic conditional logic. It takes three operands — a condition followed by a ? and two expressions to evaluate based on truthiness.
let accessAllowed = (age > 18) ? true : false;
// Can replace:
let access;
if (age > 18) {…