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 blocksfunction greet() {console.log("Hello!");}// Call the functiongreet(); // 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 structurefunction functionName(parameters) {// code to executereturn result; // optional}// Example: Add two numbersfunction add(a, b) {return a + b;}let sum = add(5, 3); // 8
sum: 8Declared functions are hoisted (can be called before declaration in the same scope).
Parameters vs Arguments
// Parameters: Variables in function definitionfunction multiply(num1, num2) { // num1, num2 are parametersreturn num1 * num2;}// Arguments: Actual values passed to functionlet product = multiply(4, 5); // 4 and 5 are arguments
product: 20Parameters are like placeholders, arguments are the actual values you provide when calling the function.
Return Statement
// Functions can return valuesfunction isAdult(age) {return age >= 18;}console.log(isAdult(20)); // true// Without return, function returns undefinedfunction sayHello() {console.log("Hello!");}let result = sayHello(); // Hello! (result is undefined)
true
Hello!
undefinedThe return statement sends a value back to where the function was called.
Function Expressions
// Assigning a function to a variableconst 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 syntaxconst divide = (a, b) => a / b;console.log(divide(10, 2)); // 5// With multiple statementsconst greetUser = (name) => {const message = "Hello, " + name;return message;};// Single parameter - parentheses optionalconst double = num => num * 2;
5
Hello, SarahArrow 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); // Accessibleconsole.log(localVar); // Accessible}scopeTest();console.log(globalVar); // Accessibleconsole.log(localVar); // ❌ Error: localVar not defined
I'm global
I'm local
I'm global
ReferenceErrorVariables declared inside a function are local to that function and not accessible outside.
Default Parameters
// Set default values for parametersfunction createGreeting(name = "Guest") {return "Welcome, " + name;}console.log(createGreeting("Alice")); // Welcome, Aliceconsole.log(createGreeting()); // Welcome, Guest
Welcome, Alice
Welcome, GuestDefault parameters provide fallback values when arguments are missing or undefined.
Common Function Mistakes
// 1. Missing parentheses when callingfunction sayHi() { console.log("Hi"); }sayHi; // ❌ Function not calledsayHi(); // ✅ Correct// 2. Returning incorrectlyfunction add(a, b) {a + b; // ❌ Missing return}// 3. Parameter vs argument mismatchfunction multiply(a, b) { return a * b; }multiply(5); // ❌ Returns NaN (5 * undefined)// 4. Scope confusionfunction 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 totalfunction 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 currencyconst formatCurrency = amount => `$${amount.toFixed(2)}`;// Usageconst 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.82Interactive Functions
// Greet button handlerdocument.getElementById("greetBtn").addEventListener("click", () => {// Using all three function typesdisplayMessage(greetUser("Alex"));});// Calculate button handlerdocument.getElementById("calculateBtn").addEventListener("click", function() {const area = calculateRectangleArea(10, 5);displayMessage("Area: " + area + " units²");});// Function declarations (hoisted)function greetUser(name) {return "Hello, " + name + "!";}// Function expressionconst calculateRectangleArea = function(width, height) {return width * height;};// Arrow functionconst displayMessage = (msg) => {document.getElementById("output").textContent = msg;};
Your Task: Function Implementation
Create JavaScript functions for all buttons:
- Add event listeners to all four buttons
- Implement functions:
- Greet User:
- Create
greetUser()function that returns a personalized greeting - Use a default parameter for the name ("Guest")
- Create
- Calculate Area:
- Create
calculateCircleArea()function (radius parameter) - Return area using formula: π * radius²
- Use
Math.PIfor π
- Create
- Convert Temperature:
- Create arrow function
celsiusToFahrenheit - Formula: (celsius * 9/5) + 32
- Convert 25°C and display result
- Create arrow function
- Reset Output:
- Create function to clear the output div
- Greet User:
- Create a
displayResult()function that:- Takes a message and displays it in the output div
- Is reused by all other functions
- 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
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 blocksfunction greet() {console.log("Hello!");}// Call the functiongreet(); // 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 structurefunction functionName(parameters) {// code to executereturn result; // optional}// Example: Add two numbersfunction add(a, b) {return a + b;}let sum = add(5, 3); // 8
sum: 8Declared functions are hoisted (can be called before declaration in the same scope).
Parameters vs Arguments
// Parameters: Variables in function definitionfunction multiply(num1, num2) { // num1, num2 are parametersreturn num1 * num2;}// Arguments: Actual values passed to functionlet product = multiply(4, 5); // 4 and 5 are arguments
product: 20Parameters are like placeholders, arguments are the actual values you provide when calling the function.
Return Statement
// Functions can return valuesfunction isAdult(age) {return age >= 18;}console.log(isAdult(20)); // true// Without return, function returns undefinedfunction sayHello() {console.log("Hello!");}let result = sayHello(); // Hello! (result is undefined)
true
Hello!
undefinedThe return statement sends a value back to where the function was called.
Function Expressions
// Assigning a function to a variableconst 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 syntaxconst divide = (a, b) => a / b;console.log(divide(10, 2)); // 5// With multiple statementsconst greetUser = (name) => {const message = "Hello, " + name;return message;};// Single parameter - parentheses optionalconst double = num => num * 2;
5
Hello, SarahArrow 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); // Accessibleconsole.log(localVar); // Accessible}scopeTest();console.log(globalVar); // Accessibleconsole.log(localVar); // ❌ Error: localVar not defined
I'm global
I'm local
I'm global
ReferenceErrorVariables declared inside a function are local to that function and not accessible outside.
Default Parameters
// Set default values for parametersfunction createGreeting(name = "Guest") {return "Welcome, " + name;}console.log(createGreeting("Alice")); // Welcome, Aliceconsole.log(createGreeting()); // Welcome, Guest
Welcome, Alice
Welcome, GuestDefault parameters provide fallback values when arguments are missing or undefined.
Common Function Mistakes
// 1. Missing parentheses when callingfunction sayHi() { console.log("Hi"); }sayHi; // ❌ Function not calledsayHi(); // ✅ Correct// 2. Returning incorrectlyfunction add(a, b) {a + b; // ❌ Missing return}// 3. Parameter vs argument mismatchfunction multiply(a, b) { return a * b; }multiply(5); // ❌ Returns NaN (5 * undefined)// 4. Scope confusionfunction 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 totalfunction 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 currencyconst formatCurrency = amount => `$${amount.toFixed(2)}`;// Usageconst 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.82Interactive Functions
// Greet button handlerdocument.getElementById("greetBtn").addEventListener("click", () => {// Using all three function typesdisplayMessage(greetUser("Alex"));});// Calculate button handlerdocument.getElementById("calculateBtn").addEventListener("click", function() {const area = calculateRectangleArea(10, 5);displayMessage("Area: " + area + " units²");});// Function declarations (hoisted)function greetUser(name) {return "Hello, " + name + "!";}// Function expressionconst calculateRectangleArea = function(width, height) {return width * height;};// Arrow functionconst displayMessage = (msg) => {document.getElementById("output").textContent = msg;};
Your Task: Function Implementation
Create JavaScript functions for all buttons:
- Add event listeners to all four buttons
- Implement functions:
- Greet User:
- Create
greetUser()function that returns a personalized greeting - Use a default parameter for the name ("Guest")
- Create
- Calculate Area:
- Create
calculateCircleArea()function (radius parameter) - Return area using formula: π * radius²
- Use
Math.PIfor π
- Create
- Convert Temperature:
- Create arrow function
celsiusToFahrenheit - Formula: (celsius * 9/5) + 32
- Convert 25°C and display result
- Create arrow function
- Reset Output:
- Create function to clear the output div
- Greet User:
- Create a
displayResult()function that:- Takes a message and displays it in the output div
- Is reused by all other functions
- 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