Skip to content

Instantly share code, notes, and snippets.

@JWardee JWardee/ArrowFunctions.js
Last active Jul 31, 2019

Embed
What would you like to do?
ES6 Examples
/**
* Arrow functions
*/
var names = ['John', 'Jane', 'Jill'];
// Old
names.map(function(name) {
console.log(name);
});
// Standard arrow functions
names.map((name) => {
console.log(name);
});
// Can be shortened to
names.map(name => console.log(name));
// ---
// Before ES6
$('.btn').on('click', function() {
var _this = $(this);
setTimeout(() => {
_this.addClass('clicked');
}, 100);
});
// After ES6
$('.btn').on('click', function() {
setTimeout(() => {
$(this).addClass('clicked');
}, 100);
});
// Can be further shortened to
$('.btn').on('click', function() {
setTimeout(x => $(this).addClass('clicked'), 100);
});
// And again...
$('.btn').on('click', e => setTimeout(x => $(this).addClass('clicked'), 100));
/**
* Cloning Objects
*/
var enemy1 = {
health: 100,
mana: 50
};
// Before ES6
var enemy2 = Object.assign({}, enemy1, {
health: 120,
stamina: 75
});
// After ES6
var enemy2 = {...enemy1,
health: 120,
stamina: 75
};
/**
* Computed property names
*/
var names = ['John', 'Jane', 'Jill'];
var ages = [25, 27, 35];
// Not possible before ES6
// ---
// After ES6
var names_with_ages = {
[names[0]]: ages[0],
[names[1]]: ages[1],
[names[2]]: ages[2]
};
/**
* Default function parameters
*/
// Before ES6
function say_hello(name) {
if (typeof name == 'undefined') {
name = 'John Doe';
}
console.log('Hello from ' + name);
}
// After ES6
function say_hello(name = 'John Doe') {
console.log(`Hello from ${name}`);
}
/**
* Object shorthand
*/
var name = 'Darren';
var age = 45;
var gender = 'Unknown';
// Before ES6
var data = {
name: name,
age: age,
gender: gender
};
// After ES6
var data = { name, age, gender };
/**
* Template literals
*/
// Before ES6
var foo = 'First name: ' + first_name + '\n'
'Last name: ' + last_name + '\n'
'Age: ' + age;
// After ES6
var foo = `First name: ${first_name}
Last name: ${last_name}
Age: ${age}`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.