Learn Javascript Conditions, Arrays, and Loops


 

In modern web-based software developments, we frequently test logical conditions to execute a block of programming codes if a condition is met and execute an alternative block of codes if a condition is false. Also, more than one item sometimes are stored in a single variable called an array. Also, we need to loop through an array and access each item.

This article shall look at everything you need about JavaScript conditions, arrays, and loops.

 

Javascript Conditions

Javascript condition statements are used to perform actions based on the results of a logical condition. A logical condition results in either true or false.

 

How to use JavaScript IF condition?

The if condition specifies javascript codes executed if a condition is True. The syntax of javascript if is here:

if (condition) {

javascript codes executed if the condition is true

} else {

javascript codes executed if the condition is false

}

 

Example 1

Think of an example when validating a submit form. We need to validate that the submitted form input values are not empty. If one of the form input values is empty, display an error message on the web page.

To address this scenario first, let's write HTML codes to display a submit form on the web page as here:

 

<!DOCTYPE html>

<html>

<head>

<title>Javascript Form Validation</title>

<style>

h1{

background-color: lightgray;

}

.txt-firstname, .txt-lastname{

padding: 5px;

font-size: 16px;

margin: 10px;

border-radius: 5px;

}

button{

background-color: lightblue;

font-weight: bold;

padding: 10px;

font-size: 16px;

border-radius: 10px;

cursor: pointer;

}

</style>

</head>

<body>

<h1>My Submit Form</h1>

<p class=”errors”>Error Messages will be displayed here!</p>

<form>

<label>First Name:</label><br>

<input type='text' name='firstname' class='txt-firstname' placeholder='First Name'><br>

<label>Last Name:</label><br>

<input type='text' name='firstname' class='txt-lastname' placeholder='Last Name'><br>

<button>Submit</button>

</form>

</body>

</html>

 

HTML codes explained:

The above HTML codes create a web page with the following HTML elements:

Display the heading of the web page

with class=”errors” to display error messages

Create submit form

with class='txt-firstname'

with class='txt-lastname'

 

You can test the above HTML codes to get the output here:


Now write javascript codes to achieve the intended purpose as here:

<!DOCTYPE html>

<html>

<head>

<title>Javascript Form Validation</title>

<style>

h1{

background-color: lightgray;

}

.txt-firstname, .txt-lastname{

padding: 5px;

font-size: 16px;

margin: 10px;

border-radius: 5px;

}

button{

background-color: lightblue;

font-weight: bold;

padding: 10px;

font-size: 16px;

border-radius: 10px;

cursor: pointer;

}

</style>

<script>

function validateForm() {

let firstname = document.forms["myForm"]["firstname"].value;

let lastname = document.forms["myForm"]["lastname"].value;

if (firstname == "") {

alert("Firstname can not be empty");

} else if(lastname == ""){

alert("Lastname can not be empty");

} else {

alert("Data can be submitted successful");

}

}

</script>

</head>

<body>

<h1>My Submit Form</h1>

<p class='errors'></p>

<form name="myForm" method="post" action="" onsubmit="validateForm()">

<label>First Name:</label><br>

<input type='text' name='firstname' class='txt-firstname' placeholder='First Name'><br>

<label>Last Name:</label><br>

<input type='text' name='lastname' class='txt-lastname' placeholder='Last Name'><br>

<button>Submit</button>

</form>

</body>

</html>

Running the above HTML codes with embedded javascript codes placed at the <head> section will display an alert box as here:

 


 

Javascript Switch Statements

Javascript switch statements perform one of many actions on different conditions.

For instance, think of an example when we need to perform based on user choices. If the user selects “add” then the block of codes to add a new item will be executed, when the user selects “update” codes to update a selected item will be executed. If the user selects “delete” then a block of code to delete a selected item will be executed. If there are no matches then the default block of code to display a list of items will be executed.

The syntax for using javascript switch conditions is here:

 

switch(variable) {

case “add”:

// Execute Block of code to add a new item

break;

case “update”:

// Execute Block of code to update selected item

break;

case “delete”:

// Execute Block of code to delete the selected item

break;

default:

// Execute Default block of code

}

 

Syntax explained:

