author | tags |
---|---|
emchateau |
javascript |
Read the value of a deeply nested property, without worrying about null or undefined value
if (user && user.hobbies && user.hobbies[i]) {
hobby = users.hobbies[i].description;
}
hobby = user?.hobbies?.[i]?.description;
Use Array.includes method to replace very long, repeating conditional statements. Where N options are valid.
if (type === "hour" || type === "day" || type === "month" || ...) {
// much more typing required, harder to maintain
}
if (["hour", "day", "week", "month"].includes(type)) {
// it's easier to add/remove/maintain
}
Unpack values from objects into distinct variables.
function renderUser(user) {
const firstName = user.firstName;
const lastName = user.lstName;
const age = user.age;
// ...
}
function renderUser({ firstName, lastName, age }) {
//...
}
const arr = ["19", "30", "30"];
const hours = arr[0];
const minutes = arr[1];
const seconds = arr[2];
const arr = ["19", "30", "30"];
const [hours, minutes, seconds] = arr;
// we can also use destructuring directly
const [hours, minutes, seconds] = str.split(":");
Use the unary operator (+) to cast any JS value to a number
// Number(e.target.value) is casting string value to number
const handleChange = (e) => setValue(Number(e.target.value));
// The unary operator is casting string value to number
const handleChange = (e) => setValue(+e.target.value);
Use spred operator to merge properties of multiple objects.
const defaultOptions = {
disabled: true,
fontSize: 16,
}
const config = {};
config.disabled = defaultOptions.disabled;
config.fontSize = defaultOptions.fontSize;
const defaultOptions = {
disabled: true,
fontSize: 16,
}
const config = { ...defaultOptions };
You can use bracket notation to get a character by index form a string.
const str = "abc";
const c = str.charAt(2);
const str = "abc";
const c = str[2];