Skip to content

A complete guide to learn JavaScript, from basics to advanced, with clear examples and easy-to-follow steps.

Notifications You must be signed in to change notification settings

ChAbdulWahhab/JavaScript-Journey

Repository files navigation

11.1 Introduction

Consider an organization that provides a Website that allows its customers to view their products. The company has received frequent customer feedbacks to provide the shopping facility online. Therefore, the company has decided to add the shopping facility in their Website by creating dynamic Web pages. These Web pages will allow the user to shop for the products online. For example, details such as credit card number, email, and phone number entered by the customer must be in a proper format. Further, the developer also requires to retrieve the chosen products and their quantity to calculate the total cost.

The developer can handle all these critical tasks by using a scripting language. A scripting language refers to a set of instructions that provides some functionality when the user interacts with a Web page.


11.2 Scripting

Scripting refers to a series of commands that are interpreted and executed sequentially and immediately on occurrence of an event. This event is an action generated by a user while interacting with a Web page. Examples of events include button clicks, selecting a product from a menu, and so on. Scripting languages are often embedded in the HTML pages to change the behaviour of the Web pages according to the user’s requirements.

There are two types of scripting languages, described as follows:

  • Client-side Scripting

    • Refers to a script being executed on the client’s machine by the browser.
  • Server-side Scripting

    • Refers to a script being executed on a Web server to generate dynamic HTML pages.

11.3 JavaScript

JavaScript is a scripting language that allows you to build dynamic Web pages by ensuring maximum user interactivity. JavaScript language is an object-based language, which means that it provides objects for specifying functionalities. In real life, an object is a visible entity such as a car or a table. Every object has some characteristics and is capable of performing certain actions. Similarly, in a scripting language, an object has a unique identity, state, and behaviour.

The identity of the object distinguishes it from the other objects of the same type. The state of the object refers to its characteristics, whereas the behavior of the object consists of its possible actions. The object stores its identity and state in fields (also called variables) and exposes its behaviour through functions (actions).

Car Table
Identity: BMW F90 M5 Identity: T002
State: Color-Red, Wheels-Four State: Color-Brown
Behavior: Running Behavior: Stable

11.4 Versions of JavaScript

The first version of JavaScript was developed by Brendan Eich at Netscape in 1995 and was named JavaScript 1.0. Netscape Navigator 1.0 and Internet Explorer 3.0 supported JavaScript 1.0. Over the period, it gradually evolved with newer versions where each version provided better features and functionalities as compared to their previous versions.

Table 11.1 lists various versions of JavaScript language, also called as ECMAScript.

Edition Name Description
1 ECMAScript 1 (1997) First edition
2 ECMAScript 2 (1998) Supported by Internet Explorer from version 4.0
3 ECMAScript 3 (1999) Added regular expressions and try/catch and was supported by Internet Explorer 5.0, Netscape Navigator 1.0, and Opera 5.0 onwards
5 ECMAScript 5 (2009) Added features such as ‘strict mode’, JSON support, String.trim(), Array.isArray(), and Array iteration methods. Is supported by Internet Explorer 6.0 and Mozilla Firefox 1.0 onwards.
6 ECMAScript 2015 Was published in 2015 and added features such as let and const, default parameter values, Array.find(), and Array.findIndex()
7 ECMAScript 2016 Was published in 2016 and added exponential operator and Array.prototype.includes
8 ECMAScript 2017 Was published in 2017 and added features such as string padding, Object.entries, Object.values, async functions, and shared memory
9 ECMAScript 2018 Was published in 2018 and added features such as rest/spread properties, asynchronous iteration, and Promise.finally()
10 ECMAScript 2019 Was published in 2019 and added features such as Array.prototype.flat, Array.prototype.flatMap, and Object.fromEntries
11 ECMAScript 2020 Was published in June 2020 and introduces a BIGINT primitive type for arbitrary-sized integers, nullish coalescing operator, and globalThis object.
12 ECMAScript 2021 Was published in June 2021 and introduces replaceAll method for Strings, Promise.any.AggregateError, WeakRef, and other features.

