JS Shorthand - Variables
Posted on 2021-04-28
Useful JS shorthand (variables)
Declaring Multiple Variables
//Longhand
let a
let b = "abc"
//Shorthand
let a, b = "abc"
Assigning Values to Multiple Variables
//Longhand
x = 1
y = 2
z = 3
//Shorthand
let [x, y, z] = [1, 2, 3]
Assigning Default Values to a Variables
//Longhand
let finalName
let name = getName()
if (name !== null && name !== undefined && name !== "") {
finalName = name
} else {
finalName = "John Doe"
}
//Shorthand
let finalName = getName() || "John Doe"
Swapping the Values of Two Variables
let x = 1, y = 2
//Longhand
const temp = x
x = y
y = temp
//Shorthand
[x, y] = [y, x]
JavaScript