There are bulit in methods we could use to do this but we'll just use the (+) operator in front of the string value
// Longhand
let bigNum = parseInt('593');
let floatNum = parseFloat ('48.6');
// Shorthand
let bigNum = +'593';
let floatNum = +'48.6';
We can assign variables in one line with the array destructuring demonstrated below.
// Longhand
let scion, cadillac, infiniti;
scion = toyota;
cadillac = generalMotors;
infiniti = nissan;
// Shorthand
let [scion, cadillac, infiniti] = [toyota, generalMotors, nissan];
This is a great alternative for small if/else statements.
let age = 17;
// Longhand
let msg;
if (age >= 18) {
msg = 'Adult';
} else {
msg = 'Minor';
}
// Shorthand
let msg = age >= 18 ? 'Adult' : 'Minor';
Use || or ?? to go back to a default value.
// Longhand
let username;
let result = getUserName();
if (result !== null && result !== undefined && result !== "") {
username = result;
} else {
username = "Guest";
}
// Shorthand
let username = getUserName() || "Guest";
// Shorthand 2
let username = getUserName() ?? "Guest";
&&) Short circuit evaluationIf you're calling a function and the variable is true use this as an alternative.
// Longhand
if (appOpen) {
goToInstagram();
}
// Shorthand
appOpen && goToInstagram();
we often use a third variable, but we can use array destructuring here again.
// Longhand
let a = 10, b = 20;
let temp = a;
a = b;
b = temp;
// Shorthand
[a, b] = [b, a];
Provides a short and clean syntax for our small functions.
// Longhand
function multiply(x, y) {
return x * y;
}
// Shorthand
const multiply = (x, y) => x * y;
Easier to read and write template literals rather than to do concatenation.
// Longhand
console.log("What a beautiful " + car + " man! Is it a " + transmisson "?");
// Shorthand
console.log(`What a beautiful ${car} man! Is it a ${transmisson} ?`);
Backticks allow us to keep a continous flow instead of stopping and adding the + operator with a new line sequence of \n
// Longhand
console.log ("Could you \n" +
"imagine typing \n" +
"this way?!");
// Shorthand
console.log (`This is
way better than
the longhand`);
Double asterisk allows us to not use Math.pow()
// Longhand
let power = Math.pow(5,5);
// Shorthand
let power = 5**5;