Note the break keyword is applied to prevent execution of the next case even if the evaluation does not match the case. On the other hand, if there is no case match then default keyword specifies the default code to run.

 

Javascript conditional ternary operator

Javascript ternary operator syntax takes a logical condition followed by a question mark (?) then the value to be displayed when a condition is true followed by a colon (:), and finally the value to be displayed when the condition is false. The syntax is as here:

condition ? ValueIfTrue : ValueIfFalse

Example 2:

Let's take an example of a login form, if the value of the variable isLogin is false then the login form will be displayed otherwise, if the value of variable isLogin is true then the user will be redirected to the user dashboard page.

Here are HTML, CSS, and javascript codes to perform the task:

<!DOCTYPE html>

<html lang="en">

<head>

<title>My Javascript Ternary Operator Example</title>

<style>

#username, #passwd {

margin: 10px;

padding: 8px;

border-radius: 10px;

font-size: 16px;

}

button{

margin: 5px;

padding-left: 20px;

padding-right: 20px;

padding-top: 10px;

padding-bottom: 10px;

border-radius: 10px;

background-color: rgb(9, 151, 30);

color: white;

font-size: 16px;

font-weight: bold;

cursor: pointer;

}

</style>

</head>

<body>

<p id="demo"></p>

<script>

let isLogin = false;

(!isLogin)? document.querySelector('#demo').innerHTML += "<form><label>Username:</label><input type='text' placeholder='Enter Username' id='username'/><br/><label>Password:</label><input type='text' placeholder='Enter Password' id='passwd'/><br/><button>Login</button></form>":document.querySelector('#demo').innerHTML += "<h1>User Login Successfuly</h1>";

</script>

</body>

</html>

 

If you assign the value of the isLogin variable to false the output will be as here:

 

If you assign the value of the isLogin variable to true the output will be as here:

 


 

Javascript arrays

A Javascript array is a variable that can store more than one item. Arrays are used to store a list of items and we can loop through an array to find a specific item by referring to index number.

How to create a javascript array?

We create a javascript array by using: array literals; and using new javascript keyword

Syntax to create an array using array literal is here:

const arrayName = [arrayItem1, arrayItem2 ……. arrayItemn] ;

 

Syntax explained:

 To create an array using array literals we start with a keyword const followed by array name then equal sign (=) and then square brackets ([]) in which inside square brackets we fill in array items.

An example is here:

const fruits = [“watermelon”,”banana”,”lemon”,”pineapple”];

In this example, we created a fruits array variable with array items “watermelon”,”banana”,”lemon”, and ”pineapple” respectively.

Syntax to create an array using the new javascript keyword is here:

const arrayName = new Array (arrayItem1, arrayItem2 ……. arrayItemn);

An example is here:

const fruits = new Array(“watermelon”, ”banana”, ”lemon”, ”pineapple”);

 

How array items are accessed?

Javascript array items are accessed using index numbers starting with array item with index number 0 and so on. The first item is accessed with a 0 index number and the second item with an index 1.

Also, we can know the number of items in the array using the length property as here:

numberOfItems = arrayName.length;

Therefore referring to a fruits array example, we can get a number of fruits in the array as here:

numberOfFruits = fruits.length;

Also, the first, second, and last items can be obtained here:

const firstItem = fruits[0];

const secondItem = fruits[1];

const lastItem = fruits[fruits.length-1];

 

How to change the array item?

We can use the index number to change the array item as here:

fruits[0] = “Orange”;

will change the array item with index 0 from “watermelon” to “orange”

 

Javascript Array methods

There are several array methods that you can use to manipulate array items like Array.push(), Array.splice(), Array.forEach(), Array.map() to mention few of them.

 

Array.push():

The array.push() method is used to add new items to the end of an array. Let's think of previous fruits example:

const fruits = [“watermelon”, ”banana”, ”lemon”, ”pineapple”];

if I want to add “mango” and “apple” at the end of the fruits array here is the javascript statement:

fruits.push(“mango”, “apple”);

Let's look at a real HTML example here:

 

Example 3


<!DOCTYPE html>

<html>

<head>

</head>

<body>

<h1>Array push example</h1>

<p class="fruits"></p>

<script>

const fruits = ["watermelon", "banana", "lemon", "pineapple"];

document.querySelector('.fruits').innerHTML = fruits;