11.5 Client-side JavaScript

JavaScript is a scripting language, which can be executed on the client-side and on the server-side. A client-side JavaScript (CSJS) is executed by the browser on the user’s workstation. A client-side script might contain instructions for the browser to handle user interactivity. These instructions might be to change the look or content of a Web page based on the user inputs. Examples include displaying a welcome page with the username, displaying date and time, validating that the required user details are filled, and so on.

A JavaScript is either embedded in an HTML page or is separately defined in a file, which is saved with a .js extension. In client-side scripting, when an HTML page is requested, the Web server sends all the required files to the user’s computer. The Web browser executes the script and displays the HTML page to the user along with any tangible output of the script.


11.6 Server-side JavaScript

A server-side JavaScript (SSJS) is executed by the Web server when an HTML page is requested by a user. The output of a server-side JavaScript is sent to the user and is displayed by the browser. In this case, a user might not be aware that a script was executed on the server to produce the desirable output.

A server-side JavaScript can interact with the database, fetch the required information specific to the user, and display it to the user. This means that server-side scripting fulfills the goal of providing dynamic content in a web page. Unlike client-side JavaScript, HTML pages using server-side JavaScript are compiled into bytecode files on the server. Compilation is a process of converting the code into machine-independent code. This machine-independent code is known as the bytecode, which is an executable file. The Web server runs this executable to generate the desired output.


11.7 Script Tag

The <script> tag defines a script for an HTML page to make them interactive. The browser that supports scripts interprets and executes the script specified under the <script> tag when the page loads in the browser. You can directly insert a JavaScript code under the <script> tag. You can define multiple <script> tags either in the <head> or in the <body> elements of an HTML page. In HTML5, the type attribute type="text/javascript" specifying the scripting language is no longer required as it is optional.

<!DOCTYPE html>
<html>
	<head>
		<title>Document</title>
		<script>
			document.write("Hello World!");
		</script>
	</head>
<body>
	...
</body>
</html>

There are two main purpose of the <script> tag, which are as follows:

  • Identifies a given segment of script in the HTML page.
  • Loads an external script file.

11.8 Variables in JavaScript

A variable refers to a symbolic name that holds a value, which keeps changing. For example, age of a student and salary of an employee can be treated as variables. A real-life example for variables includes the variables used in algebraic expressions that store values.

In JavaScript, a variable is a unique location in the computer's memory that stores a value and has a unique name. The name of the variable is used to access and read the value stored in it. A variable can store different types of data such as a character, a number, or a string. Therefore, a variable acts as container for saving and changing values during execution of the script.

11.8.1 Declaring Variables

Declaring a variable refers to creating a variable by specifying the variable name. For example, you can create a variable named studName to store the name of a student. Here, the variable name studName is referred to as a identifier. In JavaScript, the var keyword is used to create a variable by allocating memory to it. A keyword is a reserved word that holds a special meaning in JavaScript.

You can initialize the variable at the time of creating the variable or later. Initilization refers to the task of assigning a value to a variable. once the variable is initialized, you can change the value of a variable as required.

Variables allow keeping track of data during the execution of the script. While referring to a variable, you are referring to the value of that variable. In JavaScript, you can declare and initialize multiple variables in a single statement.

Following syntax demonstrates how to declare variables in JavaScript: Syntax

var <variableName>;

where,

var: Is the keyword in JavaScript
variableName: Is a valid variable name.

Following syntax demonstrates how to initalize variables in JavaScript: Syntax

<variableName> = <value>;

where, = : Is the assignment operator used to assign values. value: Is the data that is to be stored in the variable.

Following syntax demonstrates how to declare and initialize multiple variables in a single statement, which are separated by commas. Syntax

var <variableName> = <value>, <variableName2> = <value2>;

Code Snippet 2 declares two variables namely, studID and studName and assign values to them. Code Snippet 2

var studID;
var studName;
studID = 50;
studName = "Abdullah";

This code assigns values to studID and studName variables by using the assignment operator =. The value named Abdullah is specified within double quotes.

