Created
November 1, 2023 16:52
-
-
Save codebubb/e8cecc0a4d9dd06730b57994c54d5990 to your computer and use it in GitHub Desktop.
6 Ways To Write Functions in JavaScript
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
/* | |
1. With a Function declaration | |
Function is hoisted so can be used before it is declared | |
*/ | |
console.log(add(2, 2)); | |
function add(n1, n2) { | |
return n1 + n2; | |
} | |
/* | |
2. With a Function expression | |
Function is not hoisted and creates an anonymous function | |
*/ | |
const subtract = function (n1, n2) { | |
return n1 - n2; | |
} | |
console.log(subtract(2, 2)); | |
/* | |
3. With a Named Function expression | |
Function is not hoisted and creates an named function | |
*/ | |
const myMath = { | |
getFactorial: function factorial(n) { | |
if (n <= 1) { | |
return 1; | |
} | |
return n * factorial(n - 1); | |
}, | |
} | |
console.log(myMath.getFactorial(5)); | |
/* | |
4. Shorthand functions | |
Named functions are created with a shorter syntax | |
*/ | |
const user = { | |
getFullName() { | |
return `${this.firstName} ${this.lastName}` | |
}, | |
firstName: 'James', | |
lastName: 'Bubb', | |
} | |
console.log(user.getFullName()); | |
/* | |
5. Function Constructors | |
Used to create an initialise new objects. 'this' refers to the object being created | |
*/ | |
function User (firstName, lastName) { | |
this.firstName = firstName; | |
this.lastName = lastName; | |
} | |
const james = new User('James', 'Bubb'); | |
console.log(james); | |
/* | |
6. Arrow Functions | |
Inherits the 'this' context from it's surroundings. Doesn't need parentheses around single function arguments and can omit the return keyword if a single line. | |
*/ | |
const square = n => n * n; | |
console.log(square(4)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment