Learn Programming Fundamentals
1 Programming Fundamentals
2 Variables Data Types
3 Conditional Structures
4 Strings
5 Arrays
6 Objects
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.
Function syntax may vary, but typically follows a structure like this:
function functionName(parameters) { // Function body }
functionName()
.A function without parameters looks like this:
function printMessage() { console.log("Hi there..."); }
It prints Hi there...
.
A function with parameters looks like this:
function printMessage(message) { console.log(message); } printMessage("Welcome home!");
This function accepts and prints a message.
Functions can return values for decision making. For example:
function square(number) { return number * number; } let s = square(10); console.log(s); // Outputs 100
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);
checkEvenOrOdd
that determines if a number is even or odd and prints a message accordingly.