Code Snippet 3 demonstrates how to declare and initialize multiple variables in a single statement in JavaScript.

Code Snippet 3 var studName = 'Abdullah', studAge = 15;


Understanding var, let, and const

3.2 The var Keyword

3.2.1 Definition

The var keyword is the original method for declaring variables in JavaScript. It has been part of the language since 1995.

3.2.2 Key Characteristics

Function Scope: Variables declared with var are function-scoped, meaning they are accessible throughout the entire function in which they are declared, regardless of block boundaries.

Re-declaration Allowed: The same variable can be declared multiple times within the same scope without generating an error.

Re-assignment Allowed: Values can be changed after declaration.

Hoisting: Variables declared with var are hoisted to the top of their scope. The declaration is processed before code execution, but initialization remains in place.

Note: Modern JavaScript development discourages the use of var due to scope-related issues.


3.3 The let Keyword

3.3.1 Definition

The let keyword was introduced in ECMAScript 6 (ES6) in 2015 to address the shortcomings of var. It provides block-level scope.

3.3.2 Key Characteristics

Block Scope: Variables declared with let are block-scoped. They only exist within the block (defined by curly braces) in which they are declared.

No Re-declaration: Unlike var, let does not allow re-declaration of the same variable within the same scope.

Re-assignment Allowed: Values can be changed after declaration.

Temporal Dead Zone (TDZ): Variables declared with let cannot be accessed before their declaration in the code.

Usage: Use let when you need to declare a variable whose value will change during program execution, such as loop counters or accumulator variables.


3.4 The const Keyword

3.4.1 Definition

The const keyword, also introduced in ES6, is used to declare constants—variables whose binding cannot be changed after initialization.

3.4.2 Key Characteristics

Block Scope: Like let, const is block-scoped and only accessible within its defining block.

No Re-declaration: Cannot declare the same variable twice within the same scope.

No Re-assignment: Variables declared with const cannot be reassigned. The binding between the variable name and its value is constant.

Must Initialize: Constants must be initialized at the time of declaration. Declaration without initialization results in an error.

Object and Array Mutability: While the binding of a const variable cannot change, the contents of objects and arrays declared with const can be modified. You can add, remove, or change properties of objects and elements of arrays.

Usage: Use const as the default choice for variable declaration. It should be used for values that will not be reassigned, including configuration values, mathematical constants, and references to objects and arrays.


3.5 Comparison Table

Feature var let const
Scope Function Block Block
Re-declaration Allowed Not Allowed Not Allowed
Re-assignment Allowed Allowed Not Allowed
Must Initialize No No Yes
Hoisting Yes (undefined) Yes (TDZ) Yes (TDZ)
Modern Usage Avoid When value changes Default choice

11.8.2 Variable Naming Rules

You cannot refer to a variable until it is created in JavaScript. JavaScript is a case-sensitive language. This means that if you specify X and x as variables, both of them are treated as two different variables. Similarly, in JavaScript, there are certain rules, which must be followed while specifying variables names. These rules for a variable name are as follows:

  • Can consist of digits, underscore, and alphabets.
  • Must begin with a letter or the underscore character.
  • Cannot begin with a number and cannot contain any punctuation marks.
  • Cannot contain any kind of special characters such as +, *, % and so on.
  • Cannot contain spaces.
  • Cannot be a JavaScript keyword.

It is recommended to give meaningful names to variables such that the name determines the kind of data stored in the variable.

11.9 Data Types in JavaScript

A Web page designer can store different types of values such as numbers, characters, or strings in variables. However, the Web page designer must know what kind of data a particular variable is expected to store. To identify the type of data that can be stored in a variable , JavaScript provides different data types.

A Web page designer is not required to specify the data type while declaring variables. Due to this, JavaScript is referred to as the loosely typed language. This means that a variable holding a number can also hold a string value later. The values of variables are automatically mapped to their data types when the script is executed in the browser.

Data types in JavaScript are classified into two broad categories namely, primitive and composite data types. Primitive data types contain only a single value, whereas the composite data types contain a group values.

11.9.1 Primitive Data Types

