JavaScript Fundamentals: Conditionals, Loops and Functions

JavaScript Fundamentals: Conditionals, Loops and Functions

Exploring the building blocks of one of Earth's most popular programming languages

Introduction

JavaScript is a dynamic programming language that is widely used in web applications and web development, but it also has a lot of other use cases such as in game development, mobile applications, etc. The language allows one to implement dynamic features on web pages which cannot be done by making use of only HTML and CSS. In this article, we will be discussing some of the fundamental things every developer must know to use JavaScript effectively. Jim Rohn, the famous American motivational speaker is quoted as once saying:

"Success is neither magical nor mysterious. Success is the natural consequence of consistently applying the basic fundamentals."

With that in mind, let's dive in

Conditional Statements in JavaScript

In JavaScript, Conditional statements are used to perform actions based on certain conditions. We will be looking at four basic types of conditional statements in JavaScript, namely the if statement, the if/else statement, the switch statement, and the ternary operator.

If statement

The if statement performs an action based on whether a certain condition is met. Its syntax is as follows:

if (condition) {
    // executes code inside the block
}

// Example
let isRaining = true;

if (isRaining) {
    console.log("It is raining outside.");
} /* since the variable isRaining evaluates to true, the block of code
 inside the if statement will execute and log "It is raining outside."
 to the console. */

If/else statement

In the If/else statement, the else statement is added to the if statement to execute another block of code if the if block executes to false. The if/else statement syntax is shown below:

if (condition) {
    // executes the code in this block if the condition is met
} else {
    /* executes the code in this block if the condition is not 
    met in the if block */
}

// Example extending the If statement example
let isRaining = false;

if (isRaining) {
    console.log("It is raining outside");
} else {
    console.log("You can go to the park. It's not raining outside.");
} /* since the variable isRaining evaluates to false, the block of code 
inside the if statement will not execute, rather, the block of code inside
the else statement will run and log "You can go to the park. It's not
raining outside." to the console */

Switch statement

The switch statement evaluates an expression once and compares the value of the expression with the value of each case. When a match is found, the matching block of code is run, and the switch statement breaks. But, when no match is found, the default code block which specifies the code to be run when none of the other case statements match the value of the expression is run. The syntax of the switch statement is shown below:

switch (expression) {
    case a:
        // code to be executed if the expression evaluates to case a
        break;
    case b:
        // code to be executed if the expression evaluates to case b
        break;
    case c:
        // code to be executed if the expression evaluates to case c
        break;
    default:
        /* default code to be executed if the expression evaluates to
        none of the cases */
}

// Example
let country = "Nigeria";

switch (country) {
    case "United States of America": 
        console.log("United States of America");
        break;
    case "France":
        console.log("France");
        break;
    case "Germany":
        console.log("Germany");
        break;    
    case "Canada":
        console.log("Canada");
        break;
    case "Nigeria":
        console.log("Nigeria");
        break;
    default:
        console.log("Unknown country");
} /* The expression 'country' evaluates to the case "Nigeria" and is
printed to the console, which means that the value of the case "Nigeria",
and the value of the expression match. If we attempted to input another 
African country, say Rwanda for example, as the value of the expression, 
'country', the switch statement would log "Unknown country" to the console,
as it would run the default block of code seeing as none of the cases
match its value. */

Ternary Operator

The ternary operator can be best described as a way of writing a condition expression in one line. It's basically a shorter way of writing if/else statements. To use a ternary operator, you first write the condition, followed by a question mark (?), and then the value that should be returned if the condition evaluates to true, this will then be followed by a colon (:), and finally the value that should be returned if the condition evaluates to false. Let's illustrate this below:

condition ? valueIfConditionIsTrue : valueIfConditionIsFalse

/* Let us refactor or modify the example used in the if/else
statement */

// The original If/else statement
let isRaining = false;

if (isRaining) {
    console.log("It is raining outside");
} else {
    console.log("You can go to the park. It's not raining outside.");
} // remember this logs the else statement's code block to the console

// Using the ternary operator to write the same code
let isRainingTwo = false ? console.log("It is raining outside")
: console.log("You can go to the park. It's not raining outside."); 
/* this line of code will give the same answer as the if/else statement */

Loops in JavaScript

In JavaScript, loops help to execute a block of code repeatedly based on a certain condition. We would discuss the three basic loops in JavaScript, which are the for loop, the while loop, and the do...while loop.

For loop

