visit
Use Case: Conditional Assignment
Normal JavaScript:
let isAdmin;
if (user.role === 'admin') {
isAdmin = true;
} else {
isAdmin = false;
}
Shorthand:
const isAdmin = user.role === 'admin' ? true : false;
Shorterhand
const isAdmin = user.role === 'admin';
Use Case: Creating Objects with Variables
Normal JavaScript:
const name = 'Leandro';
const age = 30;
const person = {
name: name,
age: age
};
Shorthand:
const name = 'Leandro';
const age = 30;
const person = {
name,
age
};
Use Case: Providing Default Values to Function Parameters
Normal JavaScript:
function greet(name) {
name = name || 'Guest';
return `Hello, ${name}!`;
}
Shorthand:
function greet(name = 'Guest') {
return `Hello, ${name}!`;
}
Caution: be careful with this one. Check out this comment by
Use Case: Fallback for Undefined or Null Values
Normal JavaScript:
const username = getUsernameFromAPI();
const displayName = username ? username : 'Anonymous';
Shorthand:
const username = getUsernameFromAPI();
const displayName = username || 'Anonymous';
Use Case: Swapping Variables
Normal JavaScript:
let a = 5;
let b = 10;
const temp = a;
a = b;
b = temp;
Shorthand:
let a = 5;
let b = 10;
[a, b] = [b, a];
Use Case: Dynamic String Concatenation
Normal JavaScript:
const name = 'Leandro';
const greeting = 'Hello, ' + name + '!';
Shorthand:
const name = 'Leandro';
const greeting = `Hello, ${name}!`;
Use Case: Concise Function Definitions
Normal JavaScript:
function add(a, b) {
return a + b;
}
Shorthand:
const add = (a, b) => a + b;
Use Case: Providing Default Values for Null or Undefined Variables
Normal JavaScript:
const fetchUserData = () => {
return 'leandro' // change to null or undefined to see the behavior
};
const data = fetchUserData();
const username = data !== null && data !== undefined ? data : 'Guest';
Shorthand:
const fetchUserData = () => {
return 'leandro' // change to null or undefined to see the behavior
};
const data = fetchUserData();
const username = data ?? 'Guest';
Use Case: Extracting Object Properties into Variables
Normal JavaScript:
const user = {
name: 'Leandro',
age: 30,
country: 'USA'
};
const name = user.name;
const age = user.age;
const country = user.country;
Shorthand:
const user = {
name: 'Leandro',
age: 30,
country: 'USA'
};
const { name, age, country } = user;
Use Case: Merging Arrays or Objects
Normal JavaScript:
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const mergedArray = arr1.concat(arr2);
Shorthand:
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const mergedArray = [...arr1, ...arr2];
Use Case: Assigning a Default Value to a Variable
Normal JavaScript:
let count;
if (!count) {
count = 0;
}
Shorthand:
let count;
count ||= 0;
Use Case: Avoiding Unnecessary Function Execution
Normal JavaScript:
function fetchData() {
if (shouldFetchData) {
return fetchDataFromAPI();
} else {
return null;
}
}
Shorthand:
function fetchData() {
return shouldFetchData && fetchDataFromAPI();
}