A primitive data type contains a single literal value such as number or a string. A literal is a static value that you can assign to variables.

Primitive Data Type Description
boolean Contains only two values namely, true or false.
null Contains only one value namely, null. A variable of this value specifies that the variable has no value. This null value is keyword and it is not the same as the value, zero
number Contains positive and negative numbers and numbers with decimal point. Some of the valid examples include 6, 7.5, -8, 7.5e-3 and so on.
string Contains alphanumeric characters in single or double quotation marks. The single quotes is used to represent a string, which itself consists of quotation marks. A set of quotes without any characters within it is known as the null string.

11.9.2 Composite Data Types

A composite data type stores a collection of multiple related values, unlike primitive data types. In JavaScript, all composite data types are treated as objects. A composite data type can be either predefined or user-defined in JavaScript.

Data Types Description
Objects Refers to a collection of properties and functions. Properties specify the characteristics and functions determine the behavior of a JavaScript object.
Functions Refers to a collection of statements, which are instructions to achieve a specific task
Arrays Refers to a collection of values stored in a adjacent memory locations.

Escape Sequence Characters

An escape sequence character is a special character that is preceded by a backslash (\). Escape sequence characters are used to display special non-printing characters such as a tab space, a single space, or a backspace. These non-printing characters help in displaying formatted output to the user to maximize readability. The backslash character specifies that the following character denotes a non-printing character. For example, \t is an escape sequence characters must always be enclosed in double quotes.

Escape Sequence Non-Printing Character
\b Back space
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\' Single quote
\" Double quote
\\ Backslash
\aaa Matches a Latin-1 encoding character using octal representation, where aaa are three octal numbers. For example, \251 represents the copyright symbol.
\xaa Matches a Latin-1 encoding character using hexadecimal representation, where aa are two hexadecimal numbers. For example, \x61 represents the character 'a'
\uaaaa Represents the Unicode encoding character, where aaaa are four hexadecimal numbers. For example, the character \u0020 represents a space.
<script>
	document.write("You must have a \u0022credit card\u0022, if you want to shop     on the \'Internet\'.");
</script>

The code uses a Unicode encoding character namely, \u00022, which represents double quotes. These open and close double quotes will contain the term credit card. Similarly, the word Internet will be placed in single quotes. The single quotes are specified using the backslash character.

NOTE - An encoding scheme specifies how to represent character data in terms of their acceptable range, maximum number of characters, and patterns. Unicode is a character set that contains all the international characters required for processing information. Latin 1 is the encoding scheme for English and Western European languages on the Internet.


11.13 Built-in Functions

A function is a piece of code that performs some operations on variables to fulfill a specific task. It takes one or more input values, processes them, and returns an output value. JavaScript provides built-in functions that are already defined to fulfill a certain task. Table 11.5 lists the built-in functions.

Function Description Example
alert() Displays a dialog box with some information and OK button alert("Please fill all fields of the form"); Displays a message box with the instruction
confirm() Displays a dialog box with OK and Cancel buttons. It verifies an action, which a user wants to perform confirm("Are you sure you want to close the page?"); Displays a message box with the question
parseInt() Converts a string value into a numeric value parseInt("25 years");
parseFloat() Converts a string value into a number with decimal point parseFloat("10.33"); Returns 10.33
eval() Evaluates an expression and returns the evaluated result eval("2+2"); Returns 4
isNaN Checks whether a value is not a number isNaN("Hello"); Returns true
prompt() Displays a dialog box that accepts an input value through a text box. It also accepts default value for text box. prompt("Enter your name", "Name"); Displays message in dialog box and Name in text box.

NOTE - The \n character, when used in the alert() function, prints the information on a new line. This does not happen when the \n character is used with the write methods of the document object.


Operators – Introduction

In JavaScript, operators are special symbols or keywords used to perform operations on values and variables. They help in executing tasks such as calculations, assignments, comparisons, and logical decision-making. Most standard programming books categorize JavaScript operators into four primary groups, which are explained below.

1. Arithmetic Operators

