String Interpolation
Much cleaner when concatenating many variables into a string.
// Before
function getName(p) {
return p.firstName + ' ' + p.lastName;
}
// After
function getName(p) {
return `${p.firstName} ${p.lastName}`;
}
Arrow Functions
A clean way to declare functions; they set up auto return.
// Before
const getName = (p) => {
return p.firstName + ' ' + p.lastName;
}
// After
const getName = (p) => `${p.firstName} ${p.lastName}`;
Unary + Operator
A beautiful and elegant way of casting a string variable to a number.
// Before
const handleChange = (e) => {
setAge(parseInt(e.target.value));
}
// After
const handleChange = (e) => {
setAge(Number(e.target.value));
}
Conditional Ternary
Write less code by using this technique; they can even be nested.
// Before
const hasFlags = (p) => {
if (p.warnings || p.errors) {
return true;
} else {
return false;
}
}
// After
const hasFlags = (p) => p.warnings || p.errors ? true : false;
Auto Return Functions
Save another line of code with this super clean technique.
// Before
const hasFlags = (p) => {
return p.warnings || p.errors;
}
// After
const hasFlags = (p) => p.warnings || p.errors;
Auto Return Objects
Results in less code; wrap your object in brackets.
// Before
const editedUsers = users.map(u => {
return {
...u,
status: u.age >= 18 && "18+"
};
});
// After
const editedUsers = users.map(u => ({
...u,
status: u.age >= 18 && "18+"
}));
Check Length
In ES6/JS, "0" equates to "false" - therefore, checking if a length is "> 0" is redundant.
// Before
const hasHistory = (p) => {
return p.history.length > 0 ? true : false;
}
// After
const hasHistory = (p) => p.history.length ? true : false;
Array Includes
In 99% of cases, both methods work perfectly and look clean.
javascript
// Before
const filteredUsers = (term) => {
return users.filter(u => u.name.indexOf(term) > -1);
}
// After
const filteredUsers = (term) => users.filter(u => u.name.includes(term));`
If you have any questions or need further assistance, feel free to reach out:
Website: otmane.tech
Email: elhaddajiotmane@gmail.com
LinkedIn: elhaddaji-otmane
Happy coding!
Top comments (0)