The for loop has three expressions namely an initialization, which is where the variable is assigned a value, a condition, and an update or afterthought. The for loop continues to execute the block of code as long as the condition remains true, till the provided condition evaluates to false. The update expression changes the value of the variable declared in the loop after each iteration. The syntax of the for loop is described below:

for (initialization; condition; afterthought) {
    // code block
}

// Example printing all numbers between 50 and 0, including 50 and 0
for (let i = 50; i >= 0; i--) {
    console.log(i);
} /* Here, we initialize the variable, i with a value of 50, then provide the
condition that the for loop is to run till it becomes false, we then provide
an update expression that the for loop uses to decrease the value of i after
each iteration till the condition is met. The for loop above would output the 
numbers 50, 49, 48 ...0. */

While loop

The while loop executes a block of code as long as the provided condition evaluates to true. As soon as the condition evaluates to false, the while loop will stop the execution of the block of code. The while loop syntax is as follows:

while (condition) {
    // code block
}

// Refactoring or modifying the example used in the for loop

// The original for loop
for (let i = 50; i >= 0; i--) {
    console.log(i);
}

// Using the while loop to write the same code
let x = 50;
while (x >= 0) {
    console.log(x);
    x--;
} /* The while loop gives the same result as the for loop by printing
all numbers between 50 and 0, including 50 and 0 */

Do...while loop

The do...while executes a block of code repeatedly until the specified condition evaluates to false. The unique thing about this loop is that it checks the condition after each iteration or execution. As a result, the loop will always run at least once. The syntax of the do...while loop is as follows:

do {
    // code block
} while (condition);

// Refactoring or modifying the example used in the for loop

// The original for loop
for (let i = 50; i >= 0; i--) {
    console.log(i);
}

// Using the do...while loop to write the same code
let y = 50;
do {
    console.log(y);
    y--;
} 
while (y >= 0); /* The do...while loop gives the same result as the for loop
by printing all numbers between 50 and 0, including 50 and 0 */

Functions in JavaScript

A JavaScript function is a block of code that carries out a specific task. Functions allow us to put statements that perform similar tasks together. JavaScript functions could either be built-in or user-defined. Built-in JavaScript functions are predefined functions that are embedded either into JavaScript or as part of the runtime environment while user-defined functions are functions written by the user to perform a specific task.

Two ways of defining functions

Functions can either be defined using a function declaration or a function expression:

Function declaration

This is the normal way of declaring functions in JavaScript. Using function declaration:

  • We begin by writing the function keyword.

  • We then write the name of the function, which should clearly define what the function does.

  • This is then followed by parenthesis containing parameter(s), which are variables used to pass information to a function.

  • Then lastly, we put two curly braces after the parenthesis. The code block is written in between the curly braces.

The function declaration syntax is outlined below:

function name (parameter) {
    // code block
}

/* Example: A function that accepts a name as a parameter */

function myName (name) {
    console.log(`My name is ${name}.`);
}
/* In order to input a name, we make use of what is called a function call
in which we pass a value for the parameter, this value is known as an 
argument, It is illustrated below*/

myName('Samuel'); /* when the function declaration is called it accepts a 
value of Samuel for the name parameter, and when the function is run, it 
logs "My name is Samuel" to the console. */

Functions declared using function declarations are known as named functions and JavaScript will allow a function declaration to be called before it is declared, this feature of JavaScript is called hoisting, and it is generally seen as bad development practice.

Function expression

A function expression can be seen as a reference to a function. Basically, a function expression is a variable whose value is a function. Using function expression:

  • We begin by declaring a variable with a variable name.

  • We then write the assignment operator, =, and on the other side, we assign a function to it.

  • On the other side, we write the function keyword followed by parenthesis, and within the parenthesis, we include a parameter(s).

  • This is then followed by two curly braces after the parenthesis. The code block is written in between the curly braces.

The function expression syntax is outlined below:

const name = function (parameter) {
    // code block
}

//Comparing function declaration and function expression

// Function declaration
function myName (name) {
    console.log(`My name is ${name}.`);
} 
myName('Samuel');

// Function expression
const myAge = function (age) {
    console.log(`I am ${age} years old.`);
}
myAge(18); /* function expressions are called in the same way as function
declarations. And when the function expression is called it accepts a value 
of 18 for the age parameter. When the function is run, it logs "I am 18
years old" to the console. */

Functions declared using function expressions are known as anonymous functions and JavaScript will not allow a function expression to be called before it is declared, it can only be called after declaration.

Arrow functions

Arrow functions are a concise way of writing functions. Using arrow functions:

  • We begin by declaring a variable with a variable name.

  • We then write the assignment operator, =, and on the other side, we put our parenthesis, in which we include our parameter(s).

  • This is then followed by the arrow, =>, and then the curly braces in which the code block is written.

