const doubled = [1, 2, 3].map((number) => {
return number * 2;
});
// Can be shortened to:
const doubled = [1, 2, 3].map((number) => return number * 2);
// Can be further shortened to:
const doubled = [1, 2, 3].map((number) => number * 2);
// Can be further shortened to:
const doubled = [1, 2, 3].map(number => number * 2);
// => [2, 4, 6]
// Using anonymous function
function ClickCounter(element) {
this.clicks = 0;
// Store scope for later
var self = this;
element.addEventListener('click', function () {
++self.clicks;
});
}
// Using arrow function
function ClickCounter(element) {
this.clicks = 0;
// Arrow function with lexical scope
element.addEventListener('click', () => ++this.clicks);
}
class ClickCounter {
constructor(element) {
this.clicks = 0;
element.addEventListener('click', this.increment.bind(this));
}
increment() {
++this.clicks;
}
}
class Animal {
constructor(type) {
this.type = type;
}
}
class Dog extends Animal {
constructor(type, warmBlooded) {
super(type);
this.warmBlooded = warmBlooded;
}
}
// Single assignment
const theAnswerToEverything = 42;
theAnswerToEverything = 41;
// => Error
const anotherAnswerToEverything;
// => Error
let x = 0;
function outer() {
// New variable
let x = 1;
function inner() {
// Also a new variable
let x = 2;
}
}
const suchWow = 'doge';
const propertyName = 'amaze';
const myAmazingObject = {
suchWow, // Assignment shorthand
getAmaze() { // Methods
return 'wow';
},
[propertyName]: 0 // Computed property name
};
// Previously:
var myAmazingObject = {
suchWow: suchWow,
getAmaze: function () {
return 'wow';
}
};
myAmazingObject[propertyName] = 0;
const name = 'Dave';
const question = `What are you doing, ${name}?`;
// => What are you doing, Dave?
const settings = {
dimensions: {
width: 640,
height: 480
},
bpp: 32
};
// Extract object properties into different variables
const { dimensions, bpp } = settings;
function createArray() {
return [1, 2, 3];
}
let a, b, c;
[a, b, c] = createArray();
// => [1, 2, 3];
function greet(greeting = 'Hello', name = 'Clarice') {
return `${greeting}, ${name}`;
}
// => "Hello, Clarice"
function getNumberOfArguments(...args) {
return args.length;
}
getNumberOfArguments(5, true, 10, [1, 2, 3], false);
// => 5;
const goodGuys = ['Yoda', 'Luke Skywalker', 'Han Solo'];
const badGuys = ['Darth Vader', 'Kylo Ren', 'Boba Fett'];
const everyone = ['Padme', ...goodGuys, 'Count Dooku', ...badGuys];
// => ['Padme', 'Yoda', 'Luke Skywalker', 'Han Solo',
// 'Count Dooku', 'Darth Vader', 'Kylo Ren', 'Boba Fett']
// my-lib.js
export function add(x, y) {
return x + y;
}
export const pi = 3.14159265359;
export default function noop() {};
// app.js
import noop, { add, pi } from './my-lib';