Define and Call Functions in JavaScript

CSSCSSBeginner
Practice Now

Introduction

In this lab, students will explore the fundamental concepts of defining and calling functions in JavaScript. The lab provides a comprehensive introduction to function basics, covering essential skills such as creating simple functions, working with parameters, and understanding function return values. Participants will learn how to structure functions, execute them, and use console output to demonstrate their functionality.

Through a series of hands-on exercises, learners will practice creating functions without return values, implementing functions with parameters, and exploring different ways of calling and utilizing functions. By the end of the lab, students will have gained practical experience in writing reusable code blocks, understanding function syntax, and applying function concepts in JavaScript programming.

Understand Function Basics

In this step, you'll learn the fundamental concepts of functions in JavaScript. Functions are reusable blocks of code that perform a specific task and help organize your programming logic.

A function is defined using the function keyword, followed by a name, parentheses (), and a block of code enclosed in curly braces {}. Here's a basic function structure:

function functionName() {
  // Code to be executed
}

Let's create a simple example to demonstrate function basics. Open the WebIDE and create a new file called functions.js in the ~/project directory.

// Defining a simple function
function greet() {
  console.log("Hello, JavaScript Functions!");
}

// Calling the function
greet();

When you run this code, you'll see the following output:

Example output:
Hello, JavaScript Functions!

Key points to understand about functions:

  • Functions are defined using the function keyword
  • They can be called multiple times
  • They help reduce code repetition
  • Functions can be simple or complex

Try experimenting by calling the greet() function multiple times to see how it works.

Create a Simple Function without Return Value

In this step, you'll learn how to create functions that perform actions without returning a value. These functions are often used to execute a specific task or display information.

Open the WebIDE and create a new file called simple_functions.js in the ~/project directory. We'll create a few examples of functions without return values.

// Function to display a welcome message
function displayWelcome() {
  console.log("Welcome to JavaScript Functions!");
}

// Function to print multiplication table
function printMultiplicationTable(number) {
  console.log(`Multiplication Table for ${number}:`);
  for (let i = 1; i <= 10; i++) {
    console.log(`${number} x ${i} = ${number * i}`);
  }
}

// Calling the functions
displayWelcome();
printMultiplicationTable(5);

When you run this code, you'll see the following output:

Example output:
Welcome to JavaScript Functions!
Multiplication Table for 5:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

Key points about functions without return values:

  • They perform actions like printing or modifying data
  • They use console.log() to display information
  • They can take parameters to make them more flexible
  • They don't use the return keyword to send back a value

Try experimenting by creating your own functions or modifying the existing ones to display different messages or perform various tasks.

Create a Function with Parameters and Return Value

In this step, you'll learn how to create functions that accept parameters and return values. These functions are more versatile and can perform calculations or transformations.

Open the WebIDE and create a new file called parameter_functions.js in the ~/project directory. We'll create functions that demonstrate parameters and return values.

// Function to calculate the area of a rectangle
function calculateRectangleArea(length, width) {
  return length * width;
}

// Function to check if a number is even
function isEven(number) {
  return number % 2 === 0;
}

// Function to greet a person
function createGreeting(name) {
  return `Hello, ${name}! Welcome to JavaScript.`;
}

// Demonstrating function calls and return values
let rectangleArea = calculateRectangleArea(5, 3);
console.log(`Rectangle Area: ${rectangleArea} square units`);

let checkNumber = 6;
console.log(`Is ${checkNumber} even? ${isEven(checkNumber)}`);

let personalGreeting = createGreeting("Alice");
console.log(personalGreeting);

When you run this code, you'll see the following output:

Example output:
Rectangle Area: 15 square units
Is 6 even? true
Hello, Alice! Welcome to JavaScript.

Key points about functions with parameters and return values:

  • Parameters allow functions to accept input
  • The return keyword sends a value back from the function
  • Functions can perform calculations and return the result
  • Return values can be used in further computations or logging

Try experimenting by creating your own functions with different parameters and return types.

Practice Function Implementation

