Created
October 4, 2021 19:44
-
-
Save juan-reynoso/49dcf5f576adf2887ada0e30aeceb982 to your computer and use it in GitHub Desktop.
Traditional functions and arrow functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Traditional functions | |
function mySum(x, y){ | |
return x + y; | |
} | |
function myHello(){ | |
return "Hello."; | |
} | |
function myMagicFunction(){ | |
let x = 10; | |
return x + 5; | |
} | |
// Arrow Function With Parameters: | |
let sum = (x, y) => x + y; | |
// Arrow Function Without Parameters: | |
let hello = () => "Hello."; | |
// Arrow Function With Body; | |
let magicFunction = () => { | |
// do something | |
let x = 10; | |
return x + 5 | |
}; | |
console.log("Traditional functions:"); | |
console.log(mySum(2,5)); | |
console.log(myHello()); | |
console.log(myMagicFunction()); | |
console.log("Arrow functions:"); | |
console.log(sum(2,5)); | |
console.log(hello()); | |
console.log(magicFunction()); | |
class Person{ | |
constructor(name, age) { | |
this.name = name; | |
this.age = age; | |
// define methods with arrow functions | |
this.getName = () => { | |
return this.name; | |
} | |
this.getAge = () => { | |
return this.age; | |
} | |
} | |
// define methods with traditional functions | |
sayName(){ | |
return this.name; | |
} | |
sayAge(){ | |
return this.age; | |
} | |
} | |
// create an object | |
let juan = new Person("Juan Reynoso", 36); | |
console.log("Traditional functions:"); | |
console.log(juan.sayName()); | |
console.log(juan.sayAge()); | |
console.log("Arrow functions:"); | |
console.log(juan.getName()); | |
console.log(juan.getAge()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment