Asher Cohen
Back to posts

JavaScript Quick Tips and Shorthand Techniques

Practical JavaScript shortcuts — ternary operators, short-circuit evaluation, destructuring, arrow functions, and modern syntax for cleaner code

Introduction

Writing clean, concise JavaScript isn't about being clever — it's about expressing intent clearly with less code. These shorthand techniques reduce boilerplate while making your code more readable.

Conditional Shorthand

Ternary Operator

Replace simple if...else with the ternary operator:

// ❌ Longhand
const x = 20;
let answer;
if (x > 10) {
  answer = 'greater than 10';
} else {
  answer = 'less than 10';
}

// ✅ Shorthand
const answer = x > 10 ? 'greater than 10' : 'less than 10';

// Nested ternary (use sparingly)
const grade = score > 90 ? 'A' : score > 80 ? 'B' : 'C';

Short-Circuit Evaluation

Use logical operators for default values:

// ❌ Longhand
let variable2;
if (variable1 !== null && variable1 !== undefined && variable1 !== '') {
  variable2 = variable1;
} else {
  variable2 = 'default';
}

// ✅ Shorthand
const variable2 = variable1 || 'default';

// Modern: Nullish coalescing (only null/undefined)
const name = userInput ?? 'Anonymous';

If Presence Check

// ❌ Longhand
if (isValid === true) { /* ... */ }

// ✅ Shorthand
if (isValid) { /* ... */ }

// Negation
if (!isError) { /* ... */ }

Variable Declarations

// ❌ Longhand
let x;
let y;
let z = 3;

// ✅ Shorthand
let x, y, z = 3;

// Destructuring assignment
const [first, second] = [1, 2];
const { name, age } = user;

Loop Shorthand

const fruits = ['mango', 'peach', 'banana'];

// ❌ Longhand
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

// ✅ for...of (values)
for (const fruit of fruits) {
  console.log(fruit);
}

// ✅ for...in (indices/keys)
for (const index in fruits) {
  console.log(index);
}

// ✅ forEach
fruits.forEach((fruit, index) => {
  console.log(`${index}: ${fruit}`);
});

Function Shorthand

Arrow Functions

// ❌ Longhand
function add(a, b) {
  return a + b;
}

// ✅ Arrow function
const add = (a, b) => a + b;

// Single parameter — no parentheses needed
const double = x => x * 2;

// Returning objects — wrap in parentheses
const createUser = (name, age) => ({ name, age });

Method Shorthand in Objects

// ❌ Longhand
const user = {
  name: 'Alice',
  greet: function() {
    return `Hello, ${this.name}`;
  }
};

// ✅ Shorthand
const user = {
  name: 'Alice',
  greet() {
    return `Hello, ${this.name}`;
  }
};

Object and Array Shorthand

Property Value Shorthand

const name = 'Alice';
const age = 30;

// ❌ Longhand
const user = { name: name, age: age };

// ✅ Shorthand
const user = { name, age };

Spread Operator

// Combine arrays
const combined = [...arr1, ...arr2];

// Combine objects
const merged = { ...defaults, ...overrides };

// Copy (shallow)
const copy = [...originalArray];
const objCopy = { ...originalObject };

Destructuring

// Object destructuring
const { name, age, city = 'Unknown' } = user;

// Array destructuring
const [first, second, ...rest] = array;

// Function parameters
function greet({ name, greeting = 'Hello' }) {
  return `${greeting}, ${name}`;
}

String Shorthand

Template Literals

const name = 'Alice';
const age = 30;

// ❌ Longhand
const message = 'Hello, ' + name + '. You are ' + age + ' years old.';

// ✅ Template literal
const message = `Hello, ${name}. You are ${age} years old.`;

// Multi-line
const html = `
  <div>
    <h1>${title}</h1>
    <p>${content}</p>
  </div>
`;

Number Shorthand

// Numeric separators
const billion = 1_000_000_000;
const hex = 0xFF_FF_FF;

// Exponent notation
const million = 1e6;    // 1,000,000
const micro = 1e-6;     // 0.000001

// Convert to number
const num = +'42';      // 42
const num2 = ~~'42.7';  // 42 (floor)

Advanced Patterns

Optional Chaining

// ❌ Longhand
const city = user && user.address && user.address.city;

// ✅ Optional chaining
const city = user?.address?.city;

// With methods
const result = obj?.method?.();

// With arrays
const first = arr?.[0];

Nullish Coalescing

// ❌ || treats 0 and '' as falsy
const count = value || 10; // 0 becomes 10!

// ✅ ?? only checks null/undefined
const count = value ?? 10; // 0 stays 0

Logical Assignment

// ❌ Longhand
if (!user.name) user.name = 'Anonymous';

// ✅ Logical OR assignment
user.name ||= 'Anonymous';

// Nullish assignment
user.name ??= 'Anonymous';

// AND assignment
user.isActive &&= hasPermission;

Replacing Switch with Objects

// ❌ Switch statement
function getColor(type) {
  switch (type) {
    case 'success': return 'green';
    case 'warning': return 'orange';
    case 'error': return 'red';
    default: return 'blue';
  }
}

// ✅ Object lookup
const colors = {
  success: 'green',
  warning: 'orange',
  error: 'red'
};
const getColor = (type) => colors[type] ?? 'blue';

Best Practices

Do's

// ✅ Use ternary for simple conditionals
const label = isLoading ? 'Loading...' : 'Submit';

// ✅ Use template literals for strings
const msg = `Hello, ${name}`;

// ✅ Use destructuring for cleaner code
const { id, title } = post;

// ✅ Use optional chaining for safe access
const city = user?.address?.city;

// ✅ Use arrow functions for short callbacks
items.map(item => item.name);

Don'ts

// ❌ Don't nest ternaries deeply
const x = a ? b ? c : d : e ? f : g; // Unreadable!

// ❌ Don't use shorthand when it hurts clarity
const x = a && b && c && doSomething(); // Confusing intent

// ❌ Don't forget that || treats 0 and '' as falsy
const count = value || 10; // Use ?? for null/undefined

// ❌ Don't over-use shorthand
// Sometimes explicit is better than concise

Summary Table

PatternLonghandShorthand
Conditionalif...elseTernary ? :
Default valueif (!x) x = defaultx || default or x ?? default
String concat'a' + b + 'c'`a${b}c`
Functionfunction() { return x; }() => x
Object prop{ x: x, y: y }{ x, y }
Safe accessa && a.b && a.b.ca?.b?.c
Loopfor (let i = 0; ...)for...of

Conclusion

JavaScript shorthand isn't about writing the shortest code — it's about writing the clearest code:

  • Ternary for simple either/or logic
  • Template literals for readable string building
  • Destructuring for extracting values cleanly
  • Optional chaining for safe property access
  • Arrow functions for concise callbacks

Use shorthand when it improves readability. When in doubt, prefer clarity over brevity.

#javascript #tips #shorthand #clean-code #es6 #web-development