In this step, you'll practice implementing functions by creating a small program that demonstrates various function techniques. We'll build a simple calculator application to reinforce your understanding of function implementation.

Open the WebIDE and create a new file called calculator.js in the ~/project directory. We'll implement several mathematical functions:

// Function to add two numbers
function add(a, b) {
  return a + b;
}

// Function to subtract two numbers
function subtract(a, b) {
  return a - b;
}

// Function to multiply two numbers
function multiply(a, b) {
  return a * b;
}

// Function to divide two numbers with error handling
function divide(a, b) {
  if (b === 0) {
    return "Error: Division by zero";
  }
  return a / b;
}

// Function to calculate the square of a number
function square(x) {
  return x * x;
}

// Demonstrate calculator functions
console.log("Addition: 5 + 3 =", add(5, 3));
console.log("Subtraction: 10 - 4 =", subtract(10, 4));
console.log("Multiplication: 6 * 7 =", multiply(6, 7));
console.log("Division: 15 / 3 =", divide(15, 3));
console.log("Square of 4 =", square(4));
console.log("Division by zero:", divide(10, 0));

When you run this code, you'll see the following output:

Example output:
Addition: 5 + 3 = 8
Subtraction: 10 - 4 = 6
Multiplication: 6 * 7 = 42
Division: 15 / 3 = 5
Square of 4 = 16
Division by zero: Error: Division by zero

Key points about function implementation:

  • Create functions with clear, single responsibilities
  • Use parameters to make functions flexible
  • Implement error handling when necessary
  • Test your functions with different inputs
  • Use meaningful function and variable names

Try experimenting by adding more mathematical functions or modifying the existing ones.

Explore Function Calling and Output

In this step, you'll learn different ways of calling functions and exploring various output techniques in JavaScript. We'll create a comprehensive example that demonstrates multiple function calling strategies and output methods.

Open the WebIDE and create a new file called function_output.js in the ~/project directory:

// Function to generate a personalized greeting
function createGreeting(name, time) {
  return `Good ${time}, ${name}!`;
}

// Function to calculate total price with tax
function calculateTotalPrice(price, taxRate = 0.1) {
  return price + price * taxRate;
}

// Function with multiple parameters and default values
function displayUserInfo(name, age = "Not specified", city = "Unknown") {
  console.log(`Name: ${name}`);
  console.log(`Age: ${age}`);
  console.log(`City: ${city}`);
}

// Demonstrating different function calling techniques
let morningGreeting = createGreeting("Alice", "morning");
console.log(morningGreeting);

let eveningGreeting = createGreeting("Bob", "evening");
console.log(eveningGreeting);

let productPrice = 100;
let totalPrice = calculateTotalPrice(productPrice);
console.log(`Product Price: $${productPrice}`);
console.log(`Total Price (with tax): $${totalPrice}`);

// Calling function with different parameter combinations
displayUserInfo("Charlie");
displayUserInfo("David", 30);
displayUserInfo("Eve", 25, "New York");

When you run this code, you'll see the following output:

Example output:
Good morning, Alice!
Good evening, Bob!
Product Price: $100
Total Price (with tax): $110
Name: Charlie
Age: Not specified
City: Unknown
Name: David
Age: 30
City: Unknown
Name: Eve
Age: 25
City: New York

Key points about function calling and output:

  • Functions can be called with different numbers of arguments
  • Default parameter values provide flexibility
  • Use template literals for formatted output
  • console.log() is useful for displaying function results
  • You can store function return values in variables

Try experimenting by creating more complex function calls and output scenarios.

Summary

In this lab, participants explored the fundamental concepts of JavaScript functions, learning how to define, create, and call functions with different characteristics. The lab guided learners through understanding function basics, including function syntax, declaration, and execution, with a focus on creating reusable code blocks that can perform specific tasks.

The learning journey covered creating simple functions without return values, implementing functions with parameters, and demonstrating how functions can be used to organize programming logic, print output, and perform calculations. By practicing function implementation and exploring various function calling techniques, participants gained practical skills in writing modular and efficient JavaScript code.