Introduction
JavaScript is a popular easy to learn web programming language. JavaScript is used to build frontend dynamic and interactive web pages. It is a lightweight cross platform language.
This tutorial assumes zero prior knowledge of JavaScript. However, if you do not have prior basic knowledge of HTML, we recommend you go through our HTML and CSS Made Easy - Part One to have some knowledge of HTML. This is very crucial for you to easily comprehend the content of this tutorial.
We shall start by introducing you to JavaScript concepts and then conclude with 3 projects where you will apply the concept to create practical apps.
We are going to use Scrimba Integrated Development Environment (IDE) for writing and demonstrating example codes, it is a web based IDE. When you open the IDE by clicking on the link above, the page below will open. If the console window at the lower part is not showing, click on the console button on the screen. Note that you can also use any other IDE such as VS code
Now, you are ready to start coding in JavaScript. But before you start coding, let us briefly discuss console.log()
, it is one of the methods you will use regularly as a JavaScript developer.
console.log( )
console.log()
is a method in JavaScript. It is used to test and display the output of your code in the console. If the code is syntactically correct, console.log()
will display the output of the code. Otherwise, JavaScript will display error message for you on the console. We are going to use console.log()
a lot during this tutorial.
How to Enhance your Understanding
We shall provide you with example codes to explain JavaScript concepts. In order to enhance your understanding and retention of the concepts, we strongly advice that you follow the rules below:
Do not copy and paste the example codes into your IDE to practice. Instead, type them inside your IDE. Typing the code rather than copying and pasting into your IDE will significantly enhance your learning and understanding. Hence, we recommend that you should type all the example codes in this tutorial. Typing the example codes develops and strengthens your programming muscle.
In addition to the sample codes we provide for you to practice, you should always come up and practice with your own version of codes. Coding is better learnt by practice
Now, let us start coding in JavaScript!
Your First JavaScript Code
Let us start by writing and storing JavaScript inside the HTML file, we shall learn the other approach of writing and storing JavaScript in a separate file later. To store JavaScript in an HTML file, you need to insert <script>
tag into the file. Then, you can write your JavaScript codes inside the <script>
tag. On the Scrimba IDE, you have two files already created for you: the index.html and index.js.
Now, go to the body section of index.html file, change Hello World
to: This is JavaScript Tutorial by Tutorialsnote
or any other statement of your choice.
Then, insert <script> </script>
just before the closing </body> tag and type alert(‘Hello World!’)
inside the <script>
tag as shown below:
<body>
This is JavaScript Tutorial by Tutorialsnote
<script>
alert('Hello World!');
</script>
</body>
Finally, click on the green RUN button on the top right hand corner of the IDE. You should have the alert shown in the screenshot below:
When you close the popup alert, you will have the webpage preview window updated and display the screen below:
Important Things to Note in JavaScript Programming
Before we proceed further, please take note of the following:
JavaScript statements are lines of code written to provide instruction to the computer
JavaScript statements are usually grouped together in code blocks by enclosing them in curly brackets
{…}
. Code blocks enable programmers to define statements which are meant to be executed together.It is customary and best practice to terminate lines of code with semicolon “;” in JavaScript
JavaScript lines of code are executed serially in the same order as they are written. Try the lines of code below. When you run the code you will see the output of each line of code in the console arranged in the order they were written
<body> This is JavaScript Tutorial <script> console.log('Michael'); console.log(20 - 5); console.log(13 + 17); console.log(typeof 13); console.log(typeof 'John'); console.log('I am learning JavaScript'); </script> </body>
JavaScript is case sensitive,
name
is not the same asName
, similarlyAge
is not the same asage
in JavascriptIn JavaScript, multiple spaces (whitespaces) are ignored. For example, when you run the code below, the output in the console does not include the wide gap between am and learning:
<body> This is JavaScript Tutorial <script> console.log('I am learning JavaScript'); </script> </body>
JavaScript Keywords or Reserved characters - Keywords are reserved words which cannot be used as names for variables or functions declared by the programmer. Some of the keywords include but not limited to:
var
,let
,const
,if
,function
,else
,do
,while
,for
,this
,case
,in
,true
,false
,class
,try
,catch
,finally, default
etc. You don’t have to memorise them, you will get to know them as you learn and become fluent in JavaScript. If you attempt to use any of them inappropriately, JavaScript will throw out error message
Comments in JavaScript
A comment is a single or multiple non-executable statements which give more information about the code. Comment can also be used to disable a line or multiple lines of code to make JavaScript ignore them.
Single Line Comment
This is achieved by starting the line with double slashes “//”. When you try the example below, you will notice that all the lines of code starting with “//” will not be logged on the console:
<body> This is JavaScript Tutorial <script> //console.log('Hello World!'); console.log('Michael'); console.log(20 - 5); //console.log(13 + 17); console.log(typeof 13); console.log(typeof 'John'); //console.log('I am learning JavaScript'); </script> </body>
Delete the
//
preceding any of or all of the lines which were commented out and run the program again to see the impact on the output in the console.Multi-Line Comment
This is achieved by starting the first line of statements with “
/*
” and ending the last line with “*/
”. Try the example below, you will notice that all the lines of code wrapped between/* */
will be ignored and will not be logged on the console:<body> <script> /*these are comments alert('Hello World!') console.log('Michael'); console.log(20 - 5); console.log(13 + 17);*/ alert('Welcome to Tutorialsnote!') console.log(typeof 13); console.log(typeof 'John'); console.log('I am learning JavaScript'); </script> </body
JavaScript Variables
In programming, variables are means of storing data or information. Just think of it this way, a variable is like a box for storing data, while the variable name is the box label that gives you an idea of what is inside the box. In JavaScript, a variable usually has three components, namely: the keyword, the variable name (label), the assignment operator =
and the variable value. The general syntax for a variable is as follows:
keyword variableName = variableValue
Variable Keywords
Variables can be declared (created) with any of the following keywords: var
, let
and const
var
Keyword - This is outdated. You should only use var
if you want your program to be compatible with browsers which are older than 2015. Practice using var
with the examples below:
<body>
<script>
var myName = 'Michael';
var myNumber = 7;
var mySum = 5 + 3;
var mySentence = 'Tom is a boy'
console.log(myName);
console.log(myNumber);
console.log(mySentence)
</script>
</body>
let
Keyword - You should only use let
keyword where it is okay for the variable value to change or where you are going to reassign value to the variable name later. Practice using let
keyword with the examples below:
<body>
<script>
let myName = 'Michael';
let myNumber = 7;
let mySum = 5 + 3;
let mySentence = 'Tom is a boy'
console.log(myName);
console.log(myNumber);
console.log(mySentence)
</script>
</body>
Note:
let
allows reassignment of new values to variable. Practice with the examples below:
<body>
<script>
let myName = 'Michael';
let myNumber = 7;
let mySentence = 'Tom is a boy'
console.log(myName);
console.log(myNumber);
console.log(mySentence)
//Second part: let's reassign new values to the variables
myName = 'Grace';
myNumber = 14;
mySentence = 'Laura is a girl'
console.log(myName);
console.log(myNumber);
console.log(mySentence)
</script>
</body>
const
keyword - Always use const
keyword by default when declaring variables. As a general rule, only use let
where using const
is not possible. Practice using const
with the examples below:
<body>
<script>
const myName = 'Michael';
const myNumber = 7;
const mySum = 5 + 3;
const mySentence = 'Tom is a boy'
console.log(myName);
console.log(myNumber);
console.log(mySentence)
</script>
</body>
Note:
const
does not allow reassignment of new values to variables.const
makes the variable readonly. What we did withlet
above will not work withconst
. If you try the code below, the second part of the code will not run, you will get error message:
<body>
<script>
const myName = 'Michael';
const myNumber = 7;
const mySentence = 'Tom is a boy'
console.log(myName);
console.log(myNumber);
console.log(mySentence)
//Second part: let's reassign new values to the variables
myName = 'Grace';
myNumber = 14;
mySentence = 'Laura is a girl'
console.log(myName);
console.log(myNumber);
console.log(mySentence)
</script>
</body>
Variables Name
Variables in JavaScript must be identified with a unique name. In naming your variables, you should adhere to the following rules:
Though JavaScript allows the use of single alphabets such as a, b, x or y as variables name, it is strongly advised that you give more meaningful names such as age, distance, price etc to your variable. Don’t forget that the variable’s name is it’s label that is supposed to provide an idea of what the variable (the box) contains, using x, y or z will not serve this purpose.
Names must start with an alphabet not with a number. If you attempt to declare variables starting the name with a number, you will get an error message.
Names can also start with $ and _.
Names can have letters, digits, underscores, and dollar signs
Names are case sensitive. For example, const price = 5 and const Price = 5 are two different variables. Practice with the examples below:
<body> <script> const price = 5; const Price = 5; //if you change the upper case P on this line to lower case, you will get an error message console.log(price) console.log(Price) </script> </body>
JavaScript keywords cannot be used as variables names.
Where you have a compound name, use camel case. E.g firstName, lastName, fruitPrice etc
Assignment Operator
In most programming languages, including JavaScript, the equal sign =
acts as an assignment operator, it does not act as equal to operator as it does in Algebra. In JavaScript, the equal to operator is double equal or triple equal sign ==
or ===
JavaScript Data Types
JavaScript has the following five basic types of data: strings, numbers, booleans, undefined and null. Let us discuss them one by one.
JavaScript Strings
In JavaScript, strings are texts or character(s) enclosed in a single or double quotation marks. Even when you enclose a number inside a double or single quote, the number automatically becomes a string. Try example lines of code below:
<body>
<script>
console.log('Michael');
console.log(typeof 'Michael');
console.log('Tutorialsnote is cool');
console.log(typeof 'Tutorialsnote is cool');
console.log('15');
console.log(typeof'15');
console.log(15)
console.log(typeof 15);
</script>
</body>
Note:
typeof
is an operator in JavaScript that is used to display the data type of a variable
When you run the code above, you will have the following except the comments displayed on the console
CONSOLE
›Michael
›string // it shows that 'Michael' is a string
›Tutorialsnote is cool
›string // it shows that 'Tutorialsnote is cool' is a string
›15
›string // it shows that '15' is a string and not a number
›15
›number // it shows that 15 without the quote is a number
Note:
Though you can use double or singe quote, whenever you have quote(s) inside a string, you need to ensure that the string is enclosed in type of quote that does not match the quote(s) inside the string.
For example, if you attempt to run the line of code below you will get error message in the console:
<body>
<script>
console.log('We're learning JavaScript');
</script>
</body>
To eliminate the error message you need to modify the code by enclosing the sentence in a double quote so that the external quotes do not match the single quote inside the string as as shown below:
<body>
<script>
console.log("We're learning JavaScript");
</script>
</body>
Alternatively, the issue of matching quote can be addressed by the use of escape character (backslash “\
”). For example we can correct the error message above with the use of “\
” instead of using double quote “ ”. Try the code below:
<body>
<script>
console.log('We\'re learning JavaScript');
</script>
</body>
Where your string contains “\”, use double “\\
” to create single “\” and differentiate it from the escape character. When you try the example below you will notice that the “\\
” will only return single “\” in the console:
<body>
<script>
console.log('We\'re learning JavaScript. We were told to save our files here: C:\\Program Files\\JavaScript');
</script>
</body>
Managing Long String Length
For the sake of readability, it is a good practice to avoid code lines longer than 80 characters. Plus sign “+
” can be used where you need to break a long string inside a line of code. Try the example below:
<body>
<script>
console.log('We\'re learning JavaScript.'+ ' '
+ 'We were told to save our files here:'+ ' '
+ 'C:\\Program Files\\JavaScript');
</script>
</body>
Note:
The
+
and the empty strings' '
at the end of first and second lines were introduced to create space, if you remove them, the code will still run successfully but the lines will be joined at those point without any space and the sentence will look untidy.
Combining Strings and Variables Values
There will be instances where you will need to bring in variable values into your string. A good use case is when you are working on an app that displays customised massage(s) to the user. You can accomplish this using addition “+” operator to join the variable to a body of strings. Practice with the code below:
<body>
<script>
const name = 'Daniel';
const age = 17;
const address = '77, Parkway Road.';
console.log("Hello " + name + "! You're " + age + " years old, you live at " + address);
/*The rules you must follow are:
1. Enclose your strings in double or single quote
2. Use + sign at every joint between strings and variables
3. Introduce necessary space as the first or the last character in the string*/
</script>
</body>
Note that you can store the entire message in a variable as shown below to make your code better organised and easier to maintained:
<body>
<script>
const name = 'Daniel';
const age = 17;
const address = '77, Parkway Road.';
const message = "Hello " + name + "! You're " + age + " years old, you live at " + address
console.log(message);
</script>
</body>
Manipulating String in JavaScript
JavaScript has a number of inbuilt features which can be used to manipulate strings in programming. Let us discuss some of these features:
String Indexing
Characters in strings have index numbers. The index numbering starts from zero, so the first value has index number zero and second value has index number 1 etc. We can access any of the characters in a string with their index numbers. Practice with the example below:
<body>
<script>
const myFruit = 'Orange';
console.log(myFruit[0]);
console.log(myFruit[1]);
console.log(myFruit[2]);
console.log(myFruit[3]);
console.log(myFruit[4]);
console.log(myFruit[5]);
//you can apply the indexing directly on the string as shown below
console.log('Orange'[3]);
</script>
</body>
String Length
You can get the length of a string with the JavaScript inbuilt .length
property. Try the examples below:
<body>
<script>
console.log('Character'.length);
console.log('Canada'.length);
console.log("We're learning JavaScript".length); //**This is the third line of code
//length property also works with variables. If we store the strings above in variables as shown below, we'll still achieve the same result.
const myWord = 'Character';
console.log(myWord.length);
const myCountry = 'Canada';
console.log(myCountry.length);
const mySentence = "We're learning JavaScript";
console.log(mySentence.length);
</script>
</body>
Note:
.length property counts the number of character in a string, including the spaces between the words. That is why the **third line of code returned 25 when it was executed
slice( )
slice()
is used to extract and return part of a string as a new string. slice()
method takes two parameters, the starting index number and the ending index number. slice()
excludes the value for the ending index number in the output. It has a general syntax like this:
slice(starting index no, ending index no)
Try the example below for better clarity. Play around by changing the index numbers or even your own example to enhance your understanding:
<body>
This is JavaScript Tutorial by Tutorialsnote
<script>
const myWord = 'Tutorialsnote';
console.log(myWord.slice(1, 7));
const myText = 'Hello world';
console.log(myText.slice(2, 10));
const myFruits = 'Apple, Avocado, Banana, Orange';
console.log(myFruits.slice(0, 13));
//If you omit the second parameter slice() will return all the characters from the starting index to the end e.g
console.log(myWord.slice(9));
//If you want to slice from the end of the string, use negative index number e.g
console.log(myText.slice(-5));
console.log(myFruits.slice(-14, -8));
</script>
</body>
replace( )
The replace()
method is used to substitute a given value for another specified value in a string to produce a new string. The general syntax is as follows:
replace(valueToBeReplaced, replacementValue)
Try the examples below for better understanding:
<body>
This is JavaScript Tutorial by Tutorialsnote
<script>
const myText = 'I am going to the Cinema.'
console.log(myText.replace('Cinema', 'Mall'))
</script>
</body>
Note:
replace()
method only replaces the first match in the string. Try the code below, you will notice that the second Cinema was ignored:
<body>
This is JavaScript Tutorial by Tutorialsnote
<script>
const myText = 'I am going to the Cinema. I saw Tom at the Cinema last week'
console.log(myText.replace('Cinema', 'Mall'))
</script>
</body>
If you want
replace()
method to replace all the matches, you will need to use regular expression/g
as demonstrated in the code below. Try it in your IDE to see how it works:
<body>
This is JavaScript Tutorial by Tutorialsnote
<script>
const myText = 'I am going to the Cinema. I saw Tom at the Cinema last week'
console.log(myText.replace(/Cinema/g, 'Mall'))
</script>
</body>
Recall we mentioned earlier that JavaScript is case sensitive. If you type cinema or CINEMA in the code above, none of the Cinemas in the string will be replaced with Mall. Try it on the IDE to see how this scenario is treated by JavaScript.
If you want
replace()
method to ignore the case and become case insensitive, you need to use the regular expression/i
. shown below:
<body>
This is JavaScript Tutorial by Tutorialsnote
<script>
const myText = 'I am going to the Cinema. I saw Tom at the Cinema last week';
console.log(myText.replace(/cinema/i, 'Mall'));
console.log(myText.replace(/CINEMA/i, 'Megamall'));
</script>
</body>
toUpperCase( )
toUpperCase()
method is used to convert strings to upper case. Try the example below:
<body>
<script>
const myText = 'Tutorialsnote';
console.log(myText.toUpperCase());
const myName = 'thompson';
console.log(myName.toUpperCase());
</script>
</body>
toLowerCase( )
toLowerCase()
method is used to convert strings to lower case. Try the example below:
<body>
<script>
const myText = 'HOUSE';
console.log(myText.toLowerCase());
const myName = 'CLARA';
console.log(myName.toLowerCase());
</script>
</body>
JavaScript Numbers
In JavaScript you can write number with or without decimals. JavaScript treats all number the same. Unlike some programming languages, for example Python, JavaScript does not apply discriminatory treatment to numbers based on whether they have decimals or not. You can perform different types of arithmetic operation on number in JavaScript. See below the common arithmetic operators in JavaScript and what they do:
Addition “
+
” is used for adding numbers. Try the code below:
<body>
<script>
console.log(5 + 5);
</script>
</body>
Subtraction “
-
” is used for subtracting numbers. The number on the right side of the expression is taken away from the one on the left. In the examples below, 3 is taken away from 5 in the first line of code while 5 is taken away from 3 in the second line of code
<body>
<script>
console.log(5 - 3); // the answer is 2
console.log(3 - 5); // the answer is -2
</script>
</body>
Multiplication “
*
” is used for evaluating multiples of numbers. Try the code below:
<body>
<script>
console.log(5 * 3);
</script>
</body>
Division “
/
” is used to divide the number on the left side of an expression by the one on the right side, note this is similar to subtraction rule. Try the examples below on your IDE:
<body>
<script>
console.log(10 / 5); // the answer is 2
console.log(5 / 10); // the answer is 0.5
</script>
</body>
Exponent “
**
” is used to compute the the value of a number raised to the power of another. That is multiply a number by itself a number of times. For example, a * a * a is expressed as a ** 3. (a raised to the power of 3). Try the examples below on your IDE:
<body>
<script>
console.log(2 ** 3); // 2 raised to the power of 3
console.log(6 ** 2); // 6 raised to the power of 2
</script>
</body>
Reminder “
%
” is used to compute the remainder after the left number in an expression is divided by the right number. Try the examples below on your IDE:
<body>
<script>
console.log(8 % 3);
console.log(9 % 4);
console.log(4 % 2);
</script>
</body>
JavaScript can also solve arithmetic expression with multiple operators. Let us use example below to practice and learn:
<body>
<script>
console.log(5 + 5 * 3); // Work out the answer for this line before running the code
</script>
</body>
We requested that you should work out the answer before running code above, if your answer was 30, you would have been wrong! This takes us to a concept called order of operations.
Order of Operations
Order of operations is simply how JavaScript gives priority to operators in an arithmetic operation, it is also referred to as Operator Precedence. JavaScript follows the order below in assigning priority to operators in an operation:
Parentheses => Exponents => Multiplication/Division => Addition/Subtraction
It means values inside parenthesis will be evaluated first, then follow by exponents, then multiplication or division and lastly addition or subtraction irrespective of their position in the operation. Practice with the example below:
<body>
<script>
console.log(20 - 4**2 + 2 * 5 +(5-3)) // Work out the answer to this operation before running the code
</script>
</body>
Did you attempt to work out the answer before running the code? If you did not get the answer right, here is how JavaScript evaluated the expression to get 16, the correct answer:
(5-3) was evaluated first because it was inside parenthesis at this point the output of the evaluation which was 2 was kept on hold and the expression was reduced to:
console.log(20 - 4**2 + 2 * 5 + 2)
4**2 was then evaluated. 16, the output of this evaluation was also kept on hold and the expression was reduced to:
console.log(20 - 16 + 2 * 5 + 2)
2 * 5 was then evaluated to get 10 and the expression was reduced to:
console.log(20 - 16 + 10 + 2)
At this point, we were left with only addition and subtraction, both of which have the same order of precedence. Hence, the final evaluation can be performed in any order of your choice to arrive at the final answer, which is 16
Note:
You can control or manipulate the order of operations by using parenthesis. Practice with the examples below:
<body>
<script>
console.log(8 + 2 * (7 - 3));
console.log((8 + 2) * 7 - 3);
</script>
</body>
Arithmetic Operations on Variable Values
You can also perform arithmetic operations on values stored inside variables. The same order of operations applies when performing arithmetic operations on value stored inside variables, including using parenthesis to control the order of operations. Practice with the examples below:
<body>
<script>
const myNum1 = 5;
const myNum2 = 4;
const myNum3 = 3;
const myNum4 = 2;
console.log(myNum1 + myNum2 * myNum3 / myNum4);
console.log((myNum1 + myNum2) * myNum3 / myNum4);
</script>
</body>
Adding numbers and strings
When you add a string to another string, JavaScript concatenate them. So, when you add a number to a string, since numbers cannot be arithmetically added to strings, JavaScript treats the number as a string and concatenate it to the string. Practice with the codes below. The comments in the code below are for explanatory purpose, you don’t have to include them while practicing the code:
<body>
<script>
console.log(8 + 2 + '3');
// the first two numbers added and concatenated to string 3
console.log(8 + 2 + '3' + 4);
// the first two numbers added, concatenated to string 3, number 4 converted by JavaScript to a string and got concatenated to string 103
console.log(8 + 2 + 'boys ' + 'are in the hostel');
// the first two numbers added, concatenated to the string 'boys' and then to the string 'are in the hostel'
console.log(8 + '2' + 'boys ' + 'are in the hostel');
// the first number was converted to a string and concatenated to the string 'boys' and then to the string 'are in the hostel'
</script>
</body>
Note:
Addition “
+
” operations of numbers before the first string in the expression (moving from left to right) will still be evaluated normally as numbers. However, immediately after the first string is encountered, JavaScript treats every other values as strings and just concatenate them.
Booleans
Booleans are data type whose value can only be either true or false. They are use to denote whether a condition is true or false. Booleans are very important part of conditional statements. This will be clearer when we are discussing if statements. Booleans data type are usually constructed with comparison operators such as :
greater than >
less than <
greater than or equal to >=
less than or equal to <=
equal to === or == be careful with the use of ==, it converts data types before comparison
not equal to !==
Note:
In the order of operation, comparison operators has lower priority than math operators (*, /, +, -, and parenthesis)
Practice with codes below to have a better understanding of booleans:
<body>
<script>
console.log(3 > 9)
console.log(3 < 9)
console.log('a' == 'b')
console.log('a' !== 'b')
console.log(true == false)
console.log('a' == 'a')
console.log(7 == '12')
console.log(7 == '7')
console.log(7 === '7')
</script>
</body>
Note:
Double equal sign
==
does what is called type coercion before checking for equality. That is, JavaScript converts the types of the two values to be the same type before performing equality test. That is why comparison of number 7 and string ‘7’ returns true when double equal sign was used.console.log(7 == '7')
returnstrue
. To avoid this kind of unintended outcome, it is advisable to use triple equal===
Undefined
The undefined data type means that the variable has been declared, but has not yet been assigned a value. Practice with the code below:
<body>
<script>
let name; //this line of code declares a variable called name but without any value assigned to it
console.log(name); // this will return undefined because no value has been assigned to the variable
name = 'Michael'; // to assign value to the variable called name
console.log(name); // this will return Michael
</script>
</body>
Null
Null means empty or nothing, but it’s that way because it has been deliberately been set to be empty or nothing. Note that null value is not the same as undefined. Null indicates that a value has been assigned to the variable, even though it is an empty value. Whereas, in the case of undefined, no value has been assigned. Practice with the example below:
<body>
<script>
let name = null
console.log(name);
name = 'Michael';
console.log(name);
console.log(null === undefined) // this returns false in the console, confirming that null is not the same as undefined
</script>
</body>
Conditional Statements
Conditional statements are formed with combination of boolean data type and if
statements. Conditional statements make it possible for us to write programs that enable computer to make decision without human intervention on what course of action to take based on predefined conditions. The general syntax in it’s simplest form for a conditional statement is:
if (boolean or a condition that result in a boolean value) {
the code to be executed if the condition is true;
} else{
the code to be executed if the condition is false;
}
The else
keyword tells the computer to run the second line of code if the condition is false. To make the concept clearer, let us go to our IDE to practice with some real code:
<body>
<script>
if (true) {
console.log("You're right!");
} else{
console.log("You're wrong!");
}
</script>
</body>
If you run the code above, You’re right! will be displayed in the console. If you change the condition to false
or !true
(not true) and you run the code again, You’re wrong! will be displayed in the console.
Now, let us do something more practical. We are going to write a code to determine if someone is old enough to vote in a country where the minimum voting age is 18 years:
<body>
<script>
let age = 19
if (age >= 18) {
console.log('Congratulations! You\'re eligible to vote!!');
} else {
console.log('Sorry. You\'re not eligible to vote!');
}
</script>
</body>
If you run the code above as is, Congratulations! You're old enough to vote!! will be displayed in the console. Try changing the value of age variable from 19 to different values and rerun the code to see the different outcome.
You can run if statement with multiple condition with the use of else if
. Let us practice this by introducing another condition to cater for people who are not old enough now but will be eligible to vote in the next election period:
<body>
<script>
let age = 16
if (age >= 18) {
console.log('Congratulations! You\'re eligible to vote!!');
} else if (age >= 14) {
console.log('Don\'t worry! You\'ll be able to vote next elections');
} else {
console.log('Sorry. You\'re not eligible to vote!');
}
</script>
</body>
Note that you can add as many else if
as required in your code.
Functions
A function is a block of code that is designed to perform a specific task when it is called (invoked or triggered). In JavaScript, a function is declared (created) with the keyword function
followed by the function name
and then by parentheses ()
and finally by two curly brackets {}
. The parentheses contains the parameters if there’s any and the curly brackets contains the lines of code to be executed when the function is called. Functions make code reusability possible. The general syntax for function is as shown below:
function functionName(parameter1, parameter2,...parameterX) {
line(s) of code the be executed
}
The rules for naming functions are the same as those earlier highlighted for variables naming. Let us practice function with a real code:
<body>
<script>
function myProduct() {
return(console.log(5 * 7));
}
myProduct()
</script>
</body>
When you declare a function, you must call the function to execute the code inside it. For instance, if you don’t write myProduct()
outside the function code block in the example above, nothing will happen when you run the code. Comment out myProduct()
in your IDE and run the code, you will notice that nothing happens.
The function myProduct()
above is very limited because it can only compute product of 5 and 7. We can make a function more versatile with the use of what is called parameters. When we create a function with parameters in the parentheses, it will be possible to type in arguments when the function is called. Parameters are the variables that are passed into the parenthesis when a function is declared. On the other hand, the values of those variables (parameters) which are passed into the function when it is called are referred to as arguments Let apply this concept to myProduct()
function:
<body>
<script>
function myProduct(a, b) { // a and b are parameters
return(console.log(a * b));
}
myProduct(5, 7) // 5 and 7 are arguments
myProduct(2, 9) // 2 and 9 are arguments
myProduct(3, 4) // 3 and 4 are arguments
</script>
</body>
The function is now very versatile such that we can use it compute the product of any pair of two numbers. You can increase the number of parameters to accommodate more values at the point of calling the function. In subsequent subsequent tutorial, we shall discuss how to create a function that can take any number of arguments.
Document Object Model (DOM) Manipulation
The browser creates the DOM of a webpage whenever it is loaded. Simply, all the things that appear on your webpage is referred to as DOM. DOM manipulation is the ability of JavaScript to access and change elements of HTML. JavaScript does the manipulation through methods and HTML properties. A method is a function that is saved inside and object. Let us quickly discuss some of the common methods used for DOM manipulation.
document.querySelector()
document.querySelector()
method can be used to target and manipulate an HTML element using any of the CSS selectors. CSS selector can be the id, tag name or class. If no matches are found, null is returned. document.querySelector()
is useful when you need to select an element using a CSS selector. The shortcoming of this method is that it can be slow because it may need to search for multiple elements before returning the first match. Let us practice with some coding:
<body>
<h2>DOM Examples</h2>
<p>Hello World!</p>
<p>How are you finding JavaScript Tutorial?</p>
<script>
document.querySelector('p').innerHTML = 'Good day to all our esteemed students!'
</script>
</body>
In the code above, JavaScript was able to access and update the specified property (in this case innerHTML) of only the first paragraph element. The content of the second paragraph was not affected by the change even though we specified paragraph element as the argument in document.querySelector('p')
method. This is because document.querySelector()
method only returns the first Element within the document that matches the specified CSS selector. If you want to select all the elements that matches the CSS selector specified, use document.querySelectorAll()
as shown below.
<body>
<h2>DOM Examples</h2>
<p>Hello World!</p>
<p>Good day students</p>
<p>How are you finding JavaScript Tutorial?</p>
<script>
const myText = document.querySelectorAll('p');
//note myPara can be renamed anything you like as long as it complies with variable naming rules
myText.forEach((myPara) => {
myPara.innerHTML = 'Good day to all our esteemed students';
} )
//In the code above, we used two concepts (forEach and arrow function) both of which have not been discussed. Do not worry if you find them difficult to understand at this moment, they will be discussed in subsequent tutorials. The point we want you to get here is that by using querySelectorAll(), we were able to access all the paragraph elements on the web page
</script>
</body>
document.getElementById() Method
document.getElementById()
access the HTML element by using the value the element’s id
attribute and perform an action on it. The id
attribute value is passed in as the argument in document.getElementById()
, and the corresponding element is the return value. When an HTML element is inside JavaScript, it becomes a JavaScript object.
In the code below, JavaScript changed Hello world! to Good day students! For the change to be more noticeable, comment out the JavaScript code and Run the code, then uncomment and Run again.
<body>
<h2>DOM Examples</h2>
<p id='text'>Hello World!</p>
<script>
document.getElementById('text').innerHTML = 'Good day our esteemed students!'
</script>
</body>
Let us try another example applying some of the other concepts we have learnt so far in this tutorial.
<body>
<h2>DOM Example - Greetings</h2>
<p id='text'>Hello World!</p>
<button type='button' onclick='newGreetings()'>Greetings</button>
<script>
function newGreetings() {
let myContent = document.getElementById('text');
if (myContent.innerHTML != 'Hello World!') {
myContent.innerHTML = 'Hello World!';
} else {
myContent.innerHTML = 'Hello to all our esteemed students!';
}
}
</script>
</body>
In the example above, we used document.getElementById()
method, you can as well use document.querySelector()
using the the id of the HTML element as the argument as shown below. Or alternatively, we can use paragraph element as the argument. Since we have only one paragraph element, there would be no confusion with respect to which of the paragraph element we are targeting:
<body>
<h2>DOM Example - Greetings</h2>
<p id='text'>Hello World!</p>
<button type='button' onclick='newGreetings()'>Greetings</button>
<script>
function newGreetings() {
let myContent = document.querySelector('#text'); //Note that we added # to the ID
if (myContent.innerHTML != 'Hello World!') {
myContent.innerHTML = 'Hello World!';
} else {
myContent.innerHTML = 'Hello to all our esteemed students!';
}
}
</script>
</body>
Note: We added # to the HTML element id because
querySelector()
uses CSS selectors to access HTML elements.
addEventListener()
JavaScript addEventListener()
is an event handler that enables you to declare functions that can be called, upon occurrence of specified events such as click, load, keydown, keyup, keypress, mouseover etc.
addEventListener()
can be attached to a particular HTML element you want to monitor events for, and the element can have more than one handler attached. The general syntax for addEventListener is as follows:
target.addEventListener(‘event’, function, useCapture)
Let us explain each of the components of the syntax above
target - this is the HTML element you want to attach an event handler to. You can select the HTML element with his name, id or class.
event - this is the name of the event you want to monitor. Eg click, mouseover, etc.
function - this is the function that will be called when the event is detected
useCapture - an optional Boolean value (true or false) that determines which event gets executed first in situations where we have nested HTML elements with attached event handlers. The value is set to false by default, which means that the innermost HTML element’s event handler is executed first.
With addEventListener()
you can totally avoid writing inline JavaScript in an HTML document. Let us practice this concept by modifying the DOM Example - Greetings. You will see that we achieve the same outcome without writing any inline JavaScript in the file
<body>
<h2>DOM Example - Greetings</h2>
<p id='text'>Hello World!</p>
<button id='button'>Greetings</button>
<script>
const myGreetings = document.getElementById('button');
myGreetings.addEventListener('click', newGreetings);
function newGreetings() {
let myContent = document.getElementById('text');
if (myContent.innerHTML != 'Hello World!') {
myContent.innerHTML = 'Hello World!';
} else {
myContent.innerHTML = 'Hello to all our esteemed students!';
}
}
</script>
</body>
Passing Event as a Parameter
In situations where you need to have more information about the event, eg what element was clicked, you need to pass an event parameter to the function in the event handler. A common use case will be when one element is nested inside another element. This will be demonstrated in the solutions to the two of the project exercises below.
Projects
To wrap up this tutorial, carry out the following exercises/projects:
Voting Eligibility App - Create a simple web app that will enable users to confirm if they are old enough to vote or not. Remember we did something very close in one of the examples but we were displaying the output in the console. What you need to do is to take it further and convert it to a user friendly interactive app
To Do List App - Create an app that will enable users to create their todo list
Student Counter App - Create an app that will enable a user to count, monitor and record the number of student entering a named class. The number of student in a given class cannot be more than 15
The next section contains solutions to the projects with comments to explain the codes. Before you look at the solution, we recommend that you attempt to do the projects on your own first.
Sample Solutions to the Projects
Please note the following:
We used a lot of comments in the sample solutions for easy and better understanding for our students. You do not need to include the comments in your own code while you are practicing.
We used standard HTML document template for the projects solutions. Even though your code will work if you don’t use the standard template, some functionalities may not work without using the standard template in a live environment
The main objective of sample solutions we have provided is to simplify the learning process and hence, help our students understanding of the programming concepts. The solutions we provided might not be the most efficient, once again, they are meant to enhance your learning and understanding
Voting Eligibility App - see our solution below for your learning:
<!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>Document</title>
</head>
<body>
<h4>Confirm Your Voting Eligibility</h4>
<form onsubmit="checkEligibility()">
<!-- add required attribute to the input fields to make them mandatory -->
<label for="name">Name:</label>
<input type='text' placeholder='Please enter your name' id='name' required>
<label for="age">Age:</label>
<input type='number' placeholder='Please enter your age' id='age' required>
<input type="submit" value="submit">
</form>
<script>
function checkEligibility() {
//create variables with values that will enable us to access and manipulate HTML input elements using their id attribute value
let myName = document.getElementById('name').value;
let myAge = document.getElementById('age').value;
//Declare a conditional statement to test various possible scenarios and use alert function to display the appropriate message
if (myAge >= 18) {
alert('Congratulations ' + myName + '! You\'re ' + myAge + ' years old and hence, eligible to vote');
} else if (myAge >= 14) {
alert(myName + '! You\'re ' + myAge + ' years old, you will be eligible to vote next election');
} else {
alert(myName + '! You\'re ' + myAge + ' years old, you\'re too young to vote');
}
}
</script>
</body>
</html>
To Do List Project - see the solution below
<!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>Document</title>
</head>
<body>
<!--design the layout of your app with HTML -->
<div>
<h3>My ToDo List</h3>
<div>
Enter Task: <input id="enteredtask" type="text" placeholder="Enter a task">
<button id="addtask" onclick="addTask()"> Add Task </button>
</div>
<div>
<!-- create an empty ordered list that will accommodate todo items when they are created -->
<ol id="mylist"></ol>
</div>
</div>
<script>
// Declare variables that will enable us access and manipulate relevant HTML elements
//Note that the variable names are not the same as HTML id attribute values (written in lower case) which were passed into the getElementById method, we used camel case for the variable name. In short, you can change the variable name to whatever name you like as long as it complies with the variable naming rules
const enteredTask = document.getElementById('enteredtask');
const myList = document.getElementById('mylist');
function addTask() {
//Declare a conditional statement to check and ensure that the users do not submit a blank task. You will not need a conditional statement in this function if you had assigned required attribute to your input element in the HTML as we did in the first project. In that case you will just delete from 'if' line to the 'else' and start the coding for the function from 'let newTask... and also remove the closing curly bracket for the 'else'
if (enteredTask.value == '') {
alert('You cannot add a blank task. Please enter a task!');
}
else{
//declare a variable to create list items for that task that will be added by the user
let newTask = document.createElement('li');
//then, set the content of the list item created above to the value the user entered in the 'Enter Task' field
newTask.innerHTML = enteredTask.value;
//the next line of code is used to add the task entered by the user to the task list
myList.appendChild(newTask);
//next, declare a variable to create a delete button that will be attached to each of the list item we created above. The delete functionality can be employed by the users to remove completed task from the list.
let delButton = document.createElement('button');
//set the label of the button to 'Delete'
delButton.innerHTML = 'Delete';
//the next line of code is used to attach delete button to each of the added task
newTask.appendChild(delButton);
}
// the next line of code is used to set the value of input field to blank upon submission by the user. If this functionality is not implemented, the user can inadvertently save duplicated tasks
enteredTask.value = '';
}
//the code here is used to assign delete functionality to the button we created with JavaScript above
//the 'e' we passed in as a function parameter is a variable name and it can be called anything you like as long as it complies with the variable naming rules. It is necessary here to tell JavaScript which of the element we are targeting because the button element is nested inside the 'li' element we created with the variable newTask.
myList.addEventListener('click', function(e){
//tagName is a readonly property that returns the tag name of an HTML element in upper case. That is why the button in the 'if' condition below is written in upper case
if (e.target.tagName == 'BUTTON') {
//the next line of code is used to instruct JavaScript to delete (or remove) the parent element of the button the user clicks on
e.target.parentElement.remove();
}
}, false);
</script>
</body>
</html>
Student Counter App - See our solution below:
<!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>Document</title>
</head>
<body>
<!--design the layout of your app with HTML-->
<div>
<div><h3>Student Counter</h3></div>
<div><h4>Number Counted: <span id='countdisplay'>0</span></h4></div>
<div>Class ID: <input id='enteredid' placeholder='Enter class ID' type='text' ></div> <br>
<div>
<!--create buttons and assign appropriate function name as their onclick event value -->
<button onclick='countNum()' >Count</button>
<button onclick='saveCount()' >Save</button>
<button onclick='resetData()' >Reset Data</button>
</div>
<div><ol id='classid'></ol></div>
</div>
<script>
//1. set the counter to 0
let count = 0;
//2. declare variables that will enable us access and manipulate all the relevant HTML elements.
//Note that the variable names are not the same as HTML id attribute values (written in lower case) which were passed into the querySelector method, we used camel case for the variable name. In short, you can change the variable name to whatever name you like as long as it complies with the variable naming rules
let countDisplay = document.querySelector('#countdisplay');
let enteredId = document.querySelector('#enteredid');
let classId = document.querySelector('#classid')
//3. declare a function with the same name as the assigned value of the onclick event of the count button element. This function will handle the counting when the count button is clicked
function countNum() {
//reassign value to the count variable to increase the count by 1 each time count button is clicked
count = count + 1;
//assign the value of count to countDisplay
countDisplay.innerHTML = count;
//This is just a functionality that assumes the number of student in a class should not be more than 15. It calls saveCount() function once the limit has been reached
if (countDisplay.innerHTML == 15) {
alert('Student in a class cannot be more than 15');
//To call saveCount() once the limit is reached
saveCount();
}
}
//4. declare a function with the same name as the assigned value of the onclick event of the Save button element. This function will save the the task input by the user when the Save button is clicked
function saveCount() {
//declare two conditional statements to prevent users from submitting blank class ID and zero student in a class
if (countDisplay.innerHTML == 0) {
alert('The number of student in a class cannot be zero');
// the return statement below terminate the process and returns the user to the starting point of the 'if' statement whenever he tries to submit zero count. You can comment out the return statement and run the app to see the implication of not having it in the programme
return;
}
if (enteredId.value == '') {
alert('Class ID cannot be blank, please enter the class ID');
}
//if the user enters acceptable data, the lines of code below will run
else{
//declare a variable to create list item for every saved count
let newClassId = document.createElement('li');
//then, set the content of the list item created above to the value the user entered in the Class ID plus and concatenated it to string 'has'
newClassId.innerHTML = enteredId.value + ' has ';
//the next line of code is used to add the Class ID entered by the user to the list of saved count
classId.appendChild(newClassId);
//declare a variable to create span element to accommodate number in the saved count
let classCount = document.createElement('span');
//assign the value in the countDisplay concatenated to student to the classCount (the span element created in the last line of code above)
classCount.innerHTML = countDisplay.innerHTML + ' students';
//the next line of code is used to attach the span element and its value to each of the saved count
newClassId.appendChild(classCount);
//next, declare a variable to create a delete button that will be attached to each of the saved count created above. The delete functionality can be employed by the users to remove wrong entry
let deleteItem = document.createElement('button');
//set the label of the button to 'Delete'
deleteItem.innerHTML = 'Delete';
//the next line of code is used to attach delete button to each of the saved count
newClassId.appendChild(deleteItem);
// the next 3 lines of code are used to set the value of input fields to blank upon submission by the user. If this functionality is not implemented, the user can inadvertently save duplicated data
count = 0;
countDisplay.innerHTML = 0;
enteredId.value = '';
}
}
//5. the code here is used to assign delete functionality to the button we created with JavaScript above
//the 'e' we passed in as a function parameter is a variable name and it can be called anything you like as long as it complies with the variable naming rules. It is necessary here to tell JavaScript which of the element we are targeting because the button element is nested inside the 'li' element we created with the variable newClassId
classId.addEventListener("click", function(e){
if (e.target.tagName == "BUTTON") {
e.target.parentElement.remove();
}
},);
//6. the function below reset all the values to zero or blank
function resetData() {
classId.innerHTML = ''; //to remove all the saved data
count = 0; //to set the count back to zero
countDisplay.innerHTML = 0; //to set Number Counted field to zero
enteredId.value = ''; //to clear any input made by the user inside Class Id field
}
</script>
</body>
</html>
Conclusion
We hope you enjoyed and found the content of this tutorial useful and helpful. Watch out for our HTML-CSS Made Easy - Part 2, we are going to learn CSS and style two of the Apps we built in the project for this tutorial to make them look feel great.
Finally for your information, we shall explore deeper and discuss more JavaScript concepts in Part Two of this tutorial. Please watch out for it.