Stage 2: Frontend Fundamentals

JavaScript · Lesson 03

Functions

Declarations, expressions, arrow functions, parameters and scope.

JavaScript2 min readFree lesson

Learning Objectives

  • Understand the differences between function declarations, function expressions, and arrow functions.
  • Write reusable functions using parameters and return values.
  • Understand the concept of scope.
  • Use default parameters.
  • Understand the concept of callback functions.

1. Function Declaration

// Function declaration
function greet(name) {
  return `Hello, ${name}!`;
}

console.log(greet("John Doe")); // "Hello, John Doe!"
  • Hoisting: A function declaration can be called before its position in the code.
console.log(sayHi()); // Works (hoisting)

function sayHi() {
  return "Hi!";
}

2. Function Expression

// Assign a function to a variable
const greet = function(name) {
  return `Hello, ${name}!`;
};

console.log(greet("John Doe")); // "Hello, John Doe!"
  • No hoisting: Calling it before the declaration causes an error.

3. Arrow Function (ES6+)

// Basic form
const greet = (name) => {
  return `Hello, ${name}!`;
};

// Parentheses can be omitted when there is a single parameter
const double = n => {
  return n * 2;
};

// Braces and return can be omitted when the function body is a single line
const triple = n => n * 3;
const add = (a, b) => a + b;

console.log(double(5));  // 10
console.log(triple(5));  // 15
console.log(add(3, 4));  // 7

4. Parameters and Return Values

// Multiple parameters
function calculateBMI(weight, height) {
  const bmi = weight / (height * height);
  return bmi.toFixed(1);
}

const myBMI = calculateBMI(70, 1.75);
console.log(`BMI: ${myBMI}`); // "BMI: 22.9"

// A function with no return value (void)
function logMessage(message) {
  console.log(`[LOG] ${message}`);
  // No return → returns undefined
}

5. Default Parameters (ES6+)

// Set default values for parameters
function greet(name = "Guest", lang = "en") {
  if (lang === "en") {
    return `Hello, ${name}!`;
  } else {
    return `Hi, ${name}!`;
  }
}

console.log(greet());                 // "Hello, Guest!"
console.log(greet("John Doe"));       // "Hello, John Doe!"
console.log(greet("Sam", "casual"));  // "Hi, Sam!"

6. Scope

// Global scope
const globalVar = "global variable";

function outer() {
  const outerVar = "outer variable";

  function inner() {
    const innerVar = "inner variable";
    console.log(globalVar); // accessible
    console.log(outerVar);  // accessible (closure)
    console.log(innerVar);  // accessible
  }

  inner();
  // console.log(innerVar); // Error! Cannot access outside inner's scope
}

outer();

7. Callback Functions

A callback function is a function that is passed as an argument to another function and is called later.

// Callback function example
function doTask(task, callback) {
  console.log(`Task started: ${task}`);
  // Call the callback after the task completes
  callback(task);
}

function onComplete(task) {
  console.log(`Task completed: ${task}`);
}

doTask("Save file", onComplete);
// "Task started: Save file"
// "Task completed: Save file"

// Inline callback with an arrow function
doTask("Send data", (task) => {
  console.log(`✅ ${task} succeeded!`);
});

Common Callback Patterns

// setTimeout: runs the callback after n milliseconds
setTimeout(() => {
  console.log("Runs after 1 second");
}, 1000);

// Callbacks in array methods (covered in detail in Lesson 04)
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2); // [2, 4, 6, 8, 10]

Practice Files

  • View the example
  • Check the assignment
  • Assignment solution

Assignment

Assignment 03 — Unit Converter Function Collection

Assignment Goal

Using function declarations, function expressions, and arrow functions, create a collection of unit converter functions.


Requirements

Conversion Functions to Implement

Function name Purpose Formula
kgToLb(kg) kilograms → pounds lb = kg × 2.20462
lbToKg(lb) pounds → kilograms kg = lb / 2.20462
kmToMile(km) kilometers → miles mile = km × 0.621371
mileToKm(mile) miles → kilometers km = mile / 0.621371
celsiusToFahrenheit(c) Celsius → Fahrenheit °F = (°C × 9/5) + 32
fahrenheitToCelsius(f) Fahrenheit → Celsius °C = (°F - 32) × 5/9

Bonus: implement cmToInch(cm) (1 inch = 2.54 cm) and inchToCm(inch) too!

UI Requirements

  1. Separate each conversion group (weight, distance, temperature) into its own section.
  2. In each section, create an input field and 2 direction buttons.
    • Example: [Convert kg → lb] [Convert lb → kg]
  3. Display the result inside each section.
  4. Show results to 3 decimal places.

Example

[Weight conversion]
Input: [    70    ] kg
[Convert kg → lb]  →  154.324 lb
[Convert lb → kg]  →  31.751 kg

Conditions

  • Write the conversion functions as arrow functions.
  • Write each function as a one-line arrow function. (The return value comes right after =>.)
  • If the input is empty or not a number, display an error message.
  • Write all your code in a single HTML file.

Hints

// One-line arrow function example
const kgToLb = kg => kg * 2.20462;
const lbToKg = lb => lb / 2.20462;

// Result to 3 decimal places
const result = kgToLb(70).toFixed(3); // "154.323"

// Shared conversion runner (using a callback)
function convert(inputId, resultId, convertFn, unit) {
  const value = parseFloat(document.getElementById(inputId).value);
  if (isNaN(value)) { /* handle the error */ return; }
  const result = convertFn(value);
  document.getElementById(resultId).textContent = `${result.toFixed(3)} ${unit}`;
}

File Structure

Assignment/
└── index.html   ← write your code here

Grading Criteria

Item Points
All 6 conversion functions correctly implemented as arrow functions 40
UI: section separation, input field, buttons 20
Conversion accuracy and decimal handling 20
Input validation 10
Additional functions (cm↔inch) 10

Total: 100 points (+10 bonus points)

Learn this lesson with a mentor

Work through the Build Your Homepage series on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now