Agunechemba Ekene

If you’re just getting started with JavaScript, understanding functions is one of the best moves you can make. In this short, practical lesson, we’ll look at how functions work using numbers—no strings attached. Ready? Let’s go!


🚀 What’s a Function in JavaScript?

A function is a block of code that does something when you call it. Think of it like a mini-machine: you give it input, it gives you output.

Here’s a simple example:

// Define a function
function square(num) {
  return num * num;
}

// Call the function
let result = square(5);

console.log(result); // Output: 25

This function takes one number, squares it, and prints the result. Easy!


✌️ Using Two Numbers? No Problem

Let’s try a function that works with two numbers instead of one:

// Define a function
function add(a, b) {
  return a + b;
}

// Call the function
let result = add(7, 3);

console.log(result); // Output: 10

Breakdown:

  • function add(a, b) creates a function with two inputs.
  • return a + b adds them.
  • add(7, 3) returns 10.
  • console.log(result) prints 10.

Simple, clear, and super useful.


âś… Quick Review:

Test your understanding with these mini quiz questions.


1. What does the add function return when called with add(4, 6)? A. 10 B. 46 C. “4 + 6” D. undefined


2. What is the purpose of the return statement in the add function? A. To log the result B. To define a new function C. To send back the sum of a and b D. To create variables


3. What type of values are passed to the add function in add(7, 3)? A. Strings B. Numbers C. Booleans D. Arrays


4. What does console.log(result); do? A. Stores a value B. Prints result to the console C. Adds two numbers D. Declares a function


5. What will be the output of this line: console.log(add(2, 5));? A. 25 B. 7 C. “2 + 5” D. Nothing


🎯 Final Thought

Functions are the heart of JavaScript. Learn them well and everything else becomes easier. Next time you need to reuse logic, you’ll know exactly what to do.


<
Previous Post
đź’Ą JavaScript Basics: Understanding Exceptions with try...catch
>
Next Post
JS REGEX 01: The Regex Rangers - Quest for the Perfect Match