DEV Community

Harshit Kedia
Harshit Kedia

Posted on

Useful javascript ES6 nuggets

Some important points I summarized while revising ES6 from freecodecamp:

:> Using Destructuring Assignment to Assign Variables from Nested Objects:
Eg: we have object LOCAL_FORECAST:

const LOCAL_FORECAST = {
  yesterday: { low: 61, high: 75 },
  today: { low: 64, high: 77 },
  tomorrow: { low: 68, high: 80 }
};
Enter fullscreen mode Exit fullscreen mode

We assign variables lowToday and highToday with values LOCAL_FORECAST.today.low and LOCAL_FORECAST.today.high wusing this one liner code:

const {today:{low:lowToday,high:highToday}}=LOCAL_FORECAST
Enter fullscreen mode Exit fullscreen mode

:> We can access the value at any index in an array with destructuring by using commas to reach the desired index:

const [a, b,,, c] = [1, 2, 3, 4, 5, 6];
Enter fullscreen mode Exit fullscreen mode

The values of a, b, and c become 1, 2 and 5 respectively.

*Using destructuring assignment to swap the values of a and b, if we re-declare a or b while destructuring if already declared in the first let statement, then it will give an error. Eg, below code will give error:

let a = 8, b = 6;
const [b,a]=[a,b]
Enter fullscreen mode Exit fullscreen mode

Correct way is:

let a = 8, b = 6;
[b,a]=[a,b]
Enter fullscreen mode Exit fullscreen mode

*also, using const instead of let will give error above

const [a, b, ...arr] = [1, 2, 3, 4, 5, 7];
Here a, b and arr are new objects declared and their values are 1, 2 and [3, 4, 5, 7] respectively.
*behavior is similar to Array.prototype.slice()

:> Using Destructuring Assignment to Pass an Object as a Function's Parameters

const profileUpdate = (profileData) => {
  const { name, age, nationality, location } = profileData;
}
Enter fullscreen mode Exit fullscreen mode

can be effectively written as:
const profileUpdate = ({ name, age, nationality, location }) => {}

:> Creating Strings using Template Literals:
Syntax: Can add ${obj.prop}
*We use backticks, not inverted commas, put the value as ${object.property} and there is no need of putting \n for new line, we can include expressions in string literal, eg: ${a + b}

:> ES6 provides syntax to eliminate the redundancy of having to write x: x. You can simply write x once, and it will be converted tox: x (or something equivalent) for and as in the following:
const getMousePosition = (x, y) => ({ x, y });

:> Example of using function in an object in ES6:

const bicycle = {
  gear: 2,
  setGear(newGear) {
    this.gear = newGear;
  }
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)