Functions & Arrow Syntax

🟨 JavaScript Lesson 7 Beginner

Functions are the core building blocks of JavaScript. JavaScript supports function declarations, function expressions, and modern arrow function syntax.

1 Function Declarations vs. Expressions & Arrow Functions

There are multiple ways to define functions in JavaScript:

  • Function Declaration: Declared directly. These functions are hoisted, meaning you can call them before they are declared in your code file.
  • Function Expression: Stored inside variables. These are not hoisted and throw an error if called early.
  • Arrow Functions (`() => {}`): A compact, modern syntax. Arrow functions do not bind their own `this` context; instead, they inherit `this` lexically from their parent scope.
2 Code Declarations

Let's run a program showcasing declarations, expressions, default parameters, and arrow methods:

JavaScript — Functions ▶ Run Code
// 1. Function Declaration (Hoisted)
console.log("Add(5,10): " + add(5, 10));
function add(x, y) {
    return x + y;
}

// 2. Function Expression (Not Hoisted)
const multiply = function(x, y) {
    return x * y;
};
console.log("Multiply(5,10): " + multiply(5, 10));

// 3. Arrow Function with implicit return (Single line)
const square = x => x * x;
console.log("Square(6): " + square(6));

// 4. Default Parameters
const greet = (name = "Valued Guest") => `Hello, ${name}!`;
console.log(greet());
console.log(greet("Alice"));
3 Code Challenge
Challenge: Write an arrow function called `calculateTotal` that takes a subtotal and an optional tax parameter (which defaults to `0.08` or 8%). Calculate and return the total cost. Invoke it with and without the tax parameter, printing the results.