Basic Functions in JavaScript
function foo() {} vs const foo = () => {}. Hoisting is the difference you feel.
BeginnerFunction ProgramsExample 1 of 3
basic-functions.js
1// Method 1: Function Declaration2function greet(name) {3 return "Hello, " + name + "!";4}56console.log("Function declaration:", greet("John"));78// Method 2: Function Expression9const greet2 = function(name) {10 return "Hello, " + name + "!";11};1213console.log("Function expression:", greet2("Jane"));1415// Method 3: Arrow Function (ES6)16const greet3 = (name) => {17 return "Hello, " + name + "!";18};1920console.log("Arrow function:", greet3("Bob"));2122// Method 4: Arrow Function (one-liner)23const greet4 = name => "Hello, " + name + "!";2425console.log("Arrow one-liner:", greet4("Alice"));2627// Method 5: Function with default parameters28function greet5(name = "Guest") {29 return "Hello, " + name + "!";30}3132console.log("\nWith default:");33console.log(greet5("Tom"));34console.log(greet5());3536// Method 6: Function with multiple parameters37function calculate(a, b, operation = 'add') {38 switch(operation) {39 case 'add':40 return a + b;41 case 'subtract':42 return a - b;43 case 'multiply':44 return a * b;45 case 'divide':46 return a / b;47 default:48 return "Invalid operation";49 }50}5152console.log("\nCalculate function:");53console.log("10 + 5 =", calculate(10, 5, 'add'));54console.log("10 - 5 =", calculate(10, 5, 'subtract'));55console.log("10 * 5 =", calculate(10, 5, 'multiply'));56console.log("10 / 5 =", calculate(10, 5, 'divide'));
Output
Function declaration: Hello, John! Function expression: Hello, Jane! Arrow function: Hello, Bob! Arrow one-liner: Hello, Alice! With default: Hello, Tom! Hello, Guest! Calculate function: 10 + 5 = 15 10 - 5 = 5 10 * 5 = 50 10 / 5 = 2
What's going on
Declarations are hoisted. You can call them above the line. Arrow functions are not.
this inside an arrow is lexical. That is why people switch.