1. Function declarations

A function declaration defines a named function using the function keyword. This is the most traditional way to create functions in JavaScript, and it's the first pattern you'll use constantly at UrbanCart.

๐Ÿ›’
UrbanCart Example
Calculating the cart total

When a customer adds items to their UrbanCart, we need a function to sum up all the prices. Instead of writing the same addition logic in 15 different places, we write it once as a function and call it whenever we need a total.

cart.js Function Declaration
Hoisting: Function declarations are hoisted โ€” JavaScript moves them to the top of their scope before execution. This means you can call a declared function before the line where it's defined. This is unique to function declarations; expressions and arrows are not hoisted.
hoisting.js Hoisting in action

2. Function expressions

A function expression assigns an anonymous (unnamed) function to a variable. Unlike declarations, expressions are not hoisted โ€” you must define them before you call them.

discount.js Function Expression
Declaration vs Expression: Use declarations when you want hoisting (helper functions that get called throughout a file). Use expressions when you want to prevent the function from being used before it's defined โ€” this makes your code more predictable.
๐Ÿ“

Declaration

function name() {}
Hoisted. Can be called before definition. Named automatically.

๐Ÿ“ฆ

Expression

const name = function() {}
Not hoisted. Must be defined first. Stored in a variable.

3. Arrow functions

Arrow functions (introduced in ES6) provide a shorter syntax for writing functions. They're perfect for small, concise operations โ€” exactly the kind of utility functions UrbanCart needs everywhere.

format.js Arrow Function
When to use arrows: Use arrow functions for short callbacks, array methods (.map(), .filter(), .forEach()), and utility functions. Use regular function declarations for top-level named functions and methods that need their own this binding.

4. Parameters & defaults

Functions accept parameters โ€” placeholders for the data you pass in when calling the function. ES6 introduced default parameters, which provide fallback values when no argument is supplied.

discount.js Default Parameters
Important: Default parameters only kick in when the argument is undefined โ€” not when it's null or 0. Passing applyDiscount(1000, 0) uses 0, not the default.

5. Return values

Functions return data using the return keyword. Once return executes, the function stops immediately โ€” any code after it won't run. If you omit return, the function returns undefined.

returns.js Return Values

6. Scope

Scope determines where a variable is accessible. JavaScript has three scope levels: global, function, and block. Understanding scope prevents bugs and keeps your UrbanCart code predictable.

Scope Levels
Global Scope
Accessible everywhere
โŠƒ
Function Scope
Inside function only
โŠƒ
Block Scope
Inside { } only
scope.js Scope Rules
Rule of thumb: Always declare variables with const or let (never var). Use const by default, let only when you need to reassign. This keeps scope tight and prevents accidental global variables.

7. Callbacks intro

A callback is a function passed as an argument to another function. The receiving function "calls back" your function at the right time. This is a foundational pattern in JavaScript โ€” you'll use it with array methods, event handlers, and async operations throughout UrbanCart.

callbacks.js Callback Functions
Arrow shorthand: Callbacks are where arrow functions really shine. Compare: products.filter(function(p) { return p.price > 2000; }) vs products.filter(p => p.price > 2000) โ€” same result, half the code.

Try It Yourself #1

Create three UrbanCart utility functions: calculateTotal(), applyDiscount(), and formatPrice(). Run them with the sample cart data to see the results.

๐Ÿ› ๏ธ Try It Yourself โ€” UrbanCart Utility Functions
Output

Try It Yourself #2

Build a mini order processor that chains functions together. Calculate the subtotal, apply a member discount, add shipping, and format the final output โ€” all using functions you write.

๐Ÿ› ๏ธ Try It Yourself โ€” Order Processor
Output

Test your knowledge

Question 1 of 5
What is special about function declarations compared to function expressions?
Question 2 of 5
What does applyDiscount(1000) return if the function is defined as function applyDiscount(price, discount = 0.1) { return price * (1 - discount); }?
Question 3 of 5
Which of the following is a valid arrow function that doubles a number?
Question 4 of 5
A variable declared with let inside a function is accessible where?
Question 5 of 5
What is a callback function?
0
/5
Great job!

๐Ÿ† Challenge: Build a coupon system

Put your function skills to the test. Build a coupon system for UrbanCart using everything you learned:

  1. Create a validateCoupon(code) function that checks if a coupon code is valid (e.g., "SAVE10", "WELCOME20", "FLAT500")
  2. Create a getCouponDiscount(code, subtotal) function that returns the discount amount โ€” percentage coupons use a rate, FLAT500 subtracts a fixed โ‚น500
  3. Create an applyCoupon(cart, code) function that chains everything: calculates subtotal, validates coupon, applies discount, and returns a formatted receipt string
  4. Use default parameters, arrow functions, and callbacks where they make the code cleaner

Bonus: Add a forEach callback to print each cart item in the receipt.

Africa & India's Best AI Academy
๐Ÿค– AI-first ๐ŸŽ“ Placement Assistance

You just mastered JavaScript functions.
Now build a full-stack career.

Join the Best AI Programs โ€” three 5-month courses, fully online, with placement assistance. Week 1 is free.

Explore our AI-era courses โ†’