Skip to content

Instantly share code, notes, and snippets.

@Kishanjvaghela
Last active January 5, 2017 09:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kishanjvaghela/32fb3152559e6b4e236c6715c6dd0491 to your computer and use it in GitHub Desktop.
Save Kishanjvaghela/32fb3152559e6b4e236c6715c6dd0491 to your computer and use it in GitHub Desktop.
Let's Learn ES6 - Arrow Functions
// 1
let add = (a,b) => {
return a+b;
}
console.log(add(4,5));
// 2
let add = (a,b) => a+b;
console.log(add(4,5));
//////////////////////////////
//1
let numbers = [1,2,3,4,5];
let doubled = numbers.map(function(n){
return n*2;
});
console.log(doubled);
/* output
[2, 4, 6, 8, 10]
*/
//////////////////////////////
// 2
let numbers = [1,2,3,4,5];
let doubled = numbers.map(n => n*2);
console.log(doubled);
//1
let person ={
name: 'Kishan',
sayName: function() {
console.log(`I am ${this.name}`);
}
}
person.sayName();
/*
output
"I am Kishan"
*/
/////////////////////////////////////////
//2
let person ={
name: 'Kishan',
sayName: () => {
console.log(`I am ${this.name}`);
}
}
person.sayName();
/*
TypeError: Cannot read property 'name' of undefined
at Object.sayName
Cz Arrow function have Lexical scope
Lexical Scope : scope of a variable so that it may only be called (referenced)
from within the block of code in which it is defined.
*/
////////////////////////////////////
//3
let person ={
name: 'Kishan',
sayName() {
console.log(`I am ${this.name}`);
}
}
person.sayName();
/*
output
"I am Kishan"
*/
//1
let person = {
name: 'Kishan',
hobbies: ['One','Two','Three'],
showHobbies: function(){
this.hobbies.forEach(function(hobby){
console.log(`${this.name} is ${hobby}`);
});
}
}
person.showHobbies();
/*
output:
"JS Bin Output is One"
"JS Bin Output is Two"
"JS Bin Output is Three"
*/
/////////////////////////////
//2
let person ={
name: 'Kishan',
hobbies: ['One','Two','Three'],
showHobbies: function(){
this.hobbies.forEach(hobby => {
console.log(`${this.name} is ${hobby}`);
});
}
}
person.showHobbies();
/* Output:
"Kishan is One"
"Kishan is Two"
"Kishan is Three"
*/
//////////////////
//3
let person ={
name: 'Kishan',
hobbies: ['One','Two','Three'],
showHobbies: function(){
let self = this;
this.hobbies.forEach(function(hobby){
console.log(`${self.name} is ${hobby}`);
});
}
}
person.showHobbies();
/* Output:
"Kishan is One"
"Kishan is Two"
"Kishan is Three"
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment