A GUIDE TO JAVASCRIPT LOOPS AND FUNCTIONS.

Introduction to Conditionals, Loops, and Functions.

Nicholas Okeke
9 min readJul 3, 2023

Welcome to another essential part of JavaScript. In this article, we will discuss three out of many important aspect of Javascript which are Conditionals, Loops, and Functions.

CONDITIONALS

These are also called Conditional Statements and I will be using them interchangeably.

Most facts about life is that life it’s all about making decisions or choices. Your choices can make or mar you.

What Conditionals Do?

Just like in the real world, conditional statements are used in JavaScript to make decisions based on specific conditions. It helps to represent the decision making in form of a code.

Comparison Operators.

Before we delve into the types of conditionals, we need to first discuss the types of operators that are used in conditional statements to make decisions. These operators always return a Boolean after comparison.

They are:

  • ==/===: This is an operator that is used to check if two values are equal to each other. The former (==) is a loose form of comparison which compares based on value only even if it is of different data type while the latter is a strict form of comparison which compares both the value and data type.
  • </<= and >/>=: this is an operator that is used to check if two Number data types is less, less than or equal to, greater than and greater than or equal to each other. It does not have a stricter form.
  • !== or !===: this is called a not comparison operator. It is used to check if two data types are not equal to each other.

Logical Operators.

These are divided into three:

1. The AND Operator(&&): this operator implies that the two conditions must be met for the whole condition to evaluate to true. It is denoted by an ampasand as written in the parenthesis.

E.g. num1>5 && num1<10 //This implies that num1 must be within the range 6,7,8,9.

2. The OR Operator(||): this operator returns true if one more of the conditions is/are met. It is denoted by the pipe symbol in the parenthesis.

E.g. num1=5 || num1=10 // this will return true if num1 is either 5 or 10.

3. The NOT Operator(!): This operator is used to negate a condition. It turns a condition to its opposite — it turns true to false and false to true.

E.g. let isGood = !true //this evaluates isGood to false.

Types of Conditional Statement.

Here are some commonly used conditional statements that allow you control the flow of your code based on different conditions:

1. The if Statement: this statement is a basic conditional statement that executes a block of code if a certain condition is true.

Syntax:

If (condition){

//code to be executed if the condition is true

}

Example:

Const num = 3;
If(num ===3){
console.log("Yes we did it!")
} //The code prints "Yes we did it" because the num variable is equal 3.

2. The if-Else Statement: this statement provides an alternative execution path when the condition is false. If the condition is true, the code inside the “if” block is executed. Otherwise, the code inside the “else” block is executed.

Syntax:

if (condition) {

// Code to be executed if the condition is true

} else {

// Code to be executed if the condition is false

}

3. The else-if Statement: The else-if statement allows you to check multiple conditions sequentially and execute the corresponding code block of the first condition that evaluates to true. The else-if block is just like the if block that takes on a condition and executes if the if block does. There can be as many else-if block as possible depending on the number of conditions.

Syntax:

if (condition1) {

// Code to be executed if condition1 is true

} else if (condition2) {

// Code to be executed if condition2 is true

} else {

// Code to be executed if none of the conditions are true

}

Example:

