Creating and Using Functions

Learn how to create reusable blocks of code with functions - the building blocks of organized JavaScript programs.

What are Functions?

// Functions are reusable code blocks
function greet() {
console.log("Hello!");
}
// Call the function
greet(); // Hello!
greet(); // Hello! (reusable)
Hello!
Hello!

Functions allow you to package code into reusable units that can be executed multiple times with different inputs.

Function Declaration

// Basic structure
function functionName(parameters) {
// code to execute
return result; // optional
}

// Example: Add two numbers
function add(a, b) {
return a + b;
}
let sum = add(5, 3); // 8
sum: 8

Declared functions are hoisted (can be called before declaration in the same scope).

Parameters vs Arguments

// Parameters: Variables in function definition
function multiply(num1, num2) { // num1, num2 are parameters
return num1 * num2;
}

// Arguments: Actual values passed to function
let product = multiply(4, 5); // 4 and 5 are arguments
product: 20

Parameters are like placeholders, arguments are the actual values you provide when calling the function.

Return Statement

// Functions can return values
function isAdult(age) {
return age >= 18;
}
console.log(isAdult(20)); // true

// Without return, function returns undefined
function sayHello() {
console.log("Hello!");
}
let result = sayHello(); // Hello! (result is undefined)
true
Hello!
undefined

The return statement sends a value back to where the function was called.

Function Expressions

// Assigning a function to a variable
const square = function(number) {
return number * number;
};
console.log(square(4)); // 16

// Can be used immediately (IIFE)
(function() {
console.log("Immediately executed!");
})();
16
Immediately executed!

Function expressions aren't hoisted and are useful when passing functions as arguments.

Arrow Functions

// Compact syntax
const divide = (a, b) => a / b;
console.log(divide(10, 2)); // 5

// With multiple statements
const greetUser = (name) => {
const message = "Hello, " + name;
return message;
};

// Single parameter - parentheses optional
const double = num => num * 2;
5
Hello, Sarah

Arrow functions provide concise syntax and don't bind their own this value.

Function Scope

let globalVar = "I'm global";

function scopeTest() {
let localVar = "I'm local";
console.log(globalVar); // Accessible
console.log(localVar); // Accessible
}

scopeTest();
console.log(globalVar); // Accessible
console.log(localVar); // ❌ Error: localVar not defined
I'm global
I'm local
I'm global
ReferenceError

Variables declared inside a function are local to that function and not accessible outside.

Default Parameters

// Set default values for parameters
function createGreeting(name = "Guest") {
return "Welcome, " + name;
}
console.log(createGreeting("Alice")); // Welcome, Alice
console.log(createGreeting()); // Welcome, Guest
Welcome, Alice
Welcome, Guest

Default parameters provide fallback values when arguments are missing or undefined.

Common Function Mistakes

// 1. Missing parentheses when calling
function sayHi() { console.log("Hi"); }
sayHi; // ❌ Function not called
sayHi(); // ✅ Correct

// 2. Returning incorrectly
function add(a, b) {
a + b; // ❌ Missing return
}

// 3. Parameter vs argument mismatch
function multiply(a, b) { return a * b; }
multiply(5); // ❌ Returns NaN (5 * undefined)

// 4. Scope confusion
function test() {
var x = 10;
}
test();
console.log(x); // ❌ ReferenceError

Always test functions with different inputs to catch these common issues early.

Practical Example: Shopping Cart

// Function to calculate total
function calculateTotal(items, taxRate = 0.08) {
let subtotal = 0;
for (const item of items) {
subtotal += item.price * item.quantity;
}
const tax = subtotal * taxRate;
return subtotal + tax;
}

// Function to format currency
const formatCurrency = amount => `$${amount.toFixed(2)}`;

// Usage
const cartItems = [
{ name: "Shirt", price: 25.99, quantity: 2 },
{ name: "Mug", price: 9.99, quantity: 1 }
];

const total = calculateTotal(cartItems);
console.log("Total: " + formatCurrency(total));
Total: $68.82

Interactive Functions

// Greet button handler
document.getElementById("greetBtn").addEventListener("click", () => {
// Using all three function types
displayMessage(greetUser("Alex"));
});

// Calculate button handler
document.getElementById("calculateBtn").addEventListener("click", function() {
const area = calculateRectangleArea(10, 5);
displayMessage("Area: " + area + " units²");
});

// Function declarations (hoisted)
function greetUser(name) {
return "Hello, " + name + "!";
}

// Function expression
const calculateRectangleArea = function(width, height) {
return width * height;
};

// Arrow function
const displayMessage = (msg) => {
document.getElementById("output").textContent = msg;
};

Your Task: Function Implementation

Create JavaScript functions for all buttons:

  1. Add event listeners to all four buttons
  2. Implement functions:
    • Greet User:
      • Create greetUser() function that returns a personalized greeting
      • Use a default parameter for the name ("Guest")
    • Calculate Area:
      • Create calculateCircleArea() function (radius parameter)
      • Return area using formula: π * radius²
      • Use Math.PI for π
    • Convert Temperature:
      • Create arrow function celsiusToFahrenheit
      • Formula: (celsius * 9/5) + 32
      • Convert 25°C and display result
    • Reset Output:
      • Create function to clear the output div
  3. Create a displayResult() function that:
    • Takes a message and displays it in the output div
    • Is reused by all other functions
  4. Display results in this format:
    Hello, Sarah!
    Circle area: 78.54
    25°C is 77°F

Challenge: Add a temperature input field and convert user-provided value

Tip: Use toFixed(2) to format numbers

Section 1/12What are Functions?

What are Functions?

Functions allow you to package code into reusable units that can be executed multiple times with different inputs.

Creating and Using Functions

Learn how to create reusable blocks of code with functions - the building blocks of organized JavaScript programs.

What are Functions?

// Functions are reusable code blocks
function greet() {
console.log("Hello!");
}
// Call the function
greet(); // Hello!
greet(); // Hello! (reusable)
Hello!
Hello!

Functions allow you to package code into reusable units that can be executed multiple times with different inputs.

Preview