Introduction
This tutorial continues from where JavaScript Made Easy - Part One ended. Consequently, if you are a beginner in JavaScript, you need to take part one before you attempt this tutorial.
As we did in part one, we are are going to be using scrimba IDE for demonstrating example codes in this tutorial. Though, you are free to use any IDE of your choice if you are not new to coding.
We use explanatory comments in our example codes, please pay attention to the comments while you are studying this tutorial. They were inserted into the codes to make it simpler and easier for you to understand.
Now, let us go straight to business and learn more JavaScript concepts to enhance your JavaScript skills and capability.
Template Strings (Template Literals)
Template strings use back-ticks (``
) instead of double (""
) or single (''
) to define a string. Practice with the example below:
<script>
text1 = "This is my string using double quotes";
text2 = 'This is my string using single quotes';
text3 = `This is my string using back-ticks`;
console.log(text1);
console.log(text2);
console.log(text3);
</script>
With template strings, you can have both single and double quotes in a string. Practice with the example below:
<script>
myString1 = `James said "it's going to rain". Didn't he?`;
console.log(myString1);
</script>
If you try the example above with double or single quotes, you will run into problem. Try with the example below:
<script>
myString2 = "James said "it's going to rain". Didn't he?";
console.log(myString2);
myString3 = 'James said "it's going to rain". Didn't he?';
console.log(myString3);
</script>
You can fix the problem above by with the use of the escape character, the back slash (\
). You just need to place an escape character before each of the quotes matching the one use to define the string as shown below:
<script>
myString2 = "James said, \"it's going to rain\". Didn't he?";
console.log(myString2);
myString3 = 'James said, "it\'s going to rain". Didn\'t he?';
console.log(myString3);
</script>
In some instances where you have only one type of quotes in the string, you can fix the problem by avoiding using matching quotes to define the string. That is, if you have single quote(s) in the string, use double quotes to define the string and if you have double quote(s) in the string, use single quotes to define the string as shown below:
<script>
myString2 = "it's going to rain.";
console.log(myString2);
myString3 = 'James said, "I will throw the ball".';
console.log(myString3);
</script>
Also, template strings support the use of multiline strings which is not possible with single or double quotes. Practice with the example below:
<script>
myString = `I will like to
visit the Antarctica
next year`;
console.log(myString)
</script>
Template strings provide an easier, more concise and better alternative to incorporate variables and expressions into strings as illustrated below:
<script>
let userFirstName = "Amy";
let userLastName = "Wood";
console.log(`Welcome to Tutorialsnote ${userFirstName} ${userLastName}!`)
console.log("See below the alternative approach using either single or double quotes")
console.log("Welcome to Tutorialsnote" + " " + userFirstName + " " + userLastName +"!")
</script>
Arrow Functions
An arrow function is nameless and is a concise way of declaring functions in JavaScript. It is best suited for simple functions that you use only once. It has the following general syntax:
<script>
(parameters) => {//line(s) of code you want to execute;}
</script>
Since arrow function is nameless, it is a common practice to store it in a variable and use the variable name to call it like a regular function when it is required. Practice with the example below. To make it easy to understand, we first declared the function using the regular function expression and then make modifications to transform it to an arrow function:
<script>
//Regular function expression
function greetings (name) {
console.log(`Hello ${name}!`);
}
greetings("Amy") // to call the function
</script>
Here is the arrow function equivalent. We followed the general syntax above and stored the function in a variable named greetings, we have:
<script>
const greetings = (name) => {
console.log(`Hello ${name}!`);
}
greetings("Laura"); // to call the function
</script>
If your arrow function has only one statement and the statement returns a value, you can do away with the curly bracket and (the return keyword where applicable) as shown below:
<script>
const greetings = (name) => console.log(`Hello ${name}!`);
greetings("Laura"); // to call the function
</script>
Also, if your arrow function has only one parameter, you can throw away the parenthesis as shown below:
<script>
const greetings = name => console.log(`Hello ${name}!`);
greetings("Laura"); // to call the function
</script>
The switch
Statement
You can use the switch
statement instead of if
and else if
statements when you have multiple conditions. Switch requires less code and repetitions and therefore making your code more compact. The general syntax for switch
is as follows:
<script>
keyword varaibleName = variableValue;
switch(switchExpression) {
case caseValue1:
//line(s) of code to be executed;
break;
case caseValue2:
//line(s) of code to be executed;
break;
case caseValuex:
//line(s) of code to be executed;
break;
default: // default case if there are no matches
//line(s) of code to be executed if there are no matches;
}
</script>
Here is the steps for switch statement:
Declare the
switch
statement with its switchExpression; (switchExpression can be a variable, value or boolean) enclosed inside the parenthesis at the front ofswitch
statementInside the curly bracket, declare the case, assign a caseValue or caseCondition to it and terminate the line with a colon :
The subsequent line(s) of code after the case line are the code to be executed if the caseValue or caseCondition matches the switchExpression’s variableValue or condition
Finally terminate the case with a break statement, this is necessary to ensure we break out of the switch once there is a matching case. Otherwise all the other cases code within the switch will be executed
Repeat steps 2 to 4 to create as many cases as required
Declare the default case to take care of situation where there is no match between the switch condition and the case
In the example below, we used switch to create a program that scans products in a store and give you the name and price of the product. Where the product scan is not in the not in the store, you get a message that the store does not have the product you scanned:
<script>
const productCode = 1002;
let product;
let price;
switch (productCode) {
case 1001:
product = "Sugar";
price = 1.22;
console.log(`${product} is $${price}`);
break;
case 1002:
product = "Milk";
price = 2.50;
console.log(`${product} is $${price}`);
break;
case 1003:
product = "Tea";
price = 3.10;
console.log(`${product} is $${price}`);
break;
default:
console.log("Sorry, we don't have the product you scanned");
}
</script>
Note that for the example above, you can achieve the same objective with if
and else if
statements as follows:
<script>
const productCode = 1004;
let product;
let price;
if (productCode === 1001) {
product = "Sugar";
price = 1.22;
console.log(`${product} is $${price}`);
}
else if (productCode === 1002) {
product = "Milk";
price = 2.50;
console.log(`${product} is $${price}`);
}
else if (productCode === 1003) {
product = "Tea";
price = 3.10;
console.log(`${product} is $${price}`);
}
else {
console.log("Sorry, we don't have the product you scanned");
}
</script>
Here is a more complex example. The code give variable discount to customers based on the total value of their purchase. Practice the code below:
<script>
const totalPurchase = 175;
let discountRate;
let discountValue;
let discountedPurchase;
switch (true) {
case totalPurchase >= 500: //this is caseCondition1
discountRate = 0.15;
discountValue = (discountRate * totalPurchase);
discountedPurchase = (totalPurchase - discountValue);
console.log(`Your total purchase is $${totalPurchase}, your discount is $${discountValue}, Amount due for payment is: $${discountedPurchase}`);
break;
case totalPurchase >= 350: //this is caseCondition2
discountRate = 0.10;
discountValue = (discountRate * totalPurchase);
discountedPurchase = (totalPurchase - discountValue);
console.log(`Your total purchase is $${totalPurchase}, your discount is $${discountValue}, Amount due for payment is: $${discountedPurchase}`);
break;
case totalPurchase >= 150: //this is caseCondition3
discountRate = 0.05;
discountValue = (discountRate * totalPurchase);
discountedPurchase = (totalPurchase - discountValue);
console.log(`Your total purchase is $${totalPurchase}, your discount is $${discountValue}, Amount due for payment is: $${discountedPurchase}`);
break;
default:
discountRate = 0;
discountValue = (discountRate * totalPurchase);
discountedPurchase = (totalPurchase - discountValue);
console.log(`Your total purchase is $${totalPurchase}, your discount is $${discountValue}, Amount due for payment is: $${discountedPurchase}`);
}
</script>
If you look at the example code above, you will see that we have a lot of repetition. This is an indication that we can improve the code even though it works as it is. Whenever you see yourself repeating lines of code in your program, it is an indication of opportunity to create a function to handle the task being repeated. To improve the code, we created a function named discountMgt
which handles the repetitive task and call the function as many time as we need in the switch statement. The code is therefore neater and more concise. Review and practice with the code below:
<script>
let totalPurchase = 80;
function discountMgt(discountRate=0) {
let discountValue = (discountRate * totalPurchase);
let discountedPurchase = (totalPurchase - discountValue);
console.log(`Your total purchase is £${totalPurchase}, your discount is £${discountValue}, Amount due for payment is: £${discountedPurchase}`);
} //We used £ here to clearly show that the first $ sign represents the currency
switch(true) {
case totalPurchase >= 500: //this is caseCondition1
discountMgt(0.15);
break;
case totalPurchase >= 350: //this is caseCondition2
discountMgt(0.1);
break;
case totalPurchase >= 150: //this is caseCondition3
discountMgt(0.05);
break;
default:
discountMgt();
}
</script>
In the last two examples above, the switchExpression is boolean value true
. In such scenario, JavaScript compares the totalPurchase
value with the condition in caseCondition1, if the outcome of the comparison is true
, the subsequent lines of code under caseCondition1 are executed and the switch operation terminates. Otherwise, it moves to the next caseCondition(s) and if none of the caseConditions evaluates to true, the default statement is executed and the switch operation terminates.
Logical Operators
Logical operators are used to determine the logic between two expressions (values or variables). There are three of them, the and (&&), the or (||) and not (!). Let us briefly discuss each of them,
The AND Operator (&&
): It is represented by &&
, it checks if the two expressions are true
, it returns true
, and returns false
if one or both of them are false. Practice with the example below:
<script>
console.log((4 + 3) === 7 && 2*5 === 10); //returns true
console.log((4 + 3) === 7 && 2*5 === 9); //returns false
console.log((4 + 3) < 5 && 2*5 > 12); //returns false
</script>
The OR Operator (||
): It is represented by ||
, it returns true if both or one of the expressions are true, otherwise, it returns false. Practice with the examples below:
<script>
console.log((4 + 3) === 7 || 2*5 === 10); //returns true
console.log((4 + 3) === 7 || 2*5 === 9); //returns true
console.log((4 + 3) < 5 || 2*5 > 12); //returns false
</script>
The NOT Operator (!
): It is represented by !
, it returns true
for false
expressions and false
if the expression is true
. That is, it returns the opposite of the expression. Practice with examples below:
<script>
const a = 7
console.log(!(a === 7)); //returns false
console.log(!(a === 5)); //returns true
console.log(!(a < 5)); //returns true
</script>
Combining Logical Operators with if Statement
Most of the time logical operators used in conjunction with if
statement. They are used to define the if conditions. Practice with the examples below:
Using if
statement with AND Operator
<script>
const gender = "male";
const age = 42;
if (gender === "male" && age >= 40) {
console.log(`You are a ${gender} and ${age} years old, you need to go for medical check`);
}
else if (gender === "female" && age >= 45) {
console.log(`You are a ${gender} and ${age} years old, you need to go for medical check`)
}
else {
console.log(`You are a ${gender} and ${age} years old, you do not need a medical check`)
}
</script>
Using if
statement with OR Operator:
<script>
const isRaining = true;
const isSunny = true;
if (isRaining || isSunny) {
console.log("Take your umbrella when you are going out");
}
else {
console.log("You do not need an umbrella");
}
</script>
Using if statement with NOT Operator
<script>
const gender = "female";
const age = 30;
if (gender === "male" && age >= 40) {
console.log(`You are a ${gender} and ${age} years old, you need to go for medical check`);
}
else if (!(gender === "male") && age >= 45) {
console.log(`You are a ${gender} and ${age} years old, you need to go for medical check`)
}
else {
console.log(`You are a ${gender} and ${age} years old, you do not need a medical check`)
}
</script>
Ternary Operator
This is a short form of if
statement without using if
. All you need is to define the if
condition and terminate it with a question mark; this is then followed by the value to be displayed (or code to be executed) if the condition is true
; put a colon and finally the value to be displayed (or the code to be executed) if the the condition is false
. The general syntax is as follows:
variableKeyword variableName = (the boolean condition)? value_if_true : value_if_false
variableKeyword - this can be
let
orconst
variableName - the name you want to call the variable
the boolean condition - this is a condition that evaluates to either
true
orfalse
. It is usually wrapped inside parenthesis and followed by?
value_if_true - this is the value that should be returned if the boolean condition evaluates to
true
value_if_false - this is the value that should be returned if the boolean condition evaluates to
false
Practice this concept with the example below:
<script>
const budget = 3500
const carPrice = 5480;
const affordableCar = (carPrice <= budget)? "The car is affordable" : "The car is beyond budget";
console.log(affordableCar);
</script>
In the example above the boolean condition evaluates to false
because the carPrice
is more than the budget. You can reduce the value of carPrice
to a figure within the budget so that the boolean condition can evaluate to true, then run the code again to see the impact on the output of the code. Let us do the example above with regular if statement to make it clearer:
<script>
const budget = 3500
const carPrice = 5480;
if(carPrice <= budget) {
console.log("The car is affordable");
}
else {
console.log("The car is beyond budget");
}
</script>
Here is another example where we use ternary operator to set customer’s total payment depending on wether the customer meet the discount limit or not:
<script>
let totalPurchase = 140
const discountRate = 0.1
const discountAmount = totalPurchase*discountRate
const discountLimit = 150
const totalPmtDue = (totalPurchase >= discountLimit)? (totalPurchase - discountAmount) : totalPurchase
console.log(`Total Payment due: ${totalPmtDue}`)
</script>
The for
Loop
To use a for
loop, you need the following components: loop counter, loop condition and the increment step. The general syntax is as follows:
<script>
for (loop counter; loop condition; increment step) {
//line(s) of code we want to run repeatedly;
}
</script>
The loop counter keeps track of number of iteration.
The loop condition is the condition that must be fulfilled for the loop to continue, it sets a boundary or limit for the loop
The increment step is used to increment or decrement the loop counter. It specifies the movement between each iteration of the loop
Let us practice this with an example. The i
in the code below is a customary name for the loop counter, it means index. You can set i
initial value to any number depending on what you want to achieve:
<script>
for (let i = 0; i <= 3; i += 1) {
console.log(i); //this shows that i is just a counter
console.log("Tutorialsnote");
}
</script>
You can skip a step(s) in the for
loop using an if
statement and continue
keyword. Where the if
condition is met, the continue
keyword instructs JavaScript to skip that particular iteration of the loop and move to the next iteration. In the code below, we set a condition that makes the loop to skip all the iterations where the counter is an odd number. (i % 2 === 1
) means i/2 gives a remainder of 1. Any number that gives remainder of 1 when divided by 2 is an odd number:
<script>
for (let i = 0; i <= 15; i += 1) {
let number = 10 + i;
if (i % 2 === 1) {
continue;
}
else {
console.log(`10 + ${i} = ${number}`);
}
}
</script>
You can stop and exit a for
loop with break
keyword even when the loop condition still evaluates to true
. In the example code below, we set a condition that stops the loop whenever i = 5:
<script>
for (let i = 0; i <= 15; i += 1) {
let number = 10 + i;
if (i === 5) {
break;
}
else {
console.log(`10 + ${i} = ${number}`);
}
}
</script>
The while
Loop
The while
loop is used to execute line(s) of code repeatedly as long as a specified condition is met. It has the following general syntax:
<script>
let i = x; // The i is the loop counter (note that x is an integer)
while (theLoopCondition) {
The loop body //the line(s) of code to be executed
increment step // this is required to prevent the loop from running indefinitely
}
</script>
The while loop follows the cycle below:
A while loop evaluates the theLoopCondition inside the parenthesis
()
.If the theLoopCondition evaluates to true, the line of code(s) inside the loop body is executed.
The theLoopCondition is evaluated again and the execution of the line of code(s) inside the loop body is repeated.
Steps 1 to 3 above continue until the theLoopCondition evaluates to false.
When the theLoopCondition evaluates to false, the loop terminates.
Let us practice with the example below:
<script>
let i = 1;
while (i <= 5) {
console.log(i); //Line of code to be executed repeatedly
console.log("I am learning JavaScript") // Another line of code to be executed repeatedly
i = i + 1; //*Increment step. DO NOT FORGET TO ADD INCREMENT STEP. Otherwise, the code will run perpetually
//i ++; // An alternative way of writing i = i + 1
//i += 1 // An alternative way of writing i = i + 1
};
</script>
*DO NOT FORGET TO ADD INCREMENT STEP. Otherwise, the code will run perpetually because i
will always be less than five without the increment step! Here is step by step of what happens in the code above:
JavaScript takes the original value assigned to variable
i
and compares it against the loop conditionIf the value of
i
satisfies the loop condition, that is, if it evaluates to true, JavaScript moves to the loop body and execute every line of code in the loop body including the increment step that supplies a new value fori
Upon getting a new value for
i
, JavaScript move back to the loop condition and compares the new value ofi
against the loop condition, if the loop condition is met, the step 2 is repeated. The cycle continues between steps 2 and 3 until the loop condition is no longer satisfied and the loop terminatesIf there is no increment step in the loop body, when JavaScript is done executing the lines of code in the loop body, the only value of
i
JavaScript has will always be the original value ofi
which will always be less 5, which meets the loop condition and therefore the loop will continue to run forever.
Let us practice with another example:
<script>
let sum = 0; //the variable to store the sum of the numbers
let number = 1;
while(number < 10) {
console.log(number); //To display the numbers one after the other
sum += number; //To compute the sum of the numbers
number += 1; //To increment number
};
console.log(`The sum of all the numbers is ${sum}.`); //To display the sum
</script>
The do…while
Loop
This is a variant of while
loop where the code in the loop body is executed once first before the loop condition is evaluated and then it will repeat the loop as long as the loop condition evaluates to true. It has the following general syntax:
<script>
do {
// line(s) of code to be executed
}
while (theLoopCondition);
</script>
The do…while loop follows the cycle below:
The loop body is executed once first, then, the while loop evaluates the theLoopCondition inside the parenthesis
()
.If the theLoopCondition evaluates to true, the code inside the loop body (or do statement) is executed.
The theLoopCondition is evaluated again and the execution of the code inside the loop body is repeated.
Steps 2 and 3 above continue until the theLoopCondition evaluates to false.
When the theLoopCondition evaluates to false, the loop terminates.
Let us practice with the example below:
<script>
let number = 0;
do {
console.log(number);
number += 1;
}
while(number < 10);
</script>
The for loop or while loop?
How do you determine which one to use, for
loop or while
loop? The for
loop is best suited for situations where the number of iterations is known. On the other hand, while
and do…while
loops are best suited for scenarios where the number of iterations are not known.
Objects
An object is a variable that allows assignment of multiple unordered values. These values are referred to as properties. Each property in an object consists of key: value pairs. The general syntax for an object is as follows:
<script>
variableKeyword objectName = {
property1,
property2,
…,
propertyX
};
</script>
Since a property
consists key: value pairs, the general syntax can be further broken down as follows:
<script>
variableKeyword objectName = {
key1: value1,
key2: value2,
…,
keyx: valuex
};
</script>
Object allows us to group and use related multiple values together instead of declaring variable for them individually. For a regular variable you can have this:
<script>
const studentFirstName = "James"
const studentLastName = "Wood"
const studentId = 1022
const studentAge = 18
const studentCourse = "Data Science"
const studentLevel = 200
console.log(`Student Name: ${studentFirstName} ${studentLastName}, Student Id: ${studentId}, Age: ${studentAge}, Course: ${studentCourse}, Year: ${studentLevel}`)
</script>
However, with object we can group all the student details together in a single variable with more compact code as shown below:
<script>
const student = {
firstName: "James",
lastName: "Wood",
Id: 1022,
Age: 18,
Course: "Data Science",
Level: 200
}
console.log(student)
</script>
Accessing Objects Properties
JavaScript objects properties values can be accessed with either dot (.
) or square brackets []
notation. The general syntax is as follows:
<script>
variableKeyword objectName = {
key1: value1,
key2: value2,
…,
keyx: valuex
};
objectName.key1; // this will return value1
objectName.key2; // this will return value2
objectName.keyx; // this will return valuex
</script>
Note that the general syntax is just a model, hence, it will give error message if you attempt to run it on your IDE. Practice with the real examples below:
<script>
const student = {
firstName: "James",
lastName: "Wood",
Id: 1022,
Age: 18,
Course: "Data Science",
Level: 200
}
// using dot notation:
console.log(student.firstName)
console.log(student.lastName)
console.log(`I am ${student.firstName} ${student.lastName}`)
//using bracket notation:
console.log(student["firstName"])
console.log(student["lastName"])
console.log(`I am ${student["firstName"]} ${student["lastName"]}`)
//Note that property keys were wrapped in quotes when you use bracket notation
</script>
Adding and Modifying Object Properties
You can create an empty object and add properties to it later, add more properties to an object or modify an object existing properties (change the property value or delete the property) using either dot or bracket notions. Practice with the examples below.
Adding properties to an empty object:
<script>
const customer = {};
console.log(customer)
customer.firstName = "Amy"; //using dot notation
customer.lastName = "Parker"; //using dot notation
customer["telNo"] = 0123456789; //using bracket notation
console.log(customer)
</script>
Adding more properties to an object:
<script>
const customer = {
firstName: "Amy",
lastName: "Parker",
};
console.log(customer)
//Add more properties to customer object
customer.telNo = "0123456789"; //Using dot notation
customer["email"] = "amy.parker@example.com"; //Using bracket notation
console.log(customer)
</script>
Changing the value of an existing object’s property. In the example below, we modified Amy’s details by changing her lastName to Anderson. When you run the code below, the output of the second console.log(customer)
will reflect the change of Amy’s lastName from Parker to Anderson:
<script>
const customer = {
firstName: "Amy",
lastName: "Parker",
telNo: "0123456789",
email: "amy.parker@example.com"
};
console.log(customer);
//Our customer is married and wants to change her last name to Anderson. All we need to do is to simply assign Anderson as the value of her lastName as shown below:
customer.lastName = "Anderson";
console.log(customer);
</script>
To delete an existing property in an object outrightly, use delete
key word as shown below:
<script>
const customer = {
firstName: "Amy",
lastName: "Parker",
telNo: "0123456789",
email: "amy.parker@example.com"
};
console.log(customer);
//In exercise of her GDPR right, Amy has requested that her email be deleted from the company's database. This can be simply done as follows:
delete customer.email
console.log(customer);
</script>
Nesting Objects
This is when you have an object inside another object as shown below:
<script>
const person = {
fname: "James",
lname: "Cassy",
age: 45,
children: {
firstChild: "Amy",
secondChild: "Tom"
}
};
console.log(person);
</script>
Assuming we need to store more details about the children, we can do it by adding another layer of nesting as shown below:
<script>
const person = {
fname: "James",
lname: "Cassy",
age: 45,
children: {
firstChild: {
name: "Amy",
age: 15,
school: "High School for Girls"
},
secondChild: {
name: "Tom",
age: 12,
school: "High School for Boys"
}
}
};
console.log(person);
</script>
You can access nested object properties using their keys as illustrated below:
<script>
const person = {
fname: "James",
lname: "Cassy",
age: 45,
children: {
firstChild: {
name: "Amy",
age: 15,
school: "High School for Girls"
},
secondChild: {
name: "Tom",
age: 12,
school: "High School for Boys"
}
}
};
//To access the properties of the first level (outer) nest, do the following using either dot or bracket notation:
const firstBorn = person.children.firstChild;
console.log(firstBorn);
const secondBorn = person["children"]["secondChild"];
console.log(secondBorn);
//To access the properties of the second level (inner) nest, do the following:
const firstBornName = person.children.firstChild.name;
console.log(firstBornName);
const secondBornName = person["children"]["secondChild"]["name"];
console.log(secondBornName);
</script>
Objects Methods
JavaScript objects can have what is called methods. A Method is an action which can be performed on object. It is a function stored as one of the object’s properties. Practice with the example code below:
<script>
const car = {
brand: "Volvo",
model: "C70",
price: 15000,
carDetails: function details () {
return `This is ${this.brand} ${this.model}, it costs $${this.price} only`
}
};
// We shall explain JavaScript this keyword in the next section
console.log(car.carDetails())
</script>
We can make the code above more concise using Shorthand Object Method. This entails throwing away the function
keyword and the function name (details
) as illustrated below:
<script>
const car = {
brand: "Volvo",
model: "C70",
price: 15000,
carDetails() {
return `This is ${this.brand} ${this.model}, it costs ${this.price} only`;
}
};
console.log(car.carDetails())
</script>
The this
Keyword
In JavaScript this
keyword refers to an object. Which object it refers to depend on the context in which it is being used. When this
is used in an object method, it refers to the object as in the car
object example above. When this
is used alone, it refers to the global object. When this
is used in event handlers, it refers to HTML element that triggers the event as demonstrated in the example below:
<body>
<button id="btn">Click to see this</button>
<script>
document.getElementById("btn").addEventListener('click', function () {
console.log("In this example, here is \"this\":", this);
});
</script>
</body>
In the example code above, each time you click on the “Click to see this” button, the following is displayed on the console.
In this example, here is "this":,<button id="btn">
Objects names are references
An object name is a reference that points to the location where the object properties are saved in the computer memory. The object name is similar to a shortcut on your computer. Shortcut is not the file but just point to the file location in the computer memory. As a result of this, you cannot create a copy of an object by assigning its name as the value of the new object. For example, in the code below, const student = myFriend
does not create a copy of myFriend
, it only creates a copy of the reference:
<script>
const myFriend = {
firstName: "Tom",
lastName: "Wood",
age: 25
};
console.log(myFriend);
const student = myFriend;
console.log("Space");//just to create a space
console.log(student);
</script>
In the code above, student
and myFriend
share the same reference and point to the same location in the computer memory, they are therefore one and the same. Any changes you make to myFriend
automatically reflects in student
. This is demonstrated in the modified code below:
<script>
const myFriend = {
firstName: "Tom",
lastName: "Wood",
age: 25
};
console.log(myFriend);
const student = myFriend;
console.log("Space"); //just to create a space
console.log(student);
myFriend.dateOfBirth = "Dec 25, 2005"
console.log(myFriend);
console.log("Space"); //just to create a space
console.log(student)
</script>
Note that although const
keyword prevents us from changing the reference in a variable, it does not prevent us from accessing the reference and changing the object properties’ values it points to. As a result, we can access and change the properties of object myFriend
even though it was created with const
keyword as illustrated below:
<script>
const myFriend = {
firstName: "Tom",
lastName: "Wood",
age: 25
};
myFriend.firstName = "Kim";
myFriend.lastName = "Lee";
myFriend.age = 28;
console.log(myFriend);
</script>
You can directly compare two variables and get accurate result as demonstrated below:
<script>
const myFriend = "Kim";
const student = "Kim";
console.log(myFriend === student) // this returns true
</script>
Contraryly, if you try to compare two objects as we did above for variables in the example above, you will get a misleading result as demonstrated below:
<script>
const myRoomMate = {
firstName: "Tom",
lastName: "Wood",
age: 25
};
const myHouseMate = {
firstName: "Tom",
lastName: "Wood",
age: 25
};
console.log(myRoomMate === myHouseMate); //this will return false
</script>
Comparison of myRoomMate
and myHouseMate
above returns false because object names are references and object names for different objects have different references. In the example code above, the comparison operator only compares the references and not the values stored in the computer memory.
Object Destructuring
You can assign an object property as a variable value as shown below:
<script>
const student = {
firstName: "Laura",
lastName: "Wood"
};
const firstName = student.firstName; //
console.log(firstName);
const lastName =student.lastName;
console.log(lastName);
</script>
If the variable name and the name of the object property we need to access (or assign to the variable) are the same, there is a more compact way to write the code, this more concise approach illustrated below is called destructuring:
<script>
const student = {
firstName: "Laura",
lastName: "Wood"
};
const {firstName} = student;
console.log(firstName);
const {lastName} = student;
console.log(lastName);
</script>
In the code above, const {firstName} = student;
takes firstName
property from student object and save it in a variable firstName
. Similarly, const {lastName} = student;
takes lastName
property from student
object and save it in a variable lastName
. Where you need to access multiple property values as we have in this example, you don’t need to write them line by line as we did above. You can write them on a single line and make your code more compact as shown below:
<script>
const student = {
firstName: "Laura",
lastName: "Wood"
};
const {firstName, lastName} = student;
console.log(firstName);
console.log(lastName);
</script>
Shorthand Property
If you have a scenario where you need to assign variable(s) as property value(s) for an object, you can do this as illustrated below:
<script>
const brand = "Volvo";
const model = "C70";
const price = 15000;
const car = {
brand: brand, //This assigns brand variable value value to the brand property in the car object
model: model,
price: price
};
console.log(car);
</script>
Where the property key and the variable name are the same as in the code above, you can just type it once in the object. This is what is referred to as shorthand property. Practice with the example below:
<script>
const brand = "Volvo";
const model = "C70";
const price = 15000;
const car = {
brand, //This is called shorthand property
model, //This is called shorthand property
price //This is called shorthand property
};
console.log(car);
</script>
JavaScript Arrays
In JavaScript, an array like an object is special variable which can hold multiple values. That is, it enables us to hold multiple values under a single name and each of the values can be accessed via their respective index numbers. An array is another data type and it represents a list of values. The general syntax for declaring an array is as follows:
<script>
const arrayName = [item1, item2, ..., itemX]
</script>
In the general syntax above, you have the variable keyword (const or let) followed by the arrayName, then an assignment operator and finally the items (elements) enclosed in a square bracket. Here is an example of an array:
<script>
const fruits = ["Apple", "Blackberry", "Avocado"]
console.log(fruits)
</script>
Instead of storing each of the fruits in three separate variables, we stored the three of them with a name using an array. With this approach our code is more compact and more efficient. In arrays, blank spaces and line breaks are irrelevant, an array declaration can take multiple lines as shown below:
<script>
const fruits = [
"Apple",
"Blackberry",
"Avocado"
]
console.log(fruits)
</script>
You can create an empty array and provide the items later using index numbers as shown below:
<script>
const fruits = [];
fruits[0] = "Apple";
fruits[1] = "Blackberry";
fruits[2] = "Avocado";
console.log(fruits);
</script>
You can also use .push()
method to add an item to an array, it adds the item to the last position in the array. Practice with the example below:
<script>
const fruits = [];
fruits.push("Apple");
fruits.push("Blackberry");
fruits.push("Avocado");
console.log(fruits);
</script>
You can access and or modify items in an array using their relevant index numbers. Note that the index numbering starts from 0, so the first item in an array has index number 0, second item has index number 1 and it continues that way. Practice with the example below:
<script>
const fruits = ["Apple", "Blackberry", "Avocado"];
console.log(fruits); //To display fruits before modification
const myFruit = fruits[0]; //To access an item in the fruits array
console.log(myFruit); //To display the item being accessed
fruits[2] = "Banana"; //To change the item at index number 2 to "Banana"
fruits[3] = "Orange"; //To add a new item to the array. You can do this with fruits.push("Orange")
console.log(fruits); // to display
</script>
An array can contain multiple data types such as strings, numbers, objects, arrays, functions etc as illustrated in the example below:
<script>
const myArray = ["Amy", {student: {Name: "Laura", Age: 20, Height: 1.5}}, 100, Date.now()];
console.log(myArray);
const student = myArray[1];
console.log(student)
</script>
Now, let us discuss some of the common array properties and methods.
Array .length
property
Array .length
property returns the number of items in an array. Practice with the example below:
<script>
const students = ["Amy", "Tom", "Harry", "Laura"];
console.log(students.length);
const numbers = [0, 10, 20, 30, 40, 50];
console.log(numbers.length);
</script>
Since the index number of the last item in an array is 1 less than the array length, you can exploit this knowledge to access the last item or even any item in an array using .length
property as illustrated the example below:
<script>
const students = ["Amy", "Tom", "Harry", "Laura"];
console.log(students[students.length - 1]); //student.length - 1 gives the index number of the last item in students array irrespective of the numbers of items it has
console.log(students[students.length - 2]); //student.length - 2 gives the index number of the item before the last in students array irrespective of the numbers of items it has
const numbers = [0, 10, 20, 30, 40, 50];
console.log(numbers[numbers.length - 1]);
console.log(numbers[numbers.length - 2]);
</script>
Array .splice()
method
The .splice()
method removes the specified item(s) from an array. The starting item is specified with its index number. The general syntax is as follows:
<script>
arrayName.splice(theStartingIndexNo, noOfItemsToBeRemoved)
</script>
Practice with the example code below:
<script>
const students = ["Amy", "Tom", "Harry", "Laura"];
students.splice(2, 2); //This code will remove 2 items (Harry and Laura) from students array starting from index no 2 (Harry)
console.log(students);
const numbers = [0, 10, 20, 30, 40, 50];
numbers.splice(1, 3); //This code will remove 3 items (10, 20 and 30) from numbers array starting from index no 1 (10)
console.log(numbers);
</script>
Array .pop()
method
The .pop()
method removes the last element from the array. Practice with the example below:
<script>
const students = ["Amy", "Tom", "Harry", "Laura"];
students.pop();
console.log(students);
const numbers = [0, 10, 20, 30, 40, 50];
numbers.pop();
console.log(numbers);
</script>
You can store and access the “popped” element in a variable as illustrated below:
<script>
const students = ["Amy", "Tom", "Harry", "Laura"];
students.pop();
console.log(students);
const poppedStudent = students.pop(); //Returns the popped element
console.log(poppedStudent);
const numbers = [0, 10, 20, 30, 40, 50];
numbers.pop();
console.log(numbers);
const poppedNumber = numbers.pop(); //Returns the popped element
console.log(poppedNumber);
</script>
The .shift()
method
The .shift()
method removes the first element in an array, it does the opposite of .pop()
method. Practice with the examples below:
<script>
const students = ["Amy", "Tom", "Harry", "Laura"];
students.shift();
console.log(students);
const numbers = [0, 10, 20, 30, 40, 50];
numbers.shift();
console.log(numbers);
</script>
You can store and access the “shifted” element in a variable as illustrated below:
<script>
const students = ["Amy", "Tom", "Harry", "Laura"];
students.shift();
console.log(students);
const shiftedStudent = students.shift(); //Returns the shifted element
console.log(shiftedStudent);
const numbers = [0, 10, 20, 30, 40, 50];
numbers.shift();
console.log(numbers);
const shiftedNumber = numbers.shift(); //Returns the shifted element
console.log(shiftedNumber);
</script>
Array .slice()
method
The .slice()
method returns selected elements from an array as a new array. The element are selected with their index numbers. The .slice()
method includes the starting index number but excludes the ending index number. Practice with the examples below:
<script>
const students = ["Amy", "Tom", "Harry", "Laura"];
const slicedStudents = students.slice(1, 3); //Includes index no 1 but excludes index no 3
const mySlicedStudents = students.slice(-4, -2); //Includes -4 but excludes -2. If you start from the last element in the array, the index numbering starts from -1. That is, "Laura" has index no of -1, "Harry" is -2 etc
const aSlicedStudents = students.slice(0, -1) //Returns all the elements except the last one
console.log(students);
console.log(slicedStudents);
console.log(mySlicedStudents);
console.log(aSlicedStudents);
const numbers = [0, 10, 20, 30, 40, 50];
const slicedNumbers = numbers.slice(2, 5); //Includes index no 2 but excludes index no 5
const mySlicedNumbers = numbers.slice(-6, -2); //Includes -6 but excludes -2
const aSlicedNumbers = numbers.slice(0, -1); //Returns all the elements except the last one
console.log(numbers);
console.log(slicedNumbers);
console.log(mySlicedNumbers);
console.log(aSlicedNumbers);
</script>
Array .toString()
method
The .toString() method does not change the original array but returns a string with array values separated by commas. Practice with the example below:
<script>
const students = ["Amy", "Tom", "Harry", "Laura"];
const myStudents = students.toString();
console.log(students);
console.log(myStudents);
const numbers = [0, 10, 20, 30, 40, 50];
const myNumbers = numbers.toString();
console.log(numbers);
console.log(myNumbers);
</script>
Looping Through an Array
Looping through an array in JavaScript essentially involve manipulation of the array items index numbers and the array length property. Practice with the example codes below using for
loop:
<script>
//In the examples below and in similar situations, i represents the index number of each of the elements in an array
const students = ["Amy", "Tom", "Harry", "Laura"];
for (let i = 0; i < students.length; i += 1) {
let name = students[i];
console.log(name);
}
console.log("___________________________________")// To create space
const numbers = [0, 10, 20, 30, 40, 50];
for (let i = 0; i < numbers.length; i += 1) {
let num = numbers[i];
console.log(num);
}
</script>
You can also use while
loop to loop through an array. The example code below used while
loop to loop through an array:
<script>
const students = ["Amy", "Tom", "Harry", "Laura"];
// i refers index number anywhere it is used while looping through an iterable
let i = 0;
while (i < students.length) {
name = students[i];
console.log(name);
i += 1;
}
console.log("___________________________________")// To create space
const numbers = [0, 10, 20, 30, 40, 50];
//ind refers to index number anywhere it is used while looping through an iterable
let ind = 0;
while (ind < numbers.length) {
num = numbers[ind];
console.log(num);
ind += 1;
}
</script>
Spread Operator (…)
Spread operator consist of three dots(…)
and makes it possible to expand an iterable such as an array or string into its component elements, that is, it unpacks the elements of iterable objects such as arrays, sets, and maps them into a list. This is better understood with real examples. In the example below, we used spread operator to add or insert elements of flatMates
array to students
array:
<script>
let students = ["Amy", "Tom", "Bob", "Laura"];
let flatMates = ["Andy", "Rob", "Dan"];
console.log(students); // to display students in its original form
students = ["Amy", "Tom", "Bob", "Laura", ...flatMates]; //to add elements of flatmates to students
console.log(students); // to display students after adding flatMates
</script>
What we did above will be too cumbersome in a situation where you have large number of items in student, for example 100 or more. A better approach is to use spread operator and push()
method to add flatMates
to students
as shown below:
<script>
const students = ["Amy", "Tom", "Bob", "Laura"];
const flatMates = ["Andy", "Rob", "Dan"];
console.log(students); //to display students in its original form
students.push(...flatMates); // to add elements of flatmates to students
console.log(students); //to display students after adding flatMates
</script>
Spread operator can be used to concatenate two or more arrays to form a new array as illustrated below:
<script>
const year1 = ["Amy", "Tom", "Bob", "Laura"];
const year2 = ["Andy", "Rob", "Dan"];
const year3 = ["Lee", "Ray", "Becky"];
const students = [...year1, ...year2, ...year3]
console.log(students);
</script>
Spread operator allows us to access each of the elements in an array, evaluate and or perform operations on them. Practice with the example below:
<script>
const myNumbers = [10, 20, 30, 40, 50];
let minimumNum = Math.min(myNumbers);
console.log(minimumNum); //this will return NaN or null
minimumNum = Math.min(...myNumbers); // with spread operator, we are able to access and evaluate each of the elements in the array
console.log(minimumNum); //this will return 10
</script>
Spread operator also works on strings. We can use spread operator to break a string into its component characters as shown below:
<script>
let subject = "Biology";
const subjectLetters = [...subject]; //to break the string into its component characters
console.log(subject);
console.log(subjectLetters);
//You can use .join() method to join the elements of an array together as shown below:
subject = [...subject].join(""); //use .join() method to join the letter back
console.log(subject);
//Here is another example:
const alphabets = ["A", "B", "I", "L", "I", "T", "Y"];
console.log(alphabets);
const word = alphabets.join(""); // to join the elements of alphabets to form a word
console.log(word);
</script>
The rest Parameter
A rest parameter is a parameter preceded by three dots (…)
. It enables a function to accept any number of arguments by packing them into an array. It does the opposite of spread operator. Let us practice with some examples to make it clear.
<script>
function myFruits(fruit1, fruit2) {
console.log(fruit1, fruit2);
}
myFruits("Orange", "Pears") // calling myFruit with two arguments, this is the ideal situation for myFruit function
myFruits("Orange") // calling myFruit with one argument returns undefined for the missing argument
myFruits("Orange", "Pears", "Apple") //calling myFruit with more than two arguments, the extra argument(s) will be ignored
</script>
The function myFruits
in the code example above has two parameters and therefore will work effectively with two arguments. If you call myFruits
with one argument, it will return undefined for the missing argument. If you call it with more than two arguments, JavaScript will take the first two and ignore the rest. However, we can use rest parameter (…parameter
) to enable our functions to accept any number of arguments. In the case of our example above, myFruits
will be able to accept any number of arguments as illustrated below:
<script>
function myFruits(...fruits) {
console.log(fruits);
}
//We can now call myFruits with any number of arguments depending on our need without any issue
myFruits("Orange", "Pears")
myFruits("Orange")
myFruits("Orange", "Pears", "Apple")
</script>
Here is another example that can add multiple numbers. With spread parameter, we can declare a function with capability to accept multiple numbers as arguments and sum them together:
<script>
function add(...numbers){
let sum = 0;
for (let num of numbers) {
sum += num;
}
return sum;
}
console.log(add(10, 20, 30, 40, 50));
</script>
The add()
function we defined in the example above returns just the sum of the numbers. We can make the function to display the numbers added rather than just the sum of the numbers by making the modification below:
<script>
function add(...numbers){
let sum = 0;
let numList = []; //an empty array to store the numbers supplied as arguments when the function is called
for (let num of numbers) {
sum += num;
numList.push(num) //to add each of the numbers in the argument to the numList array
}
numStr = [...numList].join("+") // this line unpacks numList using the spread operator and joins them together with plus sign in-between each numbers in the numList using join() method
return (`${numStr} = ${sum}`)
}
console.log(add(10, 20, 30, 40));
</script>
Math Properties and Methods
The code below contains examples of some Math properties and methods with explanatory comments. Your knowledge and understanding Math properties and methods will be required to solve some of the challenges you will come across in your projects. Practice with example codes, paying attention to the comments:
<script>
console.log(Math.PI);
const num = 3.875;
const myRound = Math.round(num);
console.log(`Math.round() method rounds ${num} to nearest 10 to return ${myRound}`);
const myFloor = Math.floor(num); //.floor() rounds down a given number
console.log(`Math.floor() method rounds down ${num} to return ${myFloor}`);
const myCeil = Math.ceil(num); //ceil() method rounds up a given number
console.log(`Math.ciel() method rounds up ${num} to return ${myCeil}`);
const myTrunc = Math.trunc(num); //trunc method eliminates any decimal portion of a given number
console.log(`Math.trunc method() removes the decimal portion of ${num} to return ${myTrunc}`);
const numOne = 2;
const numTwo = 3;
const myPow = Math.pow(numOne, numTwo); //Math.pow() method raises a number to the power of another. the first number that is passed in is the base
console.log(`${numOne} raised to the power of ${numTwo} returns ${myPow}`);
const mySqrt = Math.sqrt(9); //Math.sqrt() method computes the square root a given number
console.log(`The square root of 9 is ${mySqrt}`);
const mySign = Math.sign(4.5); //Math.sign() method returns whether a number is positive, negative or zero. It returns 1 for positive numbers, -1 for negative numbers and 0 for zero
console.log(mySign);
const myAbs = Math.abs(-3.445); //Math.abs() method returns the absolute value of a figure
console.log(myAbs);
const myMax = Math.max(20, 50, 30, 40); //Math.max() method returns the maximum number from a list of numbers
console.log(myMax);
const myMin = Math.min(20, 50, 30, 40); //Math.min() method returns the minimum number from a list of numbers
console.log(myMin);
const myRandom = Math.random(); // Math.random() method returns a number between 0 and 1
console.log(myRandom);
</script>
The setInterval()
Method
The setInterval()
method is used to execute a given block of code, usually a function, repeatedly at a specified time interval. The syntax for setInterval()
is as follows:
<script>
setInterval(functionName, timeInterval, parameter1, ..., parameterX);
</script>
The
functionName
is the name of the function you want to execute repeatedly. Note that you write the function name without the parenthesis. If you add the parenthesis, the function will only be executed once immediately.The
timeInterval
is the time between each execution of the function in milliseconds. Note 1second = 1000millisecondsThe
parameter1
, …,parameterX
are optional additional parameters to pass to the function
Let us take a look at an example to make this concept clearer:
<script>
function message() {
console.log("This is JavaScript tutorial by Tutorialsnote.");
}
setInterval(message, 2000);
</script>
As indicated in the general syntax, you can pass in additional arguments in the setInterval()
method where it is required by the function being repeated. In the example below, the message function requires a name
argument, this is passed in as the third argument in the setInterval()
method as shown below:
<script>
function message(name) {
console.log(`${name}! This is JavaScript tutorial by Tutorialsnote.`);
}
setInterval(message, 2000, "Amy");
</script>
The two example codes above will print "This is JavaScript tutorial by Tutorialsnote."
on the console every 2 seconds perpetually unless you close or refresh the browser. This will be useful in creating a digital clock or in displaying a text at a defined interval on the screen. But this feature might not be desirable depending on what your are doing, in that case, you might want to stop the repetition at one point. Terminating the code can be achieved with clearInterval()
method.
The clearInterval()
Method
The clearInterval()
method is used to stop the operation of setInterval()
when a specified condition evaluates to true
. Practice with the code below. In the example, we passed the message function code directly into setInterval()
method and assigned the entire code to a variable named myMessage
. In addition, we set a counter to track track the occurrence of the code execution at every interval and added a conditional statement that uses clearInterval()
method to stop the repetition after the fourth occurrence:
<script>
let counter = 0;
const myMessage = setInterval(function message() {
counter += 1;
console.log(`${counter}. This is JavaScript tutorial by Tutorialsnote.`);
if (counter === 4) {
clearInterval(myMessage);
}
}, 2000);
</script>
Here is an alternative approach for the example above:
<script>
let counter = 0;
function message() {
counter += 1;
console.log(`${counter}. This is JavaScript tutorial by Tutorialsnote.`);
if (counter === 4) {
clearInterval(myMessage);
}
}
const myMessage = setInterval(message, 2000);
</script>
The setTimeout()
Method
The setTimeout()
method is used to set a delay time in milliseconds before the execution of a specified function, setTimeout()
executes the specified function once after the specified time delay while setInterval()
executes the the specified function multiple times at specified time interval. Note that in setTimeout()
, the specified times are approximate, the specified time varies based on the workload of JavaScript runtime environment. The setTimeout()
takes minimum of two arguments, a function and the delay time. However, it can additional arguments where the specified function requires argument(s). The general syntax for setTimeout()
is similar to that of setInterval()
as shown below:
<script>
setInterval(functionName, delayTime, parameter1, ..., parameterX);
</script>
The
functionName
is the name of the function you want to execute after the specified time delay. Note that the function name is written without the parenthesis. If you add the parenthesis, the function will be executed immediately without any delay.The
delayTime
is how long you want to delay the execution of the function in milliseconds. Note 1second = 1000millisecondsThe
parameter1
, …,parameterX
are optional additional parameters to pass to the function
In the example below, the execution of the function message is delayed by 2 seconds and it is performed only once unlike the same example for setInterval()
where the execution is repeated indefinitely:
<script>
function message(name) {
console.log(`${name}! This is JavaScript tutorial by Tutorialsnote.`);
}
setTimeout(message, 2000, "Amy");
</script>
Callback Function
A callback is a function that is passed as an argument to another function for execution. The function that receive another function as argument is called the higher-order function. Here is a simple general syntax:
<script>
function higherOderFunction(callback, parameter(s)) {
//line(s) of code to be executed by the higher-order function
callback(); //to invoke the callback
}
</script>
The higherOrderFunction is the function that receive another function as an argument
The callback is the parameter that represents the callback function. Note that the callback is called without the parenthesis at its front, otherwise it will be invoked immediately
The parameter(s) are the other parameters of the higherOrderFunction if there is any
The curly brackets contains the lines of code to be executed by the higherOrdeFunction and the finally callback() (a line of code to invoke the callback function).
Let us practice with an example to make this concept clearer. Imagine we have two greetings functions, greetings1
and greetings2
. The greetings1
tells the user “Welcome User!” and the greetings2
tells the user “Goodbye User!” as shown below:
<script>
greetings1("Laura");
greetings2("Laura")
function greetings1(user){
console.log(`Welcome ${user}`);
}
function greetings2(user) {
console.log(`Goodbye ${user}`);
}
</script>
When you call greetings1
and then followed by greetings2
, they are executed in the order in which they are called. So “Welcome User!” will always come before “Goodbye User! as long as we call the functions in the right order. However, imagine a situation where greetings1
is a process that takes sometime to execute, JavaScript will not wait for greetings1
to finish execution before it moves on to greetings2
. In such a scenario, “Goodbye User” will come before “Welcome User”. We simulated this scenario below using setTimeout()
method:
<script>
greetings1("Laura");
greetings2("Laura");
function greetings1(user){
setTimeout( () => console.log(`Welcome ${user}`), 2000);
} // We used setTimeout function to delay the invocation of greetings1 by 2000 msecs (2secs)
function greetings2(user) {
console.log(`Goodbye ${user}`);
}
</script>
The situation we have above is absurd and not desirable. This kind of situation can even have a very serious consequence depending on the process involved. We can prevent the occurrence of this type of situation by using callback as illustrated below:
<script>
greetings1(greetings2, "Laura");
function greetings1(callback, user){
setTimeout( () => {console.log(`Welcome ${user}`);
callback(user)}, 2000);
} // We used setTimeout function to delay the invocation of greetings1 by 2000 msecs (2secs)
function greetings2(user) {
console.log(`Goodbye ${user}`);
}
</script>
Using the concept of callback, we made greetings2
the callback function and and greetings1
as the higher-order function. That way, we instruct JavaScrip to execute greetings2
only after the execution of greetings1
no matter how long it takes. Generally, callbacks are used to manage asynchronous processes (such as reading a file, network request or interacting with databases) where one process is required to wait for another process.
The forEach()
Method
The forEach()
is a method that is used to iterate over the elements in an array and calls a specified function (a callback function) for each elements in the array. The general syntax is as follows:
<script>
arrayName.forEach(function(currentValue, index, arr), thisValue);
</script>
arrayName
is the name of the array we want to iterate of its elementsfunction()
is the function that we intend to run for each of the elements in the array. It is required.currentValue
is the value of the current element. It is requiredindex
is the index number of the current element, it is optionalarr
is the array of the current elementthisValue
is a value passed to the function as itsthis
value. It is optional and by default it returns undefined.
Let us practice with the code below:
<script>
const numbers = [10, 20, 30, 40, 50];
function listItems(item) {
console.log(item);
}
numbers.forEach(listItems);
</script>
We can create another function to perform another operations on the array items before listing them on the console. Let us for example create a function to double each of the items in the array before listing them on the console:
<script>
const numbers = [10, 20, 30, 40, 50];
function listItems(item) {
console.log(item);
}
function doubleItems(item, index, array) {
array[index] = item * 2;
}
numbers.forEach(doubleItems);
numbers.forEach(listItems);
</script>
Instead of having two separates callback functions as we did above, we can create a callback function that doubles and display each of the item in the array as shown below:
<script>
const numbers = [10, 20, 30, 40, 50];
function listDoubleItems(item) {
console.log(item * 2);
}
numbers.forEach(listDoubleItems);
</script>
The innerHTML
Property
The innerHTML
property is used to return or read all the the HTML content of an element or set the HTML content of an element. In the code below we used innerHTML
to read the content of a <div>
element, it returns everything inside the <div>
elements including HTML tags and comments:
<body>
<div id="test">
<h3>The innerHTML example!</h3>
<p>This is a demo of innerHTML property</p>
<p style="display:none">This is an hidden text</p>
<!-- This is a comment -->
</div>
<script>
let message = document.getElementById("test");
console.log(message.innerHTML);
</script>
</body>
In the code below, we used innerHTML
to set or modify the content of the <div>
element:
<body>
<div id="test">
<h3>The innerHTML example!</h3>
<p>This is a demo of innerHTML property</p>
<p style="display:none">This is an hidden text</p>
<!-- This is a comment -->
</div>
<script>
let message = document.getElementById("test");
message.innerHTML = "This is innerHTML example. Hello world!"
console.log(message.innerHTML);
</script>
</body>
The textContent
Property
The textContent
property of a node (an HTML element) returns the concatenation of the textContent
of every child node, except comments and processing instructions. Practice with the example below:
<body>
<div id="test">
<h3>The textContent example!</h3>
<p>This is a demo of textContent property</p>
<p style="display:none">This is an hidden text</p>
<!-- This is a comment -->
</div>
<script>
let message = document.getElementById("test");
console.log(message.textContent);
</script>
</body>
In addition to reading the text content of a node, the textContent property can also be used to set the text content of a node as illustrated below:
<body>
<div id="test">
<h3>The textContent example!</h3>
<p>This is a demo of textContent property.</p>
<p style="display:none">This is an hidden text</p>
<!-- This is a comment -->
</div>
<script>
let message = document.getElementById("test");
message.textContent = "Setting a new content for the node is the new message."
console.log(message.textContent);
</script>
</body>
The innerText
Property
Unlike the textContent
property, the innerText
takes CSS into account and only displays human readable text on the console as demonstrated in the example code below:
<body>
<div id="test">
<h3>The innerText example!</h3>
<p>This is a demo of innerText property</p>
<p style="display:none">This is an hidden text</p>
<!-- This is a comment -->
</div>
<script>
let message = document.getElementById("test");
console.log(message.innerText);
</script>
</body>
Project - Calculator App
Let us wrap up this tutorial with a calculator app. Knowledge of HTML and CSS is required for this project. If you have not learnt HTML and CSS before or you need a quick HTML and CSS refresher, we recommend you take our free HTML and CSS Made Easy Part One and Part Two tutorials. The sample solution we provided for this project is designed to apply as many JavaScript concepts you have learnt so far as possible. Also, we introduce you to storing of JavaScript code in a separate file.
To derive the best learning benefits from this project, we advise that you do the following: 1. read through the example solution below on an IDE and run it to see how it works; 2. attempt to create your own, possibly with modifications; 3. use the example solution as a reference when you don’t know what to do.
To simplify the learning process, we break the project down into three parts, HTML, CSS and JavaScript. Please pay attention to the comments in the sample solution.
The HTML part, this is where the structure of the calculator app is designed and built. In the sample solution below, we created an HTML file named calculator.html and link the CSS and JavaScript files to it. Then we designed the structure of the app.
To link a JavaScript file to an HTML file, go to the last line within the <body>
section of the HTML file, add your <script>
tag and insert the JavaScript file name in the opening tag as illustrated in the general syntax below:
<script src="JavaScriptFileName.js"></script>
For better understanding of how to link JavaScript file to an HTML file, see how the JavaScript file for this project (calculator.js) is linked to the HTML file in the calculator.html file below, the line was made bold to make it easy for you to identify:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator</title>
<link rel="stylesheet" href="calculator.css"> <!--To link the CSS file to the HTML-->
</head>
<body>
<div id="container">
<div id="inputbox">
<div id="display1"></div>
<div id="display2"></div>
<input id="display3" readonly value="0">
</div>
<div id="btns">
<button id="clear" onclick="clearInput('C')" class="specbtn" >C</button>
<button id="del" onclick="deleteItem('del')" class="specbtn" >del</button>
<button id="percent" onclick="percent('%')" class="specbtn">%</button>
<button id="division" onclick="operator('÷')" class="specbtn">÷</button>
<button id="seven" onclick="keyDisplay('7')">7</button>
<button id="eight" onclick="keyDisplay('8')">8</button>
<button id="nine" onclick="keyDisplay('9')">9</button>
<button id="times" onclick="operator('x')" class="specbtn">×</button>
<button id="four" onclick="keyDisplay('4')">4</button>
<button id="five" onclick="keyDisplay('5')">5</button>
<button id="six" onclick="keyDisplay('6')">6</button>
<button id="minus" onclick="operator('-')" class="specbtn">-</button>
<button id="one" onclick="keyDisplay('1')">1</button>
<button id="two" onclick="keyDisplay('2')">2</button>
<button id="three" onclick="keyDisplay('3')">3</button>
<button id="plus" onclick="operator('+')" class="specbtn">+</button>
<button id="zero" onclick="keyDisplay('0')">0</button>
<button id="dot" onclick="decimal('.')">.</button>
<button id="equal" onclick="compute()" class="specbtn">=</button>
</div>
</div>
<script src="calculator.js"></script> <!--To link the JavaScript file to the HTML-->
</body>
</html>
The CSS part - When you run the code above, the calculator app appears on the browser looking disorganised and unappealing. Here, we used CSS to make the app nice looking but lifeless, nothing happens when you click on the buttons. To achive this, we created the CSS file named calculator.css, linked it to calculator.html file by inserting <link rel="stylesheet" href="calculator.css">
into the <head>
section and wrote our CSS codes as shown below:
body{
margin-top: 10;
display: flex;
justify-content: center;
background-color: hsl(0, 0%, 95%);
}
#container{
font-family: Arial;
background-color: hsl(0, 0%, 15%);
border-radius: 20px;
max-width: 450px;
overflow: hidden;
}
#display1, #display2, #display3{
width: 95%;
padding: 10px;
font-size: 3rem;
text-align: right;
border: none;
background-color: hsl(0, 0%, 25%);
color: white
}
#btns{
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
padding: 25px;
}
button{
width: 100%;
height: 100%;
border-radius: 25px;
border: none;
background-color: hsl(0, 0%, 30%);
color: white;
font-size: 3rem;
font-weight: bold;
cursor: pointer;
}
button:hover{
background-color: hsl(0, 0%, 40%);
}
button:active{
background-color: hsl(0, 0%, 60%);
}
#equal{
width: 210%
}
.specbtn{
background-color: tomato;
}
At this point you have a nice looking calculator but lifeless!
The JavaScript part - JavaScript is used to build the app’s functionalities and hence transform our lifeless calculator app above to a lively and functioning calculator. Here, we created a JavaScript file named calculator.js to store our JavaScript codes and linked it to calculator.html by inserting <script src="calculator.js"></script>
into the lowest point within the <body>
section. Please pay attention to the comments in the example solution below:
/*Create variables that give you access to the relevant HTML elements. Recall DOM in part one
Refer to the calculator.html file to see the HTML elements and their Ids.*/
const firstDisplay = document.getElementById("display1");
const secondDisplay = document.getElementById("display3");
let operatorDisplay = document.getElementById("display2")
//Create a function to manage the display of the buttons, except some special buttons
function keyDisplay(keyValue) {
if (secondDisplay.value === "0") {
secondDisplay.value = keyValue;
}
else {
secondDisplay.value += keyValue;
}
}
//Create a function to manage All Clear (AC) button
function clearInput() {
secondDisplay.value = "0";
firstDisplay.innerText = "";
operatorDisplay.innerText = "";
}
//Create a function to manage delete (del) button
function deleteItem() {
if (secondDisplay.value === "0") {
secondDisplay.value = "0"
}
else {
secondDisplay.value = secondDisplay.value.toString().slice(0, -1);
}
}
/*Create a function to manage decimal (.) button. This is necessary to prevent
having multiple decimal input and hence complication in the computation.
When the decimal key is pressed, this function checks if the inpout already has
(includes) a decimal and just return without adding a decimal. When you follow a conditional statement with return keyword, you instruct JavaScript to do nothing if the condition is true */
function decimal(keyValue) {
if (secondDisplay.value.includes(".")) {
return;
}
else if (secondDisplay.value === "") {
secondDisplay.value = "0" + keyValue;
}
else {
secondDisplay.value += keyValue;
}
}
//Create a function to manage the % button
function percent(keyValue) {
if (firstDisplay.innerText === "") {
firstDisplay.innerText = secondDisplay.value/100;
secondDisplay.value = "";
}
else if (firstDisplay.innerText !== "" &&
operatorDisplay.innerText !== "" &&
secondDisplay.value !== "") {
secondDisplay.value /= 100;
}
else {
return
}
}
//Create a function to manage operator buttons
function operator(keyValue) {
if (secondDisplay.value !== "") {
compute();
firstDisplay.innerText = secondDisplay.value;
operatorDisplay.innerText = keyValue;
secondDisplay.value = "";
}
else if (operatorDisplay.innerText === "" && secondDisplay.value === "") {
operatorDisplay.innerText = keyValue;
}
else if (operatorDisplay.innerText !== "" && secondDisplay.value === "") {
operatorDisplay.innerText = keyValue;
}
else {
return;
}
}
//Create a function to handle computation. We used switch statement but it can also be done with if statement
function compute () {
let result;
let operator = operatorDisplay.innerText;
const firstNum = parseFloat(firstDisplay.innerText); //To convert first operand to number
const secondNum = parseFloat(secondDisplay.value); //To convert second operand to number
if (isNaN(firstNum) || isNaN(secondNum)) {return;}
switch (operator) {
case "%":
result = firstNum/100;
break;
case "÷":
result = firstNum/secondNum;
break;
case "x":
result = firstNum * secondNum;
break;
case "-":
result = firstNum - secondNum;
break;
case "+":
result = firstNum + secondNum;
break;
default:
return;
}
firstDisplay.innerText = "";
secondDisplay.value = result;
operatorDisplay.innerText = "";
}
Conclusion
We are grateful to you for staying with us to the end of this tutorial. Hopefully you enjoyed and found the its content useful and helpful. We shall discuss more JavaScript concepts in Part Three of this tutorial, please watch out for it. If you will like to receive more of our posts, please subscribe to Tutorialsnote in the section below. Also, kindly help us to share Tutorialsnote with your families, friends, and colleagues using the share button below. Thank you.