DEV Community

ELHADADJI otmane
ELHADADJI otmane

Posted on

Mastering ES6: Elevate Your Code to the Next Level! 🚀

Image description

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}`;
}
Enter fullscreen mode Exit fullscreen mode

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}`;
Enter fullscreen mode Exit fullscreen mode

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));
}
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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+"
}));
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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!
Enter fullscreen mode Exit fullscreen mode

Top comments (0)