Quicker way to declare several strings.
// Longhand
let first = "Roman";
let last = "Castillo";
// Shorthand
let first = "Roman", last = "Castillo";
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(" ");
Great for short text checks.
// Longhand
let ageGroup;
if (age > 18) {
ageGroup = "Adult";
} else {
ageGroup = "Minor";
}
// Shorthand
let ageGroup = age > 18 ? "Adult" : "Minor";
Use a fallback string when the first is empty.
// Longhand
let username = inputName;
if (!username) {
username = "Guest";
}
// Shorthand
let username = inputName || "Guest";
Prevents errors when a string is empty/null.
// Longhand
if (message) {
console.log(message);
}
// Shorthand
message && console.log(message);
Cleaner string building.
// Longhand
let text = "Hello " + name + "!";
// Shorthand
let text = `Hello ${name}!`;
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`;
Instead of multiple OR conditions.
// Longhand
if (role === "admin" || role === "owner" || role === "mod") {
allow();
}
// Shorthand
["admin", "owner", "mod"].includes(role) && allow();
Shortcut for parseInt/parseFloat.
// Longhand
let n = parseInt("25");
// Shorthand
let n = +"25";
Cleaner than charAt().
// Longhand
let letter = word.charAt(0);
// Shorthand
let letter = word[0];