Day 2 of 21 Days of Javascript
Day 2 Learnings
Today I firmed up three main ways of writing functions
- Function Expressions (Need semicolon at the end, not hoisted.)
- Function Declarations (No semicolon, hoisted.)
- Arrow Functions (Short syntax, , not hoisted.)
Here's some example code:
// 1. Function Expression
// - Assigned to a variable named min
// - Needs a semicolon at the end
// - Not hoisted: can't call before this line
const min = function(a, b) {
return (a < b) ? a : b;
};
console.log(min(3, 5)); // Outputs: 3
// 2. Function Declaration
// - Declares a function named min
// - No semicolon needed
// - Hoisted: can call before declaration
console.log(min(4, 9)); // Works because of hoisting, outputs: 4
function min(a, b) {
return (a < b) ? a : b;
}
// 3. Arrow Function
// - Assigned to a variable named min
// - Needs a semicolon at the end
// - Not hoisted: can't call before this line
const min = (a, b) => (a < b) ? a : b;
console.log(min(6, 2)); // Outputs: 2