let num = 5;
If(num>5){
console.log("Number is greater than 5)
}else if(num<5){
console.log("Number is less than 5)
}else{
console.log("Number is equals 5)
} //This prints "Number is equals 5" because number is neither greater than or less than 5.

Note that if the is an else-if block, the last block must always be an else block.

4. The switch statement: this conditional statement provides a way to select one of many code blocks to be executed based on the value of an expression. The switch statement starts with a switch keyword, followed by a parenthesis, and then a code block.

Inside the code block, there will be different cases, with case values. Each code block runs if the expression in the switch parenthesis matches with the case value. The break statement terminates the execution of the switch statement so that the execution does not go down after the condition is satisfied. A default block, which is always the last block, runs, if all the cases do not satisfy the condition.

Syntax:

switch (expression) {

case value1:

// Code to be executed if expression matches value1

break;

case value2:

// Code to be executed if expression matches value2

break;

default:

// Code to be executed if expression doesn’t match any case

}

5. Ternary Operator: this operator allows us to write conditions. Ternary means three parts which are:

  • A conditional statement.
  • A question mark that contains the block of code if the condition evaluates to true.
  • A colon that contains the block of code if the condition is false.

Syntax:

condition? Evaluates this code if true: evaluates this code if false.

E.g.

let num =5;
num<5? Console.log(true): console.log(false)

LOOPS.

What Loops Do.

Loops in JavaScript are used to carry out a repetitive tasks. They are used to automate a repetitive tasks.

Examples of cases where loops are used is accessing each elements of a list of items such as arrays, objects, strings, maps, and sets.

Types of Loops (With Syntax).

There are 5 types of loops in JavaScript, namely:

  1. for loop.
  2. while loop.
  3. do…while loop.
  4. for of loop.
  5. for in loop

1. for loop: this is used when you know the number of iterations in advance. It consists of three parts: an initialization, a condition, and an increment/decrement.

Syntax:

for(initialisation; condition; increment/decrement){

//code goes here

}

Examples:

Increment

for(let i=0; i<5=; i++){
console.log(i)
} //This prints out 0,1,2,3,4,5.

Decrement

for(let i=0; i<5=; i - ){
console.log(i)
} //This prints out 5,4,3,2,1,0.

2. while loop: this is used when you want to repeat a block of code as long as a condition is true. The loop continues until the condition evaluates to false.

Syntax:

while (condition) {

// Code to be executed as long as the condition is true

}

Examples:

let count = 1;
while (count <= 5) {
console.log(count); // Output: 1, 2, 3, 4, 5
count++;
}

3. do…while loop: this is similar to the while loop, but the condition is checked after the code block is executed. It ensures that the code is executed at least once, even if the condition is initially false.

Syntax:

do {

// Code to be executed at least once

} while (condition);

Examples:

let count = 1;
do {
console.log(count); // Output: 1
count++;
} while (count <= 5);

4. for…of loop: this is used to iterate over iterable objects such as arrays, strings, sets, and maps. It simplifies the looping process by directly accessing the elements without dealing with indices.

Syntax:

for (const element of iterable) {

// Code to be executed for each element

}

Examples:

const colors = ['red', 'green', 'blue'];
for (const color of colors) {
console.log(color); // Output: 'red', 'green', 'blue'
}

5. for…in loop: this is used to iterate over the properties of an object. It retrieves the keys of an object, allowing you to perform operations on each property.

Syntax:

for (const key in object) {

// Code to be executed for each property

}

Examples:

const person = {
name: 'John',
age: 30,
city: 'New York'
};
for (const key in person) {
console.log(key + ': ' + person[key]);
// Output: 'name: John', 'age: 30', 'city: New York'
}

Some Loops to Avoid.

While all the loops can work well, it is advisable to avoid the while loop as it can easily lead you code into an infinite loop and crash your code if its stopping condition is not properly set.

Other types of loops.

There are other functions that can be used to loop through an array. Example of this function are forEach(); map(), filter(), etc.

FUNCTIONS.

Consider a bakery where various baked goods are prepared. The bakery has a recipe book containing instructions for baking different types of cakes. Each recipe is like a function. It defines a set of steps to follow in order to bake a specific cake.

What Functions Do.

A function, in JavaScript, is a reusable block of code that performs a specific task or calculates a value.

Functions allow you to house a set of instructions into a single unit which can be invoked and executed multiple times throughout your code.

This helps organise your code, making it more readable, maintainable, and efficient.

Declaring and Calling a Function.

To declare a function means to create a function using JavaScript syntax for that function. A function can be declared with or without a parameter. The way to declare a function depends on the type of function.

To call or invoke a function means to get the value of the function. A function is usually called with an argument. If a function is not called or invoked, the function is as good as useless because there will be no task performed by the function.

Parameters and Arguments.

A parameter in a function is a variable defined in a function declaration while an argument is a value assigned to a function during the function call. The total number of a function’s parameter must be equal to the function’s argument.

The return Statement.

The return statement ends the line of code inside the function. No code will be executed beyond the return statement. The return statement is used to store the data of the function that you want to be displayed at the function call. If you do not specify the return statement, the function will return a value of undefined.

Types of Functions.

The two major types of functions are

  • Normal function
  • Arrow function.
  1. Normal Function: this function is the primitive method for declaring functions. To declare this type of function we use a function keyword followed by the function name, a pair of parenthesis and the a pair of curly braces.

Syntax:

function nameOfFunction(){

//Your code goes in here

}

nameOfFunction() //Function call.

Example:

function printNumber(num){
return num
}
console.log(printNumber(5)) //This prints out 5

The normal function can have different variations:

i. Anonymous Function: this is simply a normal function without a name. It is usually used immediately it is declared. It is passed as an argument in higher order functions.

Example:

const arr = [1,2,3]
arr.forEach(function (elem){
console.log(elem)
}) //This prints out 1,2,3. The function inside the forEach() is an anonymous function

ii. Function Expressions: This is a normal function that is declared like a variable. It is declared with a variable name. Apart from the variable name, the function may/may not be given a specific name.

Example:

const multiply = functon(a,b){
return a*b;
};

console.log(multiply(2,3)); //Outputs 6.

const addNumbers = function addTwoNumbers(a,b){
return a+b;
}

console.log(addNumbers(2,4)); //outputs 6. Notice how the functions are called.

iii. Immediately Invoked Function Expression(IIFE): this is a self-invoked function that is executed as soon as it is defined. It is enclosed in parentheses to make sure it is an expression and followed by an additional pair of parentheses “()”. They are often used to create a private scope and avoid polluting the global namespace.

(function(){
//Code to be executed immediately
})();

2. Arrow Function: This is a recent development in JavaScript and provides a concise syntax for writing functions. It is declared like a function expression but the modifications are removing the function keyword and add an arrow(=>) after the pair of parenthesis. If the code to be written within the function is a one-line code, there will be no need for a pair of curly braces and a return keyword as the arrow function makes use of its implicit return.

Example:

const divide = (a,b) => a/b; //Implicit return
console.log(divide(6,3)) //ouputs 2

const divide = (a,b) =>{
let c = a/b;
return c;
}
console.log(divide(6,2)) //Outputs 3.

Callbacks

A callback function is simply a function that is passed as a parameter to other functions.

Example:

function callback(n){
return n**2;
};

function higherOrder(functionName,n){
return function(n) * n;
}

console.log(higherOrder(callback,2)) //This outputs 8;

Relationship between Conditionals, Loops, and Functions.

Leverage the relationship between conditionals, loops and functions is one of the powerful tool that can be used in JavaScript. A function can contain a loop and a conditional statement. Then a loop can contain a conditional statement and vice versa.

Using the information above, I hope JavaSript becomes a tad easier for you.

Happy Coding!!!

--

--