10 JavaScript Shorthand Techniques

1. Declare Multiple Variables

Quicker way to declare several strings.

// Longhand
let first = "Roman";
let last = "Castillo";

// Shorthand
let first = "Roman", last = "Castillo";
    
2. Destructure Strings

Split a string into parts quickly.

// Longhand
const name = "Roman Castillo";
const parts = name.split(" ");
const first = parts[0];
const last = parts[1];

// Shorthand
const [first, last] = "Roman Castillo".split(" ");
    
3. Ternary Operator Instead of if/else

Great for short text checks.

// Longhand
let ageGroup;
if (age > 18) {
    ageGroup = "Adult";
} else {
    ageGroup = "Minor";
}

// Shorthand
let ageGroup = age > 18 ? "Adult" : "Minor";
    
4. Default Value (||)

Use a fallback string when the first is empty.

// Longhand
let username = inputName;
if (!username) {
    username = "Guest";
}

// Shorthand
let username = inputName || "Guest";
    
5. Run Code Only If String Exists (&&)

Prevents errors when a string is empty/null.

// Longhand
if (message) {
    console.log(message);
}

// Shorthand
message && console.log(message);
    
6. Template Literals

Cleaner string building.

// Longhand
let text = "Hello " + name + "!";

// Shorthand
let text = `Hello ${name}!`;
    
7. Multiline Strings

Easier than using + and \n.

// Longhand
let bio = "Line one\n" +
          "Line two\n" +
          "Line three";

// Shorthand
let bio = `Line one
Line two
Line three`;
    
8. Check Many Strings Quickly

Instead of multiple OR conditions.

// Longhand
if (role === "admin" || role === "owner" || role === "mod") {
    allow();
}

// Shorthand
["admin", "owner", "mod"].includes(role) && allow();
    
9. Convert String to Number (+)

Shortcut for parseInt/parseFloat.

// Longhand
let n = parseInt("25");

// Shorthand
let n = +"25";
    
10. Get Character by Index

Cleaner than charAt().

// Longhand
let letter = word.charAt(0);

// Shorthand
let letter = word[0];