Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

8 Functions

1 Functions

Imagine you are provided with 10 random numbers and asked to write a program to check if each number is even or odd, and print the result accordingly. An even number is divisible by 2 without a remainder, while an odd number has a remainder.

Here's how we can do it:

// For number 1
let number_1 = 10;
if (number_1 % 2 === 0) {
    console.log('Number is even!');
} else {
    console.log('Number is odd!');
}

// For number 2
let number_2 = 9;
if (number_2 % 2 === 0) {
    console.log('Number is even!');
} else {
    console.log('Number is odd!');
}

// Repeat for numbers 3 to 10...

Notice the code becomes lengthy and repetitive. We are writing the same if-else statement multiple times with only the number changing. This is where functions come into play.

Functions in programming are named blocks of code that perform specific tasks. They encapsulate reusable code, improve organization, and promote reusability, readability, and maintainability.

Syntax

Function syntax may vary, but typically follows a structure like this:

function functionName(parameters) {
    // Function body
}
  • Functions have a distinct name used to invoke them.
  • They may or may not accept parameters (variables or values passed to the function).
  • Functions are designed for specific tasks.
  • Invoke a function using functionName().

Function Without Parameters

A function without parameters looks like this:

function printMessage() {
    console.log("Hi there...");
}

It prints Hi there....

Function With Parameter

A function with parameters looks like this:

function printMessage(message) {
    console.log(message);
}

printMessage("Welcome home!");

This function accepts and prints a message.

Function With Return Value

Functions can return values for decision making. For example:

function square(number) {
    return number * number;
}

let s = square(10);
console.log(s); // Outputs 100

Example

Let's rewrite the previous example using a function:

// Function to check if a number is even or odd
function checkEvenOrOdd(number) {
    if (number % 2 === 0) {
        console.log(number + ' is even!');
    } else {
        console.log(number + ' is odd!');
    }
}

// Test the function with different numbers
checkEvenOrOdd(10);
checkEvenOrOdd(9);
checkEvenOrOdd(40);
checkEvenOrOdd(50);
checkEvenOrOdd(30);
checkEvenOrOdd(39);
checkEvenOrOdd(29);
checkEvenOrOdd(13);
checkEvenOrOdd(16);
checkEvenOrOdd(12);
checkEvenOrOdd(50);

Understanding the Code:

  • We have a reusable function checkEvenOrOdd that determines if a number is even or odd and prints a message accordingly.
  • The function is called multiple times with different numbers, demonstrating its reusability.