Examples of ES6+ Features:
JavaScript Functions:
Function w/ No Parameters:
- classic version:
function sayHi() {
return "Hi there.";
}
- ES6+ version:
const sayHi = () => "Hi there.";
Function w/One Parameter:
function sayHi(userNm) {
return "Hi there " + userNm + ".";
}
- ES6+ version:
const sayHi = userNm => "Hi there " + userNm + ".";
Function w/Two Parameters:
function sayHi(userNm, userTitle) {
return "Hi there " + userTitle + " " + userNm + ".";
}
- ES6+ version:
const sayHi = (userNm, userTitle) => "Hi there " + userTitle + " " + userNm + ".";
JavaScript Arrays:
Spread Operator:
const numStrings = ['one', 'two', 'three', 'four'];
const numStrings2 = [...numStrings, 'five', 'six', 'seven'];
console.log(numStrings2)
// output: ['one', 'two', 'three', 'four', 'five', 'six', 'seven']
- ES6+ version:
const userAcct = { firstName: 'Tom', lastName: 'Testor', age: 25 };
const userAcct += { ...userAcct, role: 'testor' };
Destructuring Operations:
const husbands = [tom, terry, todd];
const wives = [tina, terri, nicki] = husbands;
console.log("Tina's husband: " + tina);
// output: Tina's husband: tom
let husbands = {tom: 40, terry: 71, todd: 102};
let ages = {old, older, oldest} = husbands;
console.log("older: " + older);
// output: older: 71
Example of Destructuring w/ an ES6 function:
Note that the order of the ingredients for cakeMix does not matter.
let cakeIngredients = { flour: '3 cups', sugar: '1/2 cup', butter: '4 tablespoons', chocolate: '1/4 cup', eggs: 2, temperature: 350};
let cakeMix = ({sugar, flour, butter, chocolate, eggs, temperature}) => `Mix dry ingredients ${flour} flour and ${sugar} sugar. Add the ${eggs} eggs and ${butter} butter, and mix until even. Stir in the ${chocolate} chocolate. Bake at ${temperature} degrees.`
console.log("Instructions: " + cakeMix);
// output: Instructions: Mix dry ingredients 3 cups flour and 1/2 cup sugar. Add the 2 eggs and 4 tablespoons butter, and mix until even. Stir in the 1/4 cup chocolate. Bake at 350 degrees.
Template Strings:
Note: ` is called a backtick, and the constant or variable is wrapped in ${variableName} within the backticks
let sayHi = "Hi";
let name = "Tom";
let query = "What time is it?";
let question = `${sayHi}, ${name}. ${query}`;
console.log(question);
// output: Hi Tom. What time is it?
previous page
|