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 Declaration
2function greet(name) {
3 return "Hello, " + name + "!";
4}
5
6console.log("Function declaration:", greet("John"));
7
8// Method 2: Function Expression
9const greet2 = function(name) {
10 return "Hello, " + name + "!";
11};
12
13console.log("Function expression:", greet2("Jane"));
14
15// Method 3: Arrow Function (ES6)
16const greet3 = (name) => {
17 return "Hello, " + name + "!";
18};
19
20console.log("Arrow function:", greet3("Bob"));
21
22// Method 4: Arrow Function (one-liner)
23const greet4 = name => "Hello, " + name + "!";
24
25console.log("Arrow one-liner:", greet4("Alice"));
26
27// Method 5: Function with default parameters
28function greet5(name = "Guest") {
29 return "Hello, " + name + "!";
30}
31
32console.log("\nWith default:");
33console.log(greet5("Tom"));
34console.log(greet5());
35
36// Method 6: Function with multiple parameters
37function 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}
51
52console.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.