</script>

</body>

</html>

 

Then add array.push statement at javascript codes to add “mango”, and “apple” as here:

 

<!DOCTYPE html>

<html>

<head>

</head>

<body>

<h1>Array push example</h1>

<p class="fruits"></p>

<script>

const fruits = ["watermelon", "banana", "lemon", "pineapple"];

fruits.push("mango", "apple");

document.querySelector('.fruits').innerHTML = fruits;

</script>

</body>

</html>

 

Array.splice()

The javascript Array.splice() method allows us to change the array items by removing or replacing array items with new ones.

If we want to remove, add, and replace array items then the splice() method is a tool for the work. The syntax for Array.splice() method is here:

Array.splice(whereToStart, CountRemove, newArrayItem, newArrayItem, newArrayItem, …)

Syntax explained:

whereToStart parameter specifies where to start removing, replacing, or adding array items

CountRemove parameter specifies how many array items should be affected

newArrayItem parameter specifies array items values to be inserted

 

Let's think of the following fruits array:

const fruits = [“watermelon”, ”banana”, ”lemon”, ”pineapple”];

 

Suppose you want to replace starting item with index 1 which is “banana”, ”lemon”, and ”pineapple” and replace them with “papaya”, “strawbale”, and “orange”. Here is a javascript statement:

fruits.splice(1,3,“papaya”, “strawbale”, “orange”);

 

A real-life HTML example is here:

Example 4:

 

<!DOCTYPE html>

<html>

<head>

</head>

<body>

<h1>Array push example</h1>

<p class="fruits"></p>

<script>

const fruits = ["watermelon", "banana", "lemon", "pineapple"];

fruits.splice(1,3,"papaya", "strawbell", "orange");

document.querySelector('.fruits').innerHTML = fruits;

</script>

</body>

</html>

 

Array Loops

We can loop through an array using either of the following: for loop, forEach(), and Array.map().

In this article, we are going to discuss about forEach() and Array.map() as follows:

 

Array.forEach()

The full syntax of Array.forEach() method is as follows:

array.forEach(function(Value, index, arr), thisValue)

Syntax explained:

forEach() method invokes a function for each item in an array

function parameter is required and is a function to run for each array item

Value is the value for the current array item

index is the index of the current item

arr is the array of the current item

thisValue parameter is the value passed to the function

 

Let us practice a real-life example of looping through fruits array items and displaying them as list items:

 

Example 5

<!DOCTYPE html>

<html>

<head>

</head>

<body>

<h1>Array push example</h1>

<p class="fruits"></p>

<script>

const fruits = ["watermelon", "banana", "lemon", "pineapple"];

fruits.splice(1,3,"papaya", "strawbell", "orange")

let myList = "<ul>";

fruits.forEach(myFunc);

myList+= "</ul>";

document.querySelector('.fruits').innerHTML = myList;

function myFunc(item){

myList+="<li>"+item+"</li>";

}

</script>

</body>

</html>

 

Array.map()

The array.map() method creates a new array by calling a function for every array element.

The syntax is as here:

array.map(function(Value, index, arr), thisValue)

forEach() method invokes a function for each item in an array

function parameter is required, and is a function to run for each array item

Value is the value for the current array item

index is the index of the current item

arr is the array of the current item

thisValue parameter is the value passed to the function

 

Let's refer to example 5 above but this time using the map() method instead of the forEach() method:

 

<html>

<head>

</head>

<body>

<h1>Array push example</h1>

<p class="fruits"></p>

<script>

const fruits = ["watermelon", "banana", "lemon", "pineapple"];

fruits.splice(1,3,"papaya", "strawbell", "orange")

let myList = "<ul>";

fruits.map(myFunc);

myList+= "</ul>";

document.querySelector('.fruits').innerHTML = myList;

function myFunc(item){

myList+="<li>"+item+"</li>";

}

</script>

</body>

</html>

 

The output will be as here:

 


Conclusion

In this article, we explained in detail how to work with javascript logical conditions, javascript arrays, and how to loop through javascript array items. We covered logical conditions such as: if condition, switch, and ternary operators. We have discussed about forEach() and map() methods and looked at real-life examples of how to use them to build web applications.


Post a Comment

0 Comments