The syntax of arrow functions is seen as follows:

const name = (parameter) => {
    // code block
}

//Comparing function declaration and function expression with an arrow function

// Function declaration
function myName (name) {
    console.log(`My name is ${name}.`);
} 
myName('Samuel');

// Function expression
const myAge = function (age) {
    console.log(`I am ${age} years old.`);
} 
myAge(18);

//Arrow function
// One would normally write an arrow function like this:
const myHobby = (hobby) => {
    console.log(`I love ${hobby}`);
} 
myHobby('reading');

/* But when there is only one parameter and one line of code, JavaScript
allows for the arrow function to be rewritten as: */

const myHobby = hobby => console.log(`I love ${hobby}`); /* the parenthesis 
around the parameter and the curly braces around the single code line have 
both been ignored */
myHobby('reading');

Function scopes

In JavaScript, we have two types of scopes namely the block scope and the global scope associated with JavaScript variables and functions. When a variable is declared within the code block of a function, that variable is said to be block-scoped, and as such, the variable will only be accessible inside that function and will not be accessible anywhere else in the code. But when a variable is declared outside a function, it is said to be globally scoped and can be accessed anywhere within the program. Let's look at the syntax of globally and locally scoped variables:

// Locally scoped variable
let boy = "Adams";
const male = function () {
    let boy = "John";
    console.log(`His name is ${boy}.`);
}
male(); /* In this example, we declare a globally scoped variable named boy 
with the value of "Adams", and then we also initialize boy again inside the
anonymous function with a new value of "John", and log it to the console.
When the function is called, "His name is John" is logged to the console
because the locally scoped variable, boy, with the value of "John" would
override the globally scoped variable with a value of "Adams". But if we tried
using the boy variable outside of the function, we would get the value of 
"Adams", because the boy variable inside the function code block with the 
value of "John" can only be accessed within that function. This is a classic
example of locally scoped variables. */

//Globally scoped variable 
let girl = "Deborah";
const female = function () {
    console.log(`Her name is ${girl}.`);
}
female(); /* In this example, we declare a globally scoped variable named girl
with the value of "Deborah", and we don't have a similar variable inside the
anonymous function overriding the global girl variable. Therefore, when the 
function female is called, "Her name is Deborah" is logged to the console 
because the girl variable is a globally scoped variable and can be accessed 
from anywhere in the program including from inside the function. Therefore, its
value is passed to the function. This is a classic example of a globally
scoped variable. */

Nested Functions

Nested functions in JavaScript are functions that are written within other functions. Functions written inside of other functions can access the variables of their parent functions. Let's take a look at the syntax of Nested Functions:

// Example of nested functions
function addx (x) {
    function addy (y) {
        return x + y;
    }
    return addy;
}
console.log(addx(5) (7)); // Output is 12
/* The function addy is declared in the function addx, and the calculation
is then run inside addy, after which we return addy in the function body of 
addx. So when we log it to the console, we call the parent function addx, 
and pass the values of x and y respectively to obtain 12. */

Immediately invoked function expression (IIFE)

An Immediately invoked function expression is a function that is automatically called as it is being declared which means that it runs as soon it is defined. The syntax of IIFEs is illustrated below:

// Example of an Immediately invoked function expression
(function ()
    {
        console.log("This is an IIFE");
}) (); 
/* Notice the brackets () at the ending, it represents the function call, the
function is called immediately it's defined, and this logs "This is an IIFE"
to the console immediately its run. */

IIFEs are used for different purposes but one major one is to avoid polluting the global namespace. If there is a variable or function that you only need to use once, using an IIFE is a preferable solution to declaring the variable globally or to using a function expression or declaration, this helps declutter the global namespace of your program.

Two important things to note about functions

  • As said earlier in this article, the name of your function should give anyone looking into your code an insight into what the function does.

  • A function should do only one thing. It is bad development practice for a function to have more than one functionality as such a function would become less reusable and less adaptable.

Conclusion

A proper understanding of condition statements, loops, and functions in JavaScript is necessary for anyone who would become an efficient JS developer. Hopefully, this article has given you a good place to start in mastering the building blocks of one of the world's most utilized programming languages. Thanks for coming on this amazing journey with me!!!.

References

  1. What is JavaScript? A Definition of the JS Programming Language By Dillion Megida | freeCodeCamp.

  2. Loops and Iteration | mdn web docs.

  3. JavaScript For Loop | w3schools.