Arithmetic operators are used to perform basic mathematical operations on numbers. They allow you to create numeric expressions involving addition, subtraction, multiplication, division, and more.

Common Arithmetic Operators:

  • + (Addition)

  • - (Subtraction)

  • * (Multiplication)

  • / (Division)

  • % (Modulus – returns remainder)

  • ** (Exponentiation – power)

  • ++ (Increment)

  • -- (Decrement)

These operators are essential for performing calculations and manipulating numeric data in programs.


2. Assignment Operators

Assignment operators are used to assign values to variables. They can also combine assignment with another operation, allowing concise and readable code.

Common Assignment Operators:

  • = (Simple Assignment)

  • += (Add and assign)

  • -= (Subtract and assign)

  • *= (Multiply and assign)

  • /= (Divide and assign)

  • %= (Modulus and assign)

  • **= (Exponent and assign)

Programming books often refer to these as “shorthand assignment operators” because they simplify expressions.


3. Comparison Operators

Comparison operators compare two values and return a boolean result (true or false). These operators are widely used in decision-making constructs such as if, else, and loops.

Common Comparison Operators:

  • == (Equal to – compares values)

  • === (Strict equal to – compares value and type)

  • != (Not equal to)

  • !== (Strict not equal to)

  • > (Greater than)

  • < (Less than)

  • >= (Greater than or equal to)

  • <= (Less than or equal to)


4. Logical Operators

Logical operators are used to combine multiple conditions or to apply logical reasoning in a program.

They operate on boolean values and return either true or false.

Common Logical Operators:

  • && (Logical AND) — returns true only if all conditions are true

  • || (Logical OR) — returns true if at least one condition is true

  • ! (Logical NOT) — reverses a boolean value (true becomes false and vice versa)

These operators play a key role in controlling the flow of a program.


11.14 Events

Consider a scenario where you want to design an Employee registration Web form. This form allows the users to fill in appropriate details and click the submit button. When the user clicks the submit button, the form data is submitted to the server for validation purposes. In this case, when the user clicks the button, and event is generated. The submission of form refers to the action performed on click of the button.

An event occurs when a user interacts with the Web page. Some of the commonly generated events are mouse click, key strokes, and so on. The process of handling these events is known as event handling.

11.14.1 Event Handling

Event handling is a process of specifying actions to be performed when an event occurs. This is done by using an event handler. An event handler is a scripting code or a function that defines the actions to be performed when the event is triggered.

When an event occurs, an event handler function that is associated with the specific event is invoked. The information about this generated event is updated on the event object. The event object is a built-in object, which can be accessed through the window object.

It specifies the event state, which includes information such as the location of mouse cursor, element on which event occurred, and state of the keys in a keyboard.

11.14.2 Event Bubbling

Event bubbling is mechanism that allows you to specify a common event handler for all child elements. This means that the parent element handles all the events generated by the child elements. For example, consider a Web page that consists of a paragraph and a table. The paragraph consists of multiple occurrences of italic text. Now, you want to change the color of each italic text of a paragraph when the user clicks a particular button. Instead of declaring an event handler for each italic text, you can declare it within the P element. This allows you to apply colors for all italic text within the paragraph. This helps in reducing the development time and efforts since it minimizes the code.

Figure 11.11: Event Bubbling

11.14.3 Life Cycle of on Event

An event's life starts when the user preforms an action to interact with the Web page. It finally ends when the event handler provides a response to the user's action.

Steps involved in the life cycle of an event are as follows:

  • The user performs an action to raise an event.
  • The event object is updated to determine the event state.
  • The event is fired.
  • The event bubbling occurs as the event bubbles through the elements of the hierarchy.
  • The event handler is invoked that performs the specified actions.

11.14.4 Keyboard Events

Keyboard events are the events that occur when a key or a combination of keys are pressed or released from a keyboard. These events occur for all keys of a keyboard.

Different keyboard events are as follows:

  • Onkeydown
    • Occurs when a key is pressed down.
  • Onkeyup
    • Occurs when the key is released.
  • Onkeypress
    • Occurs when a key is pressed and released.