Data Structures Notes Full
Data Structures Notes Full
Competency: Apply Data Structure and Algorithm Fundamentals Using Java Script
Competency: Apply Data Structure and Algorithm Fundamentals Using Java Script
1.3 Data types are effectively used according to their intended use
2.1 Data structure concepts are clearly identified based on intended use.
2. Apply Data
Structure 2.2 Linear Data Structures are properly applied based on their operational
complexity
2.3 NonLinear Data Structures are properly applied based on their operational
complexity
3. Implement 3.2 JavaScript source code is successfully run in accordance with expected
JavaScript
3.3 Time and space complexity are successfully tested based on data structure
standards
Learning outcomes: At the end of the module the learner will be able to:
Page 2 of 203
Page 3 of 203
In this system there are 16 symbols or possible digit values from 0 to 9, followed by six
alphabetic characters -- A, B, C, D, E and F. These characters are used to
represent decimal values from 10 to 15 in single bits.
Here's what the decimal and hexadecimal systems look like for digits 0 to 15.
Decimal 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Hexadecimal 0 1 2 3 4 5 6 7 8 9 A B C D E F
Octal base has a base of eight and uses the numbers from 0 to 7. The octal numbers, in
the number system, are usually represented by binary numbers when they are grouped in
pairs of three. For example, an octal number 128 is expressed as 0010102 in the binary
system, where 1 is equivalent to 001 and 2 is equivalent to 010.
Base – 8
Page 4 of 203
Step 3: Repeat the above steps until you get 0 as the quotient.
Step 4: Now, write the remainders in such a way that the last remainder is written
first, followed by the rest in the reverse order.
Step 5: This can also be understood in another way which states that the Least
Significant Bit (LSB) of the binary number is at the top and the Most Significant Bit
(MSB) is at the bottom. This number is the binary value of the given decimal number.
Solution: We will start dividing the given number (13) repeatedly by 2 until we get the quotient as 0.
We will note the remainders in order.
13 ÷ 2 6 1 (LSB)
Page 5 of 203
Division by 2 Quotient Remainder
6÷2 3 0
3÷2 1 1
1÷2 0 1 (MSB)
After noting the remainders, we will write them in such a way that the Most Significant Bit (MSB)
of the binary number is written first, followed by the rest. Therefore, the binary equivalent for the
given decimal number 1310 is 11012. This means that 1310 = 11012.
Decimal to Binary Table
There are different methods of converting numbers from decimal to binary. When we convert numbers
from decimal to binary, the base of the number changes from 10 to 2. It should be noted that all
decimal numbers have their equivalent binary numbers. The following table shows the decimal to
binary chart of the first 20 whole numbers.
0 0
1 1
2 10
3 11
4 100
5 101
6 110
7 111
Page 6 of 203
Decimal Numbers Binary Numbers
8 1000
9 1001
10 1010
11 1011
12 1100
13 1101
14 1110
15 1111
16 10000
17 10001
18 10010
19 10011
20 10100
Examples
1: Convert 17410 to binary.
2: Convert the following decimal number into binary number: 156
3: State true or false with reference to decimal to binary conversion.
a.) The binary number system has a base of 2 since it uses only two digits to represent a number.
b.) When the decimal number 10 is converted to binary, it gives the value as 1010.
Page 7 of 203
c.) When the decimal number 4 is converted to binary, it gives the value as 100.
Solution:
a.) True, the binary number system has a base of 2 since it uses only two digits to represent a number.
b.) True, when the decimal number 10 is converted to binary, it gives the value as 1010.
c.) True, when the decimal number 4 is converted to binary, it gives the value as 100.
There are two main methods for converting binary number systems into decimal number systems.
These methods are:
1. Positional Notation
2. Doubling
Conversion Using Positional Notation
Write the binary number and count the power of 2 from right to left, starting from
0 onwards.
Now each binary number has the corresponding power of 2 starting from right to
left. So the most significant bit will have the highest power of 2.
Add the product of the second step
The final answer will be converted into a decimal number that is base 10.
Example of Positional Notation
1 0 1
1 x 22 + 0 x 21 + 1 x 20
4+0+1
(5)10
Page 8 of 203
Similar we can represent fractional binary number into decimals
1 0 1.1 0 1
(4 + 0 + 1) . (0.5 + 0 + 0.125)
(5.625)10
Conversion using doubling is one of the simplest ways for converting binary numbers into decimal
numbers. We need to take the most signification bit or leftmost digit of the number. Then multiply the
digit by 2 and add the second leftmost bit and store the result. Similarly, we need to take the result
and multiply it by 2 and take the third leftmost bit and update the result. This process will continue till
we reach the least significant bit which is the rightmost bit. Since we are multiplying by 2 so this
process is known as Doubling.
Example of Doubling
=1
=1x2+0=2
=2x2+1=5
Page 9 of 203
Binary to Decimal Formula
The formula to convert binary number system into decimal]’n be represented by,
Where,
For Example :
(1000)2 = 1 x 23 + 0 x 22 + 0 x 21 + 0 x 20
0000 0 1000 8
0001 1 1001 9
0010 2 1010 10
0011 3 1011 11
Page 10 of
Binary1 Decimal1 Binary2 Decimal2
0100 4 1100 12
0101 5 1101 13
0110 6 1110 14
0111 7 1111 15
To convert a decimal number to an octal number, there are several direct and indirect methods. They
are as given below:
o Decimal to Octal Conversion Using by Direct Method: As the name suggests decimal
numbers are directly converted to octal numbers.
o Decimal to Octal Conversion Using by Indirect Method: This method converts the decimal
number into a binary number or hexadecimal first and then converts that to an octal
number.
To convert a Decimal number to an Octal number directly, you must start dividing the number by 8
until you get 0 as the quotient. This is a straightforward method that involves dividing the number
to be converted.
Step 1: If the decimal number is N, divide it by 8 because the octal number system’s base is 8.
Step 2: Note the value of the residual, which will be one of the following: 0, 1, 2, 3, 4, 5, 6, or 7.
Divide the remaining decimal number until it equals 0 and record the remainder of each step.
Step 3: Then, from bottom to top (or in reverse order), write the remainders, which will be the
equivalent octal number of the provided decimal number.
Page 11 of
Page 12 of
Let’s see this with the help of an example:
Note: The dividend (here given decimal number) is the number to be divided, the divisor (here base of
octal, i.e., 8) is the number to be divided by, and the quotient (remaining divided decimal number) is
the outcome of the division.
As mentioned above this method converts the decimal number into a binary number or hexadecimal
first and then converts that binary or hexadecimal number to an octal number.
Let’s see how to convert decimal numbers to binary to octal conversion. By repeatedly dividing a
number by two and recording the result, decimal values can be transformed into binary.
Page 13 of
Take a look at an example to see how this works.
The remainders are to be read from bottom to top to obtain the binary equivalent.
4310=1010112
A binary number can be converted to an octal number in a variety of ways. Direct and indirect
approaches can both be used to convert. To begin, you must convert a binary into a different base
system (e.g., into decimal, or into hexadecimal). After that, you must convert it to an octal number.
Because the octal number system has only eight digits (from 0 to 7), we may express each octal digit
using only three bits, as seen below.
0 000
1 001
2 010
3 011
4 100
5 101
Page 14 of
6 110
7 111
Step 1: Consider the binary number. For the integer component, divide the binary digits into three
groups (beginning from the right), and for the fraction part, start from the left.
Step 2: Each set of three binary digits should be converted to one octal digit.
= (1010111100)
= (1 2 7 4)
= (1274)
Page 15 of
This is a simple procedure that involves dividing the number to be transformed by two.
Step 1: If the decimal number is N, divide it by 16 because the hexadecimal number system’s base is
16. Make a note of the value of the remainder, which will range from 0 to 15 (replace 10, 11, 12, 13,
14, 15 with A, B, C, D, E, and F respectively). Divide the remaining decimal number until it equals 0
and record the remainder of each step. Then, from bottom to top (or in reverse order), write the
remainders, which will be the equivalent hexadecimal number of the supplied decimal number.
Example:
This approach works by estimating a decimal number’s hexadecimal equivalent. Any decimal number
can be used as a starting point. Make a list of 16’s abilities. Multiply the decimal number by the 16th
power. Find the rest of the items. Multiply the residual by the 16th power. Repeat until you’ve figured
out the whole solution.
Example:
Page 16 of
Now we will convert hexadecimal number to octal number. Here are the steps:
Step 2: If n is the digit’s position from the right end, multiply each digit by 16n−116n−1.
Step 3: After you’ve multiplied the terms, add them together. The comparable decimal form is the
resultant.
Step 5: With the quotient, repeat the previous two steps until the quotient is zero. Reverse the order
of the remainder. The obtained number corresponds to the desired outcome.
Example:
To convert Decimal to Octal including decimal points, we first convert it to hexadecimal and then
convert it to octal.
If the decimal fractional portion is M, multiply it by 16 because the hexadecimal number system’s
base is 16. Take note of the integer part’s value, which will range from 0 to 15. (replace 10, 11, 12,
13,
Page 17 of
14, and 15 by A, B, C, D, E, and F respectively). Multiply the remaining decimal fractional number
until it equals 0 and record each integer part of the result. Then write the integer part’s results, which
will be a fraction hexadecimal number comparable to the specified decimal value.
Once we get the hexadecimal number we convert it to octal using the steps we discussed above.
Page 18 of
4330/8 541 2
541/8 67 5
67/8 8 3
8/8 1 0
1/8 0 1
Example 2: What is the number 4321.35610 in the octal number system? (till 6 significant digits)
Solution: In order to convert 4321.35610 into octal, we divide it into two parts of whole number and
fraction. First, let’s convert the whole number part. We divide the number 4321 by 8 till we get the
quotient 0.
4321/8 540 1
540/8 67 4
67/8 8 3
8/8 1 0
1/8 0 1
We read the reminder in reverse order. So 4321=10341. Next is the conversion of the fraction part. If
the decimal fractional component is M, multiply it by 8 because the octal number system’s base is 8;
till the significant digits are required.
Page 19 of
— Octal
0.356 x 8 = 12.848 12
0.848 x 8 = 6.784 6
0.784 x 8 = 6.272 6
0.272 x 8 = 2.176 2
0.176 x 8 = 1.408 1
0.408 x 8 = 3.264 3
Go through the steps given below to learn how to convert the numbers from decimal to hex.
Step 1: First, divide the decimal number by 16, considering the number as an integer.
Step 3: Again divide the quotient by 16 and repeat till you get the quotient value equal to zero.
Step 4: Now take the values of the remainder’s left in the reverse order to get the hexadecimal
numbers.
Note: Remember, from 0 to 9, the numbers will be counted as the same in the decimal system. But
from 10 to 15, they are expressed in alphabetical order such as A, B, C, D, E, F and so on.
Let us take an example to understand the steps given above for decimal to hex conversion.
Page 20 of
Example: Convert (960)10 into hexadecimal.
Solution:
To convert decimal to hex, i.e. 960 base 10 to a hexadecimal number, follow the steps given below:
Step 4: Now taking the remainder in reverse order and substituting the equivalent hexadecimal value
for them, we get,
3→3, 12→C and 0→0
Let’s discuss the octal to binary conversion steps for the indirect method.
To convert octal to decimal, we multiply each digit by the power of 8 based on the position starting
from the right. We will multiply the first digit from the right by 80. Next, we will multiply the second
digit by 81 and so on.
Page 19 of
Step 2: Convert decimal to binary.
For converting decimal to binary, we will divide the given number by 2 and record
the quotient and reminder. We will repeat the process until we obtain 0 as the quotient.
548=4×80+5×81
548=4×1+5×8
548=4+40
548=4410
44÷2 22 0
22÷2 11 0
11÷2 5 1
5÷2 2 1
2÷2 1 0
Page 20 of
Division Quotient Remainder
1÷2 0 1
On arranging all the remainders in the reverse order, we will obtain the following binary number:
Thus, 4410=1011002
There is no specific octal to binary formula for conversion. However, if you are looking for an easier
and less complicated octal to binary conversion method, the direct method involves the following
steps:
In octal to binary conversion, each digit in the octal number has a three-digit binary representation.
Using it, we can easily convert a number from octal to binary. We can convert octal to binary by
choosing the binary equivalent of every digit of the octal number from the below-mentioned chart.
The following table includes the octal numbers 0 to 7 and their equivalent three-digit binary
representation to aid octal to binary conversion.
0 000
1 001
2 010
Page 21 of
Octal Number Equivalent Three-digit Binary Representation
3 011
4 100
5 101
6 110
7 111
From the above chart, we will note down their binary equivalents.
5→101
4→100
Now, combining the two, we get the following binary number: 1011002.
Let’s understand the steps with the help of an example. We will also understand how the three-digit
binary representation is obtained for each octal digit.
Page 22 of
Page 23 of
7 6 5
Step 2: Each octal digit represents 3 binary bits. Starting from right to left, the value of these three
digits is 20=1,21=2, and 22=4 respectively. Thus, write (4, 2, 1) below each octal digit.
7 6 5
4 2 1 4 2 1 4 2 1
Step 3: Identify the numbers among 4, 2, and 1 (powers of 2), which add up to the octal number
written on the top. Write 1 below if the number is used. Write 0 below the number that is not used in
the sum. For example, 7=4+2+1, so we write 1 under all the three numbers.
7 6 5
4 2 1 4 2 1 4 2 1
1 1 1 1 1 0 1 0 1
Step 4: Write the 1s and 0s from left to write to find the binary equivalent of the given octal number.
Thus, 7658=1111101012
Octal to decimal:
Page 23 of
348=(3×81)+(4×80)
348=24+4
348=2810
Page 24 of
Solved Examples of Octal to Hexadecimal
Problem : 1
Solution:
Octal is first converted to binary before being converted to hexadecimal. Looking at the table of the
octal to binary conversion,
5 = 101
1 =000
(50)8=(101000)2
0010 = 2
1000 = 8
Problem : 2
Solution:
(56)8
= (101)(110)
=(101110)2
Page 25 of
Now convert (101110)2 in hexadecimal
Page 26 of
(101110)2
= (10)(1110)
= (2)(14)
= (2E)16
Problem: 3
Solution:
= 3×81+6×80+1×8−1+2×8−2+5×8−3
= (30.16601563)10(30.16601563)10
It is safe and wise to agree that number system holds its importance for everything which includes
proportion and percentage. Number system plays a crucial role, both in our everyday lives and the
technological world. With its myriad qualities, it simplifies our lives a lot, which has been discussed
as follows:
It enables to keep count of all the things around people. Like how many apples are in the
basket, or the number of milk cartons to be purchased, etc.
It enables the unique and accurate representation of different types of numbers.
Making a phone call is possible only because we have a proper and efficient number
system.
Elevators used in public places also depend upon number systems for their functioning.
Computation of any kind of interest on amounts deposited in banks.
Creation of passwords on computers, security purposes.
Page 27 of
Encrypting important data, by converting figures into another number system to avoid
hacking and misuse of data.
It enables easy conversion of numbers for technical purposes.
The entirety of computer architecture depends upon number systems (octal,
hexadecimal). Every fiber of data gets stored in the computer as a number.
Page 28 of
Description of logic gates
Logic gates are an important concept if you are studying electronics. These are important digital
devices that are mainly based on the Boolean function.
Logic gates are used to carry out logical operations on single or multiple binary inputs and give one
binary output. In simple terms, logic gates are the electronic circuits in a digital system.
AND gate
In the AND gate, the output of an AND gate attains state 1 if and only if all the inputs are in state 1.
A B Y
0 0 0
0 1 0
1 0 0
1 1 1
NAND gate
This basic logic gate is the combination of AND and NOT gates.
Page 29 of
The Boolean expression of the NAND gate is
A Y
0 1
1 0
OR gate
In an OR gate, the output of an OR gate attains state 1 if one or more inputs attain state 1.
A B Y
0 0 0
0 1 1
1 0 1
1 1 1
NOR gate
The NOR gate is a combination OR gate followed by an inverter. Its output is "true" if both inputs are
"false." Otherwise, the output is "false."
Page 30 of
The truth table of a two-input OR basic gate is given as
A B Y
0 0 0
0 1 1
1 0 1
1 1 1
XOR gate
In an XOR gate, the output of a two-input XOR gate attains state 1 if one adds only input and attains
state 1.
A B Y
0 0 0
0 1 1
1 0 1
1 1 0
Page 31 of
Exclusive-NOR Gate (XNOR Gate)
In the XNOR gate, the output is in state 1 when both inputs are the same, that is, both 0 or both 1.
A B Y
0 0 1
0 1 0
1 0 0
1 1 1
The easiest way to learn the function of basic logic gates is explained below.
For AND Gate – If both the inputs are high then the output is also high
For OR Gate – If a minimum of one input is high then the output is High
For XOR Gate – If the minimum one input is high then only the output is high
NAND Gate – If the minimum one input is low then the output is high
NOR Gate – If both the inputs are low then the output is high.
Page 32 of
Applications of Logic Gates
Circuits
According to the first theorem, the complement result of the AND operation is equal to the OR
operation of the complement of that variable. Thus, it is equivalent to the NAND function and is
a negative-OR function proving that (A.B)' = A'+B' and we can show this using the following
table.
0 0 0 1 1 1 1
0 1 0 1 1 0 1
1 0 0 1 0 1 1
1 1 1 0 0 0 0
Page 33 of
De-Morgan's Second Theorem
According to the second theorem, the complement result of the OR operation is equal to the AND
operation of the complement of that variable. Thus, it is the equivalent of the NOR function and is
a negative-AND function proving that (A+B)' = A'.B' and we can show this using the following
truth table.
0 0 0 1 1 1 1
0 1 1 0 1 0 0
1 0 1 0 0 1 0
1 1 1 0 0 0 0
Let's take some examples in which we take some expressions and apply DeMorgan's theorems.
Example 1: (A.B.C)'
(A.B.C)'=A'+B'+C'
Example 2: (A+B+C)'
(A+B+C)'=A'.B'.C
Example 3: ((A+BC')'+D(E+F')')'
For applying the DeMorgan's theorem on this expression, we have to follow the following
expressions:
Page 34 of
1) In complete expression, first, we find those terms on which we can apply the DeMorgan's
theorem and treat each term as a single variable.
So,
3) Next, we use rule number 9, i.e., (A=(A')') for canceling the double bars.
Now, this expression has no term in which we can apply any rule or theorem. So, this is the final
expression.
Page 35 of
Example 3: (AB'.(A + C))'+ A'B.(A + B + C')'
Every Variable has a data type that tells what kind of data is being stored in a variable. There are two
types of data types in JavaScript.
Primitive data types: The predefined data types provided by JavaScript language are known as
primitive data types. Primitive data types are also known as in-built data types.
Page 36 of
Below is a list of Primitive Data Types with proper descriptions and examples:
1. Number: Number data type in javascript can be used to hold decimal values as well as
values without decimals.
2. String: The string data type in javascript represents a sequence of characters that are surrounded
by single or double quotes.
4. Boolean: The boolean data type can accept only two values i.e. true and false.
5. Null: This data type can hold only one possible value that is null.
6. BigInt: This data type can represent numbers greater than 253-1 which helps to perform operations
on large numbers. The number is specified by writing ‘n’ at the end of the value
7. Symbol: This data type is used to create objects which will always be unique. these objects can
be created using Symbol constructor.
Non-primitive data types: The data types that are derived from primitive data types of the JavaScript
language are known as non-primitive data types. It is also known as derived data types or reference
data types.
Below is a list of Non-primitive Data Types with proper descriptions and examples:
When describing objects and their purpose in JavaScript, one can look at the distinction between
properties and methods. Property is the value stored in the hash key, while function is the method
stored there. Properties define it, while methods allow it to do things.
2. Array: With the help of an array, we can store more than one element under a single
name.
Page 37 of
Difference between Primitive vs Non-Primitive:
Primitive Non-Primitive
Non-Primitive data types are created by
Primitive Data types are predefined.
the programmer
JavaScript is a dynamically typed language. It means that a variable doesn’t associate with a type. In
other words, a variable can hold a value of different types. For example:
To get the current type of the value that the variable stores, you use the typeof operator:
Output:
"number"
"boolean"
"string"
Page 38 of
The undefined type
The undefined type is a primitive type that has only one value undefined. By default, when a variable
is declared but not initialized, it is assigned the value of undefined.
let counter;
console.log(counter); // undefined
console.log(typeof counter); // undefinedCode language: JavaScript (javascript)
In this example, the counter is a variable. Since counter hasn’t been initialized, it is assigned the value
undefined. The type of counter is also undefined.
It’s important to note that the typeof operator also returns undefined when you call it on a variable that
hasn’t been declared:
The null type is the second primitive data type that also has only one value null. For example:
The typeof null returns object is a known bug in JavaScript. A proposal to fix this was proposed but
rejected. The reason was the that fix would break a lot of existing sites.
Page 39 of
The number type
JavaScript uses the number type to represent both integer and floating-point numbers.
The following statement declares a variable and initializes its value with an integer:
To represent a floating-point number, you include a decimal point followed by at least one number.
For example:
Note that JavaScript automatically converts a floating-point number into an integer number if the
number appears to be a whole number.
The reason is that Javascript always wants to use less memory since a floating-point value uses twice
as much memory as an integer value. For example:
To get the range of the number type, you use Number.MIN_VALUE and Number.MAX_VALUE.
For example:
console.log(Number.MAX_VALUE); // 1.7976931348623157e+308
console.log(Number.MIN_VALUE); // 5e-324Code language: JavaScript (javascript)
Also, you can use Infinity and -Infinity to represent the infinite number. For example:
NaN stands for Not a Number. It is a special numeric value that indicates an invalid number. For
example, the division of a string by a number returns NaN:.
Page 40 of
console.log('a'/2); // NaN;Code language: JavaScript (javascript)
console.log(NaN/2); // NaN
console.log(NaN == NaN); // falseCode language: JavaScript (javascript)
In JavaScript, a string is a sequence of zero or more characters. A string literal begins and ends with
either a single quote(') or a double quote (").
A string that begins with a double quote must end with a double quote. Likewise, a string that begins
with a single quote must also end with a single quote:
If you want to single quote or double quotes in a literal string, you need to use the backslash to escape
it. For example:
let message = 'I\'m also a valid string'; // use \ to escape the single quote (')Code language: JavaScript
(javascript)
JavaScript strings are immutable. This means that it cannot be modified once created. However, you
can create a new string from an existing string. For example:
Page 41 of
In this example:
Behind the scene, the JavaScript engine creates a new string that holds the new string 'JavaScript
String' and destroys the original strings 'JavaScript' and ' String'.
The following example attempts to change the first character of the string JavaScript:
let s = 'JavaScript';
s[0] = 'j';
console.log(s)Code language: JavaScript (javascript)
But not:
The boolean type has two literal values: true and false in lowercase. The following example declares
two variables that hold the boolean values.
JavaScript allows values of other types to be converted into boolean values of true or
false.
Page 42 of
Application of JavaScript
In JavaScript, an operator is a special symbol used to perform operations on operands (values and
variables). For example, 2 + 3; // 5. Here + is an operator that performs addition, and 2 and 3
are operands.
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’ is called
the operator. JavaScript supports the following types of operators.
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
one.
Arithmetic Operators
1
+ (Addition)
Page 43 of
2
- (Subtraction)
Page 44 of
3
* (Multiplication)
4
/ (Division)
5
% (Modulus)
6
++ (Increment)
7
-- (Decrement)
Note − Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give "a10".
Example
<html>
<body>
Page 45 of
<!--
var a = 33;
var b = 10;
var c = "Test";
var linebreak = "<br />";
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);
document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);
document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);
document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);
document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);
a = ++a;
document.write("++a = ");
result = ++a;
Page 46 of
document.write(result);
document.write(linebreak);
Output
a + b = 43
a - b = 23
a / b = 3.3
a%b=3
a + b + c = 43Test
++a = 35
--b = 8
Set the variables to different values and then try...
Comparison Operators
1
= = (Equal)
Page 47 of
Checks if the value of two operands are equal or not, if yes, then the condition
becomes true.
2
!= (Not Equal)
Checks if the value of two operands are equal or not, if the values are not equal, then
the condition becomes true.
Ex: (A != B) is true.
3
> (Greater than)
Checks if the value of the left operand is greater than the value of the right operand,
if yes, then the condition becomes true.
4
< (Less than)
Checks if the value of the left operand is less than the value of the right operand, if
yes, then the condition becomes true.
5
>= (Greater than or Equal to)
Checks if the value of the left operand is greater than or equal to the value of the
right operand, if yes, then the condition becomes true.
6
<= (Less than or Equal to)
Checks if the value of the left operand is less than or equal to the value of the right
operand, if yes, then the condition becomes true.
Page 48 of
Ex: (A <= B) is true.
Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
document.write("(a == b) => ");
result = (a == b);
document.write(result);
document.write(linebreak);
Page 49 of
document.write(result);
document.write(linebreak);
Output
(a == b) => false
(a < b) => true
(a > b) => false
(a != b) => true
(a >= b) => false
a <= b) => true
Set the variables to different values and different operators and then try...
Logical Operators
1
&& (Logical AND)
If both the operands are non-zero, then the condition becomes true.
Page 50 of
2
|| (Logical OR)
If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.
3
! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the Logical NOT
operator will make it false.
Example
Try the following code to learn how to implement Logical Operators in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var a = true; var b = false;
var linebreak = "<br />";
Page 51 of
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Output
(a && b) => false
(a || b) => true
!(a && b) => true
Set the variables to different values and different operators and then try...
Bitwise Operators
1
& (Bitwise AND)
Ex: (A & B) is 2.
2
| (BitWise OR)
Ex: (A | B) is 3.
3
^ (Bitwise XOR)
Page 52 of
It performs a Boolean exclusive OR operation on each bit of its integer
arguments. Exclusive OR means that either operand one is true or operand two is
true, but not both.
Ex: (A ^ B) is 1.
4
~ (Bitwise Not)
It is a unary operator and operates by reversing all the bits in the operand.
5
<< (Left Shift)
It moves all the bits in its first operand to the left by the number of places specified
in the second operand. New bits are filled with zeros. Shifting a value left by one
position is equivalent to multiplying it by 2, shifting two positions is equivalent to
multiplying by 4, and so on.
Ex: (A << 1) is 4.
6
>> (Right Shift)
Binary Right Shift Operator. The left operand’s value is moved right by the number
of bits specified by the right operand.
Ex: (A >> 1) is 1.
7
>>> (Right shift with Zero)
This operator is just like the >> operator, except that the bits shifted in on the left are
always zero.
Ex: (A >>> 1) is 1.
Example
<html>
Page 53 of
<body>
<script type = "text/javascript">
<!--
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
var linebreak = "<br />";
Page 54 of
document.write(result); document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
(a & b) => 2
(a | b) => 3
(a ^ b) => 1
(~b) => -4
(a << b) => 16
(a >> b) => 0
Set the variables to different values and different operators and then try...
Assignment Operators
1
= (Simple Assignment )
Assigns values from the right side operand to the left side operand
2
+= (Add and Assignment)
It adds the right operand to the left operand and assigns the result to the left operand.
Ex: C += A is equivalent to C = C + A
3
−= (Subtract and Assignment)
Page 55 of
It subtracts the right operand from the left operand and assigns the result to the left
operand.
Ex: C -= A is equivalent to C = C - A
4
*= (Multiply and Assignment)
It multiplies the right operand with the left operand and assigns the result to the left
operand.
Ex: C *= A is equivalent to C = C * A
5
/= (Divide and Assignment)
It divides the left operand with the right operand and assigns the result to the left
operand.
Ex: C /= A is equivalent to C = C / A
6
%= (Modules and Assignment)
It takes modulus using two operands and assigns the result to the left operand.
Ex: C %= A is equivalent to C = C % A
Note − Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=, &=, |= and
^=.
Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 33; var b = 10;
var linebreak = "<br />";
Page 56 of
document.write("Value of a => (a = b) => ");
result = (a = b);
document.write(result);
document.write(linebreak);
Page 57 of
</html>
Output
Value of a => (a = b) => 10
Value of a => (a += b) => 20
Value of a => (a -= b) => 10
Value of a => (a *= b) => 100
Value of a => (a /= b) => 10
Value of a => (a %= b) => 0
Set the variables to different values and different operators and then try...
Miscellaneous Operator
We will discuss two operators here that are quite useful in JavaScript: the conditional operator (? :)
and the typeof operator.
Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and then executes one of
the two given statements depending upon the result of the evaluation.
1
? : (Conditional )
Example
Try the following code to understand how the Conditional Operator works in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10; var b = 20;
var linebreak = "<br />";
Page 58 of
document.write ("((a > b) ? 100 : 200) => "); result = (a > b) ? 100 : 200; document.write(result);
document.write(linebreak);
document.write ("((a < b) ? 100 : 200) => "); result = (a < b) ? 100 : 200; document.write(result); document.write(li
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Output
((a > b) ? 100 : 200) => 200
((a < b) ? 100 : 200) => 100
Set the variables to different values and different operators and then try...
typeof Operator
The typeof operator is a unary operator that is placed before its single operand, which can be of any
type. Its value is a string indicating the data type of the operand.
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number, string, or
boolean value and returns true or false based on the evaluation.
Number "number"
String "string"
Page 59 of
Boolean "boolean"
Object "object"
Function "function"
Undefined "undefined"
Null "object"
Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = "String";
var linebreak = "<br />";
result = (typeof b == "string" ? "B is String" : "B is Numeric"); document.write("Result => ");
document.write(result);
document.write(linebreak);
result = (typeof a == "string" ? "A is String" : "A is Numeric"); document.write("Result => ");
document.write(result); document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
Page 60 of
</body>
</html>
Output
Result => B is String
Result => A is Numeric
Write an algorithm
An algorithm is a procedure or step-by-step instruction for solving a problem. They form the
foundation of writing a program.
Input
Tasks to be preformed
Output expected
1. Sorting algorithms
Javascript provides a rich set of data types and operators that can be used to implement various sorting
algorithms such as bubble sort, insertion sort and quick sort.
These algorithms are useful in many applications because they can be used to sort data of different
sizes and types.
they are:-
(i) Bubble sort: An uncomplicated sorting algorithm that compares nearby components
repeatedly and switches them out if they are out of order.
Page 61 of
3. Move on to the next pair of elements and repeat step 2 until the end of the list is reached.
4. For each item on the list, repeat steps 2 and 3 once more. that is referred to as passes.
5. Repeat steps 2-4 for the entire list. As you repeat the passes, elements will "bubble up" to
their correct position in the sorted list.
6. Once a pass is completed and no swaps are made, the list is sorted, and the algorithm can stop.
7. The final sorted list is returned.
(ii) Insertion sort: a method of sorting that creates a sorted list one individual element at a time
by placing each one in the appropriate spot.
1. Initialize an empty sorted list and an unsorted list of the elements to be sorted.
2. The first member from the unsorted list should be taken and placed in the appropriate
position in the sorted list.
3. Repeat step 2 for each subsequent element in the unsorted list.
4. Compare the current element with the elements in the sorted list, starting with the
element immediately to the left.
5. Swap the two elements if the current element is smaller than the element to its left.
6. If the current element is larger than the element to its left, insert it at its correct position in
the sorted list.
7. Repeat steps 4-6 for each subsequent element in the unsorted list.
8. Once all elements have been processed, the sorted list will contain all elements in the
correct order.
9. The sorting process is complete.
(iii) Selection sort: a method of sorting that consistently starts the sorted listing with the
smallest detail from the unordered listing.
Page 62 of
4. Change the current minimum to the first element of the list whenever it reaches its conclusion.
5. For the remaining unsorted portion of the listing, repeat steps 2-4, but begin with the second
item on the list (as the first element is already sorted).
6. Continue sorting the list in this manner until it is all sorted.
(iv) Quick sort: A divide-and-conquer sorting algorithm that chooses a pivot element and splits the
list into sublists depending on whether the elements are fewer than or more than the pivot. After
that, the sublists are sorted repeatedly until the full list is sorted.
1. Choose a pivot element from the list. This is typically the first element, but it can also be
a random element or the median of the list.
2. Divide the list into two sublists: one containing elements less than the pivot and one
containing elements greater than the pivot.
3. Recursively sort the sublist containing elements less than the pivot using the same process.
4. Use the same procedure to recursively sort the sublist of entries larger than the pivot.
5. Concatenate the sorted sublists with the pivot element in between to form a fully sorted list.
6. Return the fully sorted list.
(v) Merge sort: The divide-and-conquer sort algorithm divides the list into two halves, sorts
each half, and then merges the two halves in sorted order.
Merge-sort Algorithm:
1. Make two sublists out of the list: one with elements below the pivot and one with
elements above the pivot.
2. Produces a new sorted sublist by iteratively merging sublists until only one sublist exists.
This will be your sorted list.
3. Steps to merge two sub-directories:-
4. Create an empty list to hold the sorted elements.
5. Compares the first element of each sublist.
6. Adds the smaller element to the new list and removes it from the parent sublist.
7. Repeat the steps 2 and 3 until a list is completly empty.
Page 63 of
8. Adds the remaining elements from other sublists to a new list.
9. Replaces the merged sublist with the new sorted list.
10. Repeat this process until all sublists are merged into one sorted list.
(vi) Heapsort: A sorting algorithm that sorts elements using a data structure called heap.
1. Build max heap: Starting with the first non-leaf node, compare each node with its child nodes
and replace the nodes with the largest of its children to satisfy the max heap property.
2. Swap root with last element: Swap the root (largest element) with the last element in
the stack.
3. Stack the rest of the elements. Starting from the root, each node is compared with its
children, swapping nodes with their older children until the max heap property is satisfied.
4. Repeat steps 2 and 3 with the newly stacked elements, except for the last element in
the correct position.
5. Repeat this process until only one element remains in the stack. This is now sorted.
6. Heapify Down: Starting from the root node, it compares elements with its children and
swaps with the larger of the two until the max heap property is satisfied.
7. Heapify Up: Start with the last element in the heap, compare it to its parent, and swap it
with the parent to satisfy the max heap property.
(vii) Radix sort: A sorting algorithm that sorts elements based on the digits or digits of their
binary representation.
1. determine how many digits are contained in the input listing's largest element.
2. Initialize a variable, say digit place, to 1, which represents the current digit place.
3. Create an empty list for each possible digit value from 0 to 9.
4. Iterate through the input list and add each element to the appropriate list based on the value
of the current digit place.
5. Concatenate all the lists together to form the new list in the order of the digit lists.
6. Multiply digitPlace by 10 to move to the next digit place.
Page 64 of
7. Repeat steps 4-6 for each digit place until all digits in the largest element have
been considered.
8. The final list will be sorted in ascending order by the digits of the elements.
9. Return the final sorted list.
2. Searching algorithms
Searching Algorithms are designed to check for an element or retrieve an element from any data
structure where it is stored.
They are:-
(i) Linear Search is defined as a sequential search algorithm that starts at one end and goes through
each element of a list until the desired element is found, otherwise the search continues till the end
of the data set.
(ii) Binary Search is defined as a searching algorithm used in a sorted array by repeatedly
dividing the search interval in half. The idea of binary search is to use the information that the
array is sorted and reduce the time complexity to O(log N).
3. Graph algorithms
Javascript's support for pointers and data structures such as arrays and linked lists makes it suitable for
implementing algorithms that manipulate graphs, such as finding the shortest path between two nodes
in a graph.
4. Cryptographic Algorithms
Javascript supports low-level operations and efficient data manipulation, making it ideal for
implementing algorithms used in cryptography, such as data encryption and decryption algorithms.
Efficiency: A good algorithm should perform its task quickly and use minimal resources.
Correctness: It must produce the correct and accurate output for all valid inputs.
Page 65 of
Clarity: The algorithm should be easy to understand and comprehend, making it
maintainable and modifiable.
Scalability: It should handle larger data sets and problem sizes without a significant
decrease in performance.
Reliability: The algorithm should consistently deliver correct results under different
conditions and environments.
Optimality: Striving for the most efficient solution within the given problem constraints.
Robustness: Capable of handling unexpected inputs or errors gracefully without crashing.
Adaptability: Ideally, it can be applied to a range of related problems with
minimal adjustments.
Simplicity: Keeping the algorithm as simple as possible while meeting its
requirements, avoiding unnecessary complexity.
Structured English is the use of the English language with the syntax of structured programming to
communicate the design of a computer program to non-technical users by breaking it down into
logical steps using straightforward English words. Structured English gives aims to get the benefits
of both the programming logic and natural language: program logic helps to attain precision, whilst
natural language helps with the familiarity of the spoken word.
Structured English
Structure English is derived from structured programming language which gives more understandable
and precise description of process. It is based on procedural logic that uses construction and
imperative sentences designed to perform operation for action.
It is best used when sequences and loops in a program must be considered and the
problem needs sequences of actions with decisions.
It does not have strict syntax rule. It expresses all logic in terms of sequential
decision structures and iterations.
Page 66 of
Give 5% Discount
else
if purchase amount >=10,000
then
if the customer is a regular customer
then Give 5% Discount
else No Discount
end if
else No Discount
end if
end if
Following are the algorithm of the sum and the average of three numbers is given below.
Explanation:
Step 1: Start
Step 2: Read the three number suppose "a","b","c" form the user.
Step 4 : sum=a+b+c;
Step 5: Avg=sum/3
Step 7: End.
The idea is to use the compound expression where each number is compared with the other two to find
out which one is the maximum of them.
Page 67 of
Algorithm
1. Definition
Sequence, the order that commands are executed by a computer, allows us to carry out tasks that
have multiple steps.
In programming, sequence is a basic algorithm: A set of logical steps carried out in order. Computers
need instructions in the form of an algorithm in order to complete a desired task, and this algorithm
must have the correct order of steps, or sequence.
2. Selection/conditional structures
Page 68 of
A CONDITIONAL is a type of step in an algorithm where a decision must be made.
Computers follow logical instructions and they need to know how to handle different
decisions so that programs can proceed no matter what the outcome of those
selections may be.
a. IF-THEN-ELSE CONDITIONALS
One of the first things that programmers learn is how to use IF-THEN-ELSE statements.
Every programming language has some version of these. The syntax and exact usage may be
different but they all accomplish the same thing, which is to allow for program execution
based on conditionals. The basic flow is: If some condition is true then do this, otherwise
do that.
Complex conditional statements can have more than just two choices. As humans, the way we
make decisions when we have several options to choose from is very different than
computers. We are able to select one item out of a group of choices, however a computer
program must proceed by making binary decisions, meaning that it can only select between
two things at a time. Even the most complex conditional statements boil down to a series of
binary choices.
Page 69 of
b. SWITCH AND CASE CONDITIONALS
The switch statement is used to allow you to perform different actions based on different
conditions. In some languages this was a common structure for conditional execution that makes
it easier for a program to execute one of several cases depending on the value of the expression at
the switch.
Page 70 of
Pseudocode is an informal way of programming description that does not require any strict
programming language syntax or underlying technology considerations. It is used for creating an
outline or a rough draft of a program. Pseudocode summarizes a program’s flow, but excludes
underlying details.
• Variables:
• Assignment:
• Input/output:
• Selection:
• Repetition:
Advantages of pseudocode –
Page 71 of
Examples
1: Write pseudo code that reads two numbers and multiplies them together and print out their product.
2: Write pseudo code that tells a user that the number they entered is not a 5 or a 6.
3: Write pseudo code that performs the following: Ask a user to enter a number. If the number is
between 0 and 10, write the word blue. If the number is between 10 and 20, write the word red. if the
number is between 20 and 30, write the word green. If it is any other number, write that it is not a
correct color option.
4: Write pseudo code to print all multiples of 5 between 1 and 100 (including both 1 and
100). 5: Write pseudo code that will count all the even numbers up to a user defined stopping
c) Find the smallest (minimum) and largest (maximum) of the five entered numbers.
d) Write out the results found from steps b and c with a message describing what they are.
Homework
1: Write pseudo code that reads in three numbers and writes them all in sorted order.
2: Write pseudo code that will calculate a running sum. A user will enter numbers that will be
added to the sum and when a negative number is encountered, stop adding numbers and write out
the final result.
Design of Flowchart
Page 72 of
When to Use a Flowchart
Materials needed: Sticky notes or cards, a large piece of flipchart paper or newsprint, and marking
pens.
1. Define the process to be diagrammed. Write its title at the top of the work surface.
2. Discuss and decide on the boundaries of your process: Where or when does the process
start? Where or when does it end? Discuss and decide on the level of detail to be included in
the diagram.
3. Brainstorm the activities that take place. Write each on a card or sticky note.
4. Arrange the activities in proper sequence.
5. When all activities are included and everyone agrees that the sequence is correct, draw
arrows to show the flow of the process.
6. Review the flowchart with others involved in the process (workers, supervisors,
suppliers, customers) to see if they agree that the process is drawn accurately.
Flowchart Symbols
Here is a chart for some of the common symbols used in drawing flowcharts.
Page 73 of
Process Indicates processes like mathematical operations.
Flowchart can have only one start and one stop symbol
On-page connectors are referenced using numbers
Off-page connectors are referenced using alphabets
General flow of processes is top to bottom or left to right
Arrows should not cross each other
Example Flowcharts
Page 74 of
Here is a flowchart to calculate the average of two numbers.
Page 75 of
https://www.tutorialspoint.com/programming_methodologies/programming_methodologies_flowchart
_elements.htm
1. Selection/conditional structures
Conditional statements help you to make a decision based on certain conditions. Very often when
you write code, you want to perform different actions for different decisions. You can use
conditional statements in your code to do this. In all programming languages we have the following
conditional statements:
b. If/else statement
c. Nested if statement
d. If/Else If statement
Syntax
Start
If (condition) then
Instructions
End if
End
Use if/else to specify a block of code to be executed, if the same condition is false
Syntax
Start
Page 76 of
If (condition) then
Instructions
Else
Instructions
End if
End
Use else/if to specify a new condition to test, if the first condition is false.
Syntax
Start
If (condition) then
Instructions
Instructions
Instructions
Else [optional]
Instructions
End if
End
Page 77 of
1.4. NESTED IF statement
A NESTED IF is an IF statement that is the target of another if statement. Nested if statements means
an IF statement inside another IF statement.
Syntax
Start
If (condition)
If (condition) then
Instructions
Else
Instructions
End if
Else [optional]
Instructions
End if
End
Page 78 of
1.5. Sequence structures
A sequential statement or switch case statement or simply switch statement tests the value of a
variable and compares it with multiple cases. Once the case match is found, a block of statements
associated with that particular case is executed.
Each case in a block of a switch has a different name which is referred to as an identifier. The value
provided by the user or initialized is compared with all the cases inside the switch block until the
match is found.
Syntax
case value-1:
Block-1;
Page 79 of
Break; case
value-2:
Block-2;
Break; case
value-n:
Block-n;
Break;
default:
Block-1;
Break;
Statement-x;
Page 80 of
2. Looping/iterating structures
A loop is a sequence that gets executed several times. A complete execution of a sequence is called
an iteration of the loop.
A for-loop has two parts: a header specifying the iteration, and a body which is executed once per
iteration. The header often declares an explicit loop counter or loop variable, which allows the body
to know which iteration is being executed. For-loops are typically used when the number of iterations
is known before entering the loop.
The while construct consists of a block of code and a condition/expression. The condition/expression
is evaluated, and if the condition/expression is true, the code within the block is executed. This
repeats until the condition/expression becomes false.
Because the while loop checks the condition/expression before the block is executed, the control
structure is often also known as a pre-test loop.
Page 81 of
2.3. DO WHILE loop statement
In most computer programming languages, a do while loop is a control flow statement that executes a
block of code at least once, and then repeatedly executes the block, or not, depending on a given
Boolean condition at the end of the block.
First, the code within the block is executed, and then the condition is evaluated. If the condition is
true the code within the block is executed again. This repeats until the condition becomes false.
Because do while loops check the condition after the block is executed, the control structure is often
also known as a post-test loop.
Syntax in JavaScript
Starting value; do
while (testExpression);
Page 82 of
statement(s);
initialization;
while (condition1)
statement(s);
while (condition2)
statement(s);
Page 83 of
... ... ...
} ... ... ...
do
statement(s); do
statement(s);
Page 84 of
}while (condition2);
}while (condition1);
Page 85 of
Learning outcome 2: Apply Data Structure
2.1 Data structure concepts are clearly identified based on intended use.
Identification of data structure concepts
Page 86 of
Data Structure is a way of collecting and organizing data in such a way that we can perform
operations on these data in an effective way. Data Structures is about rendering data elements in
terms of some relationship, for better organization and storage.
A data structure is a technique of storing and organizing the data in such a way that the data can be
utilized in an efficient manner.
Example: Library is composed of elements (books) to access a particular book requires knowledge of
the arrangement of the books.
2.1.1. Importance of data structures
The data structures have the following importance for programming:
• Data structures study how data are stored in a computer so that operations can be
implemented efficiently
• Data structures are especially important when there is a large amount of information
to deal with.
• Data structures are conceptual and concrete ways to organize data for efficient
storage and manipulation
Identification of data structure concepts
Definition of Data structures: A data structure is a specialized format for organizing, processing,
retrieving and storing data.
Page 87 of
Linear data structure: Data structure in which data elements are arranged sequentially or linearly,
where each element is attached to its previous and next adjacent elements, is called a linear data
structure.
Examples of linear data structures are array, stack, queue, linked list, etc.
Static data structure: Static data structure has a fixed memory size. It is
easier to access the elements in a static data structure.
An example of this data structure is an array.
Dynamic data structure: In the dynamic data structure, the size is not fixed.
It can be randomly updated during the runtime which may be considered
efficient concerning the memory (space) complexity of the code.
Examples of this data structure are queue, stack, etc.
The types of linear data structures are Array, Queue, Stack, Linked List.
Array: An array consists of data elements of the same data type. For example, if we want to
store the roll numbers of 10 students, so instead of creating 10 integer type variables, we
will create an array having size 10.
Therefore, we can say that an array saves a lot of memory and reduces the length of the code.
Stack: It is linear data structure that uses the LIFO (Last in First Out) rule in which the data
added last will be removed first. The addition of data element in a stack is known as a push
operation, and the deletion of data element from the list is known as pop operation.
Page 88 of
Queue: It is a data structure that uses the FIFO (First In First Out). In this rule, the
element which is added first will be removed first.
There are two terms used in the queue front and rear. The insertion operation performed at
the back end is known enqueue, and the deletion operation performed at the front end is
known as dequeue.
Linked List: It is a collection of nodes that are made up of two parts, data element and
reference to the next node in the sequence.
Non-linear data structure: Data structures where data elements are not placed sequentially or
linearly are called non-linear data structures. In a non-linear data structure, we can’t traverse all the
elements in a single run only.
Examples of non-linear data structures are trees and graphs.
Trees and Graphs are the types of linear non- data structure.
o Tree
It is a non-linear data structure that consists of various linked nodes. It has a hierarchical tree structure
that forms a parent-child relationship. The diagrammatic representation of a tree data structure is
shown below:
Page 89 of
For example, the posts of employees are arranged in a tree data structure like managers, officers,
clerk. In the above figure, A represents a manager, B and C represent the officers, and other
nodes represent the clerks.
o Graph
A graph is a non-linear data structure that has a finite number of vertices and edges, and these
edges are used to connect the vertices. The vertices are used to store the data elements, while the
edges represent the relationship between the vertices. A graph is used in various real-world
problems like telephone networks, circuit networks, social networks like LinkedIn, Facebook. In
the case of facebook, a single user can be considered as a node, and the connection of a user with
others is known as edges.
The structure of the data and the synthesis of the algorithm are relative to each other.
Data presentation must be easy to understand so the developer, as well as the user, can
make an efficient implementation of the operation.
Page 90 of
Data structures provide an easy way of organizing, retrieving, managing, and storing data.
Here is a list of the needs for data.
List representation
What is a List in
JavaScript?
In JavaScript, a 'List' is a synonym for an 'Array'. For beginners, think of an array as a list, like a
shopping list. This list has slots where you put the items you want to buy. In JavaScript, these
slots are called 'indices' and the items in the list are called 'elements'.
The elements in an array can be anything: numbers, strings, boolean values, other arrays, and
even objects. In JavaScript, arrays are zero-indexed. This means that the first slot in the array is
not number 1, but number 0. Here's an example of an array:
The elements in an array can be anything: numbers, strings, boolean values, other arrays, and
even objects. In JavaScript, arrays are zero-indexed. This means that the first slot in the array is
not number 1, but number 0. Here's an example of an array:
Page 91 of
In this array, "apple" is at index 0, "banana" is at index 1, and so on.
Page 92 of
Accessing Elements
Modifying Elements
You can change an element in an array by accessing it with its index and assigning a new value.
For example:
fruits[1] = "blueberry";
console.log(fruits); // Outputs: ["apple", "blueberry", "cherry", "date"]
Array Length
The length of an array is the number of elements in it. You can get the length of an array using
the length property:
console.log(fruits.length); // Outputs: 4
push: Adds one or more elements to the end of an array, and returns the new length of
the array.
fruits.push("elderberry");
console.log(fruits); // Outputs: ["apple", "blueberry", "cherry", "date", "elderberry"]
pop: Removes the last element from an array and returns that element.
unshift: Adds one or more elements to the beginning of an array, and returns the
new length of the array.
Page 93 of
fruits.unshift("avocado");
console.log(fruits); // Outputs: ["avocado", "apple", "blueberry", "cherry", "date"]
shift: Removes the first element from an array and returns that
You can use a for loop to iterate over the elements in an array:
apple
blueberry
cherry
date
In this representation, we use two types of nodes one for representing the node with data called
'data node' and another for representing only references called 'reference node'. We start with a
'data node' from the root node in the tree. Then it is linked to an internal node through a 'reference
node' which is further linked to any other node directly. This process repeats for all the nodes in
the tree.
The above example tree can be represented using List representation as follows...
Page 94 of
List operations
List operators (JavaScript)
Operation Description
Usage
A list means a multi-value variable such as an array.
A list operation processes the corresponding elements of two lists, or each element of one list and
a scalar value. The return value is a list. If two list operands are not the same length, the last
element of the shorter list fills out the operation.
Examples
This example adds the corresponding elements of two arrays.
function p(stuff) {
Page 95 of
a = new Array(1, 2, 3);
0.3); c = a + b;
p(c); // <<<1.1>>>,<<<2.2>>>,<<<3.3>>>
This example adds the corresponding elements of two arrays. The first array is shorter so its last
element fills out the operation.
function p(stuff) {
c = a + b;
p(c); // <<<1.1>>>,<<<2.2>>>,<<<3.3>>>,<<<3.4>>>,<<<3.5>>>
This example adds a scalar value to each element of an array.
function p(stuff) {
a = new Array(1, 2,
3); c = a + 0.01;
p(c); // <<<1.01>>>,<<<2.01>>>,<<<3.01>>>
Data Structure
The data structure is a particular way of organizing and storing data in a computer so that it can
be accessed and modified efficiently. It is a collection of data values, the relationships among
them, and the functions or operations that can be applied to the data.
Arrays, Linked List, Stack, Queue, etc., are some examples of Data Structures that are universally
used in almost every realm of Computer Science i.e. Operating systems, Compiler Design,
Artificial intelligence, Graphics, and a lot more.
Page 96 of
Important terms used in Data Structure:
Data: Elementary value or the collection of values. Example: Name and id of the
employee are the data about the employee.
Group Items: Data items with subordinate data items. Example: The name of the
employee can have the first name and the last name.
Record: The collection of various data items. Example: Name, address, and experience
of the employee can be grouped together to form the record for the employee.
File: Collection of various records of one type of entity.
Attribute and Entity: An entity can be defined as the class of certain objects, containing
various attributes, where each attribute represents the particular property of that entity.
Field: A single elementary unit of information representing the attribute of an entity.
Complexed applications and an increase in the amount of data can result in below:
Processor speed: High-speed processing is a must to handle a large amount of data. Still,
the processor may fail to deal with such a large amount of data, because the data is
increasing day by day to the billions of files per entity.
Data Search: An inventory can have hundreds of items in a store, which simply
means that an application needs to traverse hundreds of items every time to search for
a particular item. This results in slowing down the search process.
Multiple requests: Even a very large server can fail if thousands of users are searching
the data simultaneously on a web server. The data structures are used to solve any such
problems. Thus, all the items are not required to be searched and the required data can
be searched instantly if the data is organized to form a data structure in such a way.
Page 97 of
Reusability: After the implementation of a particular data structure, we can use it at any
other place. Thus, the data structures are reusable. Compiling the implementation of
data structures into libraries that can be used by different clients, serves this purpose.
Abstraction: The ADT (abstract data type) provides a level of abstraction. The data
structure is specified by ADT. The client program does not get into the
implementation details and uses the data structure through the interface only.
An abstract data type is an abstraction of a data structure that provides only the
interface to which the data structure must adhere. The interface does not give any
specific details about something should be implemented or in what programming
language.
In other words, we can say that abstract data types are the entities that are
definitions of data and operations but do not have implementation details. In this
case, we know the data that we are storing and the operations that can be
performed on the data, but we don't know about the implementation details.
Searching techniques
Searching in data structure refers to the process of finding the required information from a
collection of items stored as elements in the computer memory.
These sets of items are in different forms, such as an array, linked list, graph, or tree. Another
way to define searching in the data structures is by locating the desired element of specific
characteristics in a collection of items.
Searching in the data structure can be done by applying searching algorithms to check for or
extract an element from any form of stored data structure.
These algorithms are classified according to the type of search operation they perform, such as:
Sequential search
The list or array of elements is traversed sequentially while checking every component of
the set. For example – Linear Search.
Interval Search
The interval search includes algorithms that are explicitly designed for searching in sorted
Page 98 of
data structures. In terms of efficiency, these algorithms are far better than linear search
algorithms. Example- Logarithmic Search, Binary search.
The linear search algorithm iteratively searches all elements of the array. It has the best execution
time of one and the worst execution time of n, where n is the total number of items in the search
array.
It is the simplest search algorithm in data structure and checks each item in the set of elements
until it matches the searched element till the end of data collection. When the given data is
unsorted, a linear search algorithm is preferred over other search algorithms.
Space Complexity
Since linear search uses no extra space, its space complexity is O(n), where n is the number of
elements in an array.
Time Complexity
Best-case complexity = O(0) occurs when the searched item is present at the first
element in the search array.
Worst-case complexity = O(n) occurs when the required element is at the tail of the
array or not present at all.
Average- case complexity = average case occurs when the item to be searched is
in somewhere middle of the Array.
Page 99 of
45, 78, 15, 67, 08, 29, 39, 40, 12, 99
To find ‘29’ in an array of 10 elements given above, as we know linear search algorithm will
check each element sequentially till its pointer points to 29 in the memory space. It takes O(6)
time to find 29 in an array. To find 15, in the above array, it takes O(3), whereas, for 39, it
requires O(7) time.
This algorithm locates specific items by comparing the middlemost items in the data collection.
When a match is found, it returns the index of the item. When the middle item is greater than the
search item, it looks for a central item of the left sub-array. If, on the other hand, the middle item
is smaller than the search item, it explores for the middle item in the right sub-array. It keeps
looking for an item until it finds it or the size of the sub-arrays reaches zero.
Binary search needs sorted order of items of the array. It works faster than a linear search
algorithm. The binary search uses the divide and conquers principle.
Page 100 of
if A[midPoint] x
set upperBound = midPoint - 1
if A[midPoint] = x
EXIT: x found at location midPoint
end while
end procedure
Example,
Binary search reduces the time to half as the comparison count is reduced significantly as
compared to the linear search algorithm.
Space complexity refers to the amount of memory used by an algorithm or a program during its
execution.
Time complexity, on the other hand, refers to the amount of time it takes for an algorithm or
program to complete its execution.
Classification of Sorting Algorithms
Sorting is an algorithm which arranges the elements of a given list in a particular order
[ascending or descending].
1. By number of comparisons:
Comparison-based sorting algorithms check the elements of the list by key
Page 101 of
comparison operation and need at least O(n log n) comparisons for most inputs. In
this method, algorithms are classified based on the number of comparisons. For
comparison based sorting algorithms, best case behavior is O(n log n) and worst
case behavior is O(n2). For example – Quick Sort, Bubble Sort, Insertion Sort etc.
2. By Number of Swaps:
In this method, sorting algorithms are categorized by the number of swaps
(interchanging of position of two numbers, also called inversion).
3. By Memory Usage:
Some sorting algorithms are “in place” and they need O(1) or O(log n) memory to
create auxiliary locations for sorting the data temporarily.
4. By Recursion:
Sorting algorithms are either recursive (for example – quick sort) or non-recursive
(for example – selection sort, and insertion sort), and there are some algorithms
which use both (for example – merge sort).
5. By Stability:
Sorting algorithm is stable if two elements with equal values appear in the same
order in output as it was in the input. The stability of a sorting algorithm can be
checked with how it treats equal elements. Stable algorithms preserve the relative
order of equal elements, while unstable sorting algorithms don’t. In other words,
stable sorting maintains the position of two equals elements similar to one another.
For example – Insertion Sort, Bubble Sort , and Radix Sort.
6. By Adaptability:
In a few sorting algorithms, the complexity changes based on pre-sorted input i.e.
pre-sorted array of the input affects the running time. The algorithms that take this
adaptability into account are known to be adaptive algorithms. For example – Quick
sort is an adaptive sorting algorithm because the time complexity of Quick sort
depends on the initial input sequence. If input is already sorted then time
complexity becomes O(n^2) and if input sequence is not sorted then time
complexity becomes O(n logn).
Some adaptive sorting algorithms are: Bubble Sort, Insertion Sort and Quick Sort.
On the other hand, some non-adaptive sorting algorithms are: Selection Sort, Merge
Sort, and Heap Sort.
7. Internal Sorting:
Sorting algorithms that use main memory exclusively during the sort are called
internal sorting algorithms. This kind of algorithm assumes high-speed random
Page 102 of
access to all memory. Some of the common algorithms that use this sorting feature
are: Bubble Sort, Insertion Sort., and Quick Sort.
8. External Sorting:
Sorting algorithms that use external memory, during the sorting come under this
category.
They are comparatively slower than internal sorting algorithms. For example, merge
sort algorithm. It sorts chunks that each fit in RAM, then merges the sorted chunks
together.
Sorting techniques
Page 103 of
In the following sections, we list some important scientific applications where sorting
algorithms are used
When you have hundreds of datasets you want to print, you might want to arrange
them in some way.
Sorting algorithm is used to arrange the elements of a list in a certain order (either
ascending or descending).
Searching any element in a huge data set becomes easy. We can use Binary search
method for search if we have sorted data. So, Sorting become important here.
They can be used in software and in conceptual problems to solve more advanced
problems.
Some of the most common sorting algorithms are:
Page 104 of
Below are some of the most common sorting algorithms:
1. Selection sort
Selection sort is another sorting technique in which we find the minimum element in every
iteration and place it in the array beginning from the first index. Thus, a selection sort also gets
divided into a sorted and unsorted subarray.
Lets consider the following array as an example: arr[] = {64, 25, 12, 22, 11}
First pass:
For the first position in the sorted array, the whole array is traversed from index 0 to 4
sequentially. The first position where 64 is stored presently, after traversing whole array it is
clear that 11 is the lowest value.
64 25 12 22 11
Thus, replace 64 with 11. After one iteration 11, which happens to be the least value in the
array, tends to appear in the first position of the sorted list.
11 25 12 22 64
Second Pass:
For the second position, where 25 is present, again traverse the rest of the array in a sequential
manner.
11 25 12 22 64
After traversing, we found that 12 is the second lowest value in the array and it should appear
at the second place in the array, thus swap these values.
11 12 25 22 64
Third Pass:
Now, for third place, where 25 is present again traverse the rest of the array and find the third
least value present in the array.
Page 105 of
11 12 25 22 64
While traversing, 22 came out to be the third least value and it should appear at the third place
in the array, thus swap 22 with element present at third position.
11 12 22 25 64
Fourth pass:
Similarly, for fourth position traverse the rest of the array and find the fourth least element in
the array
As 25 is the 4th lowest value hence, it will place at the fourth position.
11 12 22 25 64
Fifth Pass:
At last the largest value present in the array automatically get placed at the last position in the
array
The resulted array is the sorted array.
11 12 22 25 64
2. Bubble sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent
elements if they are in the wrong order. This algorithm is not suitable for large data sets as its
average and worst-case time complexity is quite high.
First Pass:
Bubble sort starts with very first two elements, comparing them to check which one is greater.
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5
> 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
Page 106 of
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm
does not swap them.
Second Pass:
Now, during second iteration it should look like this:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Third Pass:
Now, the array is already sorted, but our algorithm does not know if it is completed.
The algorithm needs one whole pass without any swap to know it is sorted.
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Illustration:
Page 107 of
3. Insertion Sort
Insertion sort is a simple sorting algorithm that works similarly to the way you sort playing
cards in your hands. The array is virtually split into a sorted and an unsorted part. Values from
the unsorted part are picked and placed at the correct position in the sorted part.
12 11 13 5 6
First Pass:
Initially, the first two elements of the array are compared in insertion sort.
12 11 13 5 6
Here, 12 is greater than 11 hence they are not in the ascending order and 12 is not at
its correct position. Thus, swap 11 and 12.
So, for now 11 is stored in a sorted sub-array.
11 12 13 5 6
Second Pass:
Now, move to the next two elements and compare them
11 12 13 5 6
Here, 13 is greater than 12, thus both elements seem to be in ascending order,
hence, no swapping will occur. 12 also stored in a sorted sub-array along with 11
Third Pass:
Now, two elements are present in the sorted sub-array which are 11 and 12
Moving forward to the next two elements which are 13 and 5
11 12 13 5 6
Both 5 and 13 are not present at their correct place so swap them
Page 108 of
11 12 5 13 6
After swapping, elements 12 and 5 are not sorted, thus swap again
11 5 12 13 6
5 11 12 13 6
5 11 12 13 6
Clearly, they are not sorted, thus perform swap between both
5 11 12 6 13
5 11 6 12 13
5 6 11 12 13
Page 109 of
4. Merge Sort
The Merge Sort algorithm is a sorting algorithm that is based on the Divide and
Conquers paradigm. In this algorithm, the array is initially divided into two equal halves and
then they are combined in a sorted manner.
The merge sort algorithm is an implementation of the divide and conquers technique. Thus, it
gets completed in three steps:
1. Divide: In this step, the array/list divides itself recursively into sub-arrays until the
base case is reached.
2. Conquer: Here, the sub-arrays are sorted using recursion.
Page 110 of
3. Combine: This step makes use of the merge( ) function to combine the sub-arrays
into the final sorted array.
To know the functioning of merge sort, let’s consider an array arr[] = {38, 27, 43, 3, 9, 82, 10}
At first, check if the left index of array is less than the right index, if yes then calculate its mid
point
Now, as we already know that merge sort first divides the whole array iteratively into equal
halves, unless the atomic values are achieved.
Here, we see that an array of 7 items is divided into two arrays of size 4 and 3 respectively.
Now, again find that is left index is less than the right index for both arrays, if found yes, then
again calculate mid points for both the arrays.
Page 111 of
Now, further divide these two arrays into further halves, until the atomic units of the array is
reached and further division is not possible.
After dividing the array into smallest units, start merging the elements again based on
comparison of size of elements
Firstly, compare the element for each list and then combine them into another list in a sorted
manner.
Page 112 of
After the final merging, the list looks like this:
5. Quick sort
Quicksort is a sorting algorithm based on the divide and conquer approach where an array is
divided into subarrays by selecting a pivot element (element selected from the array).
1. While dividing the array, the pivot element should be positioned in such a way that
elements less than the pivot are kept on the left side, and elements greater than the
pivot is on the right side of the pivot.
2. The left and right subarrays are also divided using the same approach. This process
continues until each subarray contains a single element.
Page 113 of
3. At this point, elements are already sorted. Finally, elements are combined to form a
sorted array.
To know the functioning of Quick sort, let’s consider an array arr[] = {10, 80, 30, 90, 40, 50,
70}
Indexes: 0 1 2 3 4 5 6
low = 0, high = 6, pivot = arr[h] = 70
Initialize index of smaller element, i = -1
Step1
Page 114 of
Step2
Step3
Page 115 of
Step 4
j = 5 : Since arr[j] <= pivot, do i++ and swap arr[i] with arr[j]
i=3
arr[] = {10, 30, 40, 50, 80, 90, 70} // 90 and 50 Swapped
Step 5
Page 116 of
Step 6
Now 70 is at its correct place. All elements smaller than 70 are before it and all
elements greater than 70 are after it.
Since quick sort is a recursive function, we call the partition function again at left
and right partitions
Step 7
Page 117 of
Step 8
6. Heap sort
Heap sort is a comparison-based sorting technique based on Binary Heap data structure. It is
similar to the selection sort where we first find the minimum element and place the minimum
element at the beginning. Repeat the same process for the remaining elements.
Build Complete Binary Tree: Build a complete binary tree from the array.
Page 118 of
Transform into max heap: After that, the task is to construct a tree from that unsorted array
and try to convert it into max heap.
To transform a heap into a max-heap, the parent node should always be greater than
or equal to the child nodes
Here, in this example, as the parent node 4 is smaller than the child
node 10, thus, swap them to build a max-heap.
Transform it into a max heap
Now, as seen, 4 as a parent is smaller than the child 5, thus swap both of these again
and the resulted heap and array should be like this:
Page 119 of
Perform heap sort: Remove the maximum element in each step (i.e., move it to the end
position and remove that) and then consider the remaining elements and transform it into a max
heap.
Delete the root element (10) from the max heap. In order to delete this node, try to
swap it with the last node, i.e. (1). After removing the root element, again heapify it
to convert it into max heap.
Resulted heap and array should look like this:
Page 120 of
Repeat the above steps and it will look like the following:
Page 121 of
Now when the root is removed once again it is sorted. and the sorted array will be
like arr[] = {1, 3, 4, 5, 10}.
7. Counting sort
Counting sort is a sorting technique based on keys between a specific range. It works by
counting the number of objects having distinct key values (kind of hashing). Then do some
arithmetic to calculate the position of each object in the output sequence.
Page 122 of
Now, store the count of each unique element in the count array
If any element repeats itself, simply increase its count.
Here, the count of each unique element in the count array is as shown below:
Index: 01 2 3 4 5 6 7 8 9
Count: 0 2 2 0 1 1 0 1 0 0
Modify the count array such that each element at each index stores the sum of
previous counts.
Page 123 of
Index: 01 2 3 4 5 6 7 8 9
Count: 02 4 4 5 6 6 7 7 7
The modified count array indicates the position of each object in the output
sequence.
Find the index of each element of the original array in the count array. This gives
the cumulative count.
Page 124 of
Count: 0024456677
Output each object from the input sequence followed by increasing its count by 1.
Process the input data: 1, 4, 1, 2, 7, 5, 2. Position of 1 is 0.
Put data 1 at index 0 in output. Increase count by 1 to place next data 1 at an index
1 greater than this index.
After placing each element at its correct position, decrease its count by one.
Application of linear data structures and their operations
Page 125 of
Sequential Organization: In linear data structures, data elements are arranged
sequentially, one after the other. Each element has a unique predecessor (except for
the first element) and a unique successor (except for the last element)
Order Preservation: The order in which elements are added to the data structure is
preserved. This means that the first element added will be the first one to be
accessed or removed, and the last element added will be the last one to be accessed
or removed.
Fixed or Dynamic Size: Linear data structures can have either fixed or dynamic
sizes. Arrays typically have a fixed size when they are created, while other
structures like linked lists, stacks, and queues can dynamically grow or shrink as
elements are added or removed.
Efficient Access: Accessing elements within a linear data structure is typically
efficient. For example, arrays offer constant-time access to elements using their
index.
Linear data structures are commonly used for organising and manipulating data in a sequential
fashion. Some of the most common linear data structures include:
Arrays: A collection of elements stored in contiguous memory locations.
Linked Lists: A collection of nodes, each containing an element and a reference to
the next node.
Stacks: A collection of elements with Last-In-First-Out (LIFO) order.
Queues: A collection of elements with First-In-First-Out (FIFO) order.
1. Array
An array is a collection of items of same data type stored at contiguous memory locations.
Array
Page 126 of
Contiguous Memory Allocation: In most programming languages, elements in an
array are stored in contiguous (adjacent) memory locations.
Zero-Based Indexing: In many programming languages, arrays use zero-based
indexing, which means that the first element is accessed with an index of 0, the
second with an index of 1, and so on.
Random Access: Arrays provide constant-time (O(1)) access to elements. This
means that regardless of the size of the array, it takes the same amount of time to
access any element based on its index.
Types of arrays:
One-Dimensional Array: This is the simplest form of an array, which consists of a
single row of elements, all of the same data type. Elements in a 1D array are
accessed using a single index.
One-Dimensional Array
Page 127 of
Two-Dimensional Array:
Multi-Dimensional Array: Arrays can have more than two dimensions, leading to
multi-dimensional arrays. These are used when data needs to be organized in a
multi-dimensional grid.
Multi-Dimensional Array
Page 128 of
Common Features of Linked List:
Node: Each element in a linked list is represented by a node, which contains two
components:
Data: The actual data or value associated with the element.
Next Pointer(or Link): A reference or pointer to the next node in the
linked list.
Head: The first node in a linked list is called the “head.” It serves as the starting
point for traversing the list.
Tail: The last node in a linked list is called the “tail.”
Types of Linked Lists:
Singly Linked List: In this type of linked list, every node stores the address or
reference of the next node in the list and the last node has the next address or
reference as NULL. For example: 1->2->3->4->NULL
Doubly Linked Lists: In a doubly linked list, each node has two pointers: one
pointing to the next node and one pointing to the previous node. This bidirectional
structure allows for efficient traversal in both directions.
Page 129 of
Circular Linked Lists: A circular linked list is a type of linked list in which the
first and the last nodes are also connected to each other to form a circle, there is no
NULL at the end.
Page 130 of
Stack Data structure
Types of Stacks:
Fixed Size Stack: As the name suggests, a fixed size stack has a fixed size and
cannot grow or shrink dynamically. If the stack is full and an attempt is made to add
an element to it, an overflow error occurs. If the stack is empty and an attempt is
made to remove an element from it, an underflow error occurs.
Dynamic Size Stack: A dynamic size stack can grow or shrink dynamically. When
the stack is full, it automatically increases its size to accommodate the new element,
and when the stack is empty, it decreases its size. This type of stack is implemented
using a linked list, as it allows for easy resizing of the stack.
Stack Operations:
push(): When this operation is performed, an element is inserted into the stack.
pop(): When this operation is performed, an element is removed from the top of the
stack and is returned.
top(): This operation will return the last inserted element that is at the top without
removing it.
size(): This operation will return the size of the stack i.e. the total number of
elements present in the stack.
isEmpty(): This operation indicates whether the stack is empty or not.
4. Queue Data Structure
A queue is a linear data structure that follows the First-In-First-Out (FIFO) principle. In a
queue, the first element added is the first one to be removed.
Page 131 of
Types of Queue:
Input Restricted Queue: This is a simple queue. In this type of queue, the input
can be taken from only one end but deletion can be done from any of the ends.
Output Restricted Queue: This is also a simple queue. In this type of queue, the
input can be taken from both ends but deletion can be done from only one end.
Circular Queue: This is a special type of queue where the last position is
connected back to the first position. Here also the operations are performed in FIFO
order.
Double-Ended Queue (Dequeue): In a double-ended queue the insertion and
deletion operations, both can be performed from both ends.
Priority Queue: A priority queue is a special queue where the elements are
accessed based on the priority assigned to them.
Queue Operations:
Enqueue(): Adds (or stores) an element to the end of the queue..
Dequeue(): Removal of elements from the queue.
Peek() or front(): Acquires the data element available at the front node of the
queue without deleting it.
rear(): This operation returns the element at the rear end without removing it.
isFull(): Validates if the queue is full.
isNull(): Checks if the queue is empty.
Advantages of Linear Data Structures
Efficient data access: Elements can be easily accessed by their position in the
sequence.
Dynamic sizing: Linear data structures can dynamically adjust their size as
elements are added or removed.
Ease of implementation: Linear data structures can be easily implemented using
arrays or linked lists.
Versatility: Linear data structures can be used in various applications, such as
searching, sorting, and manipulation of data.
Simple algorithms: Many algorithms used in linear data structures are simple and
straightforward.
Disadvantages of Linear Data Structures
Limited data access: Accessing elements not stored at the end or the beginning of
the sequence can be time-consuming.
Memory overhead: Maintaining the links between elements in linked lists and
pointers in stacks and queues can consume additional memory.
Page 132 of
Complex algorithms: Some algorithms used in linear data structures, such as
searching and sorting, can be complex and time-consuming.
Inefficient use of memory: Linear data structures can result in inefficient use of
memory if there are gaps in the memory allocation.
Unsuitable for certain operations: Linear data structures may not be suitable for
operations that require constant random access to elements, such as searching for an
element in a large dataset.
Most Common Operations Performed in Linear Data Structures
Next, we'll look at the most popular data structure operations. Data structure operations refer
to the methods that allow you to manipulate data within a data structure. These are the most
popular data structure operations:
1. Traversal
A traversal operation is used to visit every data structure node in a particular order. This is a
technique that can be used to print, search, display, and read data stored in a structure.
2. Insertion
Insertion operations add data elements to a database structure. This can be operated at any
point in the data structure, including its beginning, middle, and end.
3. Deletion
Data elements are removed from a data structure by deletion operations. These operations are
usually performed on nodes that no longer need them.
4. Merge
Two data structures can be combined into one using merge operations. This is used when two
data structures need to be combined into one.
5. Copy
To create a duplicate data structure, copy operations can be used. You can do this by copying
every element from the original structure to the new one.
Page 133 of
6. Search Operation
Search operations can be used to locate a particular data element within a data structure. These
operations often use a compare function in order to determine if two elements are equal.
7. Sort Operation
Sort operations are used for arranging data elements in a data structure in a particular order.
You can use a variety of sorting algorithms to accomplish this, including bubble sort, insertion
sort, and merge sort.
o A non-linear data structure is another important type in which data elements are not
arranged sequentially; mainly, data elements are arranged in random order without
forming a linear structure.
o Multiple runs are required to traverse through all the elements completely. Traversing in a
single run is impossible to traverse the whole data structure.
o Each element can have multiple paths to reach another element.
o The data structure where data items are not organized sequentially is called a non-linear
data structure. In other words, data elements of the non-linear data structure could be
connected to more than one element to reflect a special relationship among them.
Tree:
o The tree is a non-linear data structure that is comprised of various nodes. The nodes in the
tree data structure are arranged in hierarchical order.
Page 134 of
o It consists of a root node corresponding to its various child nodes, present at the next
level. The tree grows on a level basis, and root nodes have limited child nodes depending
on the order of the tree.
o For example, in the binary tree, the order of the root node is 2, which means it can have at
most 2 children per node, not more than it.
o The non-linear data structure cannot be implemented directly, and it is implemented using
the linear data structure like an array and linked list.
o The tree itself is a very broad data structure and is divided into various categories
like Binary tree, Binary search tree, AVL trees, Heap, max Heap, min-heap, etc.
o All the types of trees mentioned above differ based on their properties.
Graph
o A graph is a non-linear data structure with a finite number of vertices and edges, and
these edges are used to connect the vertices.
o The graph itself is categorized based on some properties; if we talk about a complete
graph, it consists of the vertex set, and each vertex is connected to the other vertexes
having an edge between them.
o The vertices store the data elements, while the edges represent the relationship between
the vertices.
o A graph is very important in various fields; the network system is represented using the
graph theory and its principles in computer networks.
o Even in Maps, we consider every location a vertex, and the path derived between two
locations is considered edges.
o The graph representation's main motive is to find the minimum distance between two
vertexes via a minimum edge weight.
o It is used to store the data elements combined whenever they are not present in the
contiguous memory locations.
Page 135 of
o Unlike in an array, we have to define the size of the array, and subsequent memory space
is allocated to that array; if we don't want to store the elements till the range of the array,
then the remaining memory gets wasted.
o So to overcome this factor, we will use the non-linear data structure and have multiple
options to traverse from one node to another.
Trees: Unlike Arrays, Stack, Linked Lists, and queues, which are linear data structures, trees are
hierarchical.
o A tree data structure is a collection of objects or entities known as nodes linked together
to represent or simulate hierarchy.
o This data is not arranged in a sequential contiguous location like as we have observed in
an array, the homogeneous data elements are placed at the contiguous memory location
so that the retrieval of data elements is simpler.
o Each node contains some data and the link or reference of other nodes that can be called
children.
Page 136 of
Graphs
o One node is connected with another node with an edge in a graph. The graph is a non-
linear data structure consisting of nodes and edges and is represented by G ( V, E ), where
V stands for the set of vertices and E stands for the set of edges. The graphs are divided
into various categories: directed, undirected, weighted and unweighted, etc.
o This data is not arranged in sequential contiguous locations as observed in the array. The
homogeneous data elements are placed at the contiguous memory location to retrieve data
elements is simpler.
o It does not have any concept of root node or child node, unlike trees. Also, it does not
have any particular order of arranging the data elements like in trees, and we have a
particular hierarchical order in which the data elements are arranged.
o Every tree is called a graph, and in other words, we call it a spanning tree, which has the
n- 1 edges, where n stands for the total number of vertices in a graph.
Page 137 of
Difference Between Linear and Non-linear Data Structures
Arrangement In a linear data structure, the data In a non-linear data structure, the
of Data elements connect to each other data elements connect to each other
Element sequentially. A user can transverse each hierarchically. Thus, they are present
element through a single run. at various levels.
Complexity of The linear data structures are The non-linear data structures are
Implementatio comparatively easier to comparatively difficult to
n implement. implement and understand as
compared to the linear data
structures.
Levels A user can find all of the data elements One can find all the data elements
at a single level in a linear data structure. at multiple levels in a non-linear
data structure.
Traversal You can traverse a linear data structure It is not easy to traverse the non-
in a single run. linear data structures. The users need
multiple runs to traverse them
completely.
Page 138 of
Complexity The time complexity of this data structure Non-linear data structure’s time
of Time is directly proportional to its size. It complexity often remains the
means that the time complexity increases same with an increase in its input
with increasing input size. size.
Applications Linear data structures work well mainly Non-linear data structures work
in the development of application mainly well in image processing
software. and Artificial Intelligence.
Here, we are going to use JavaScript in developing a web application. So, we must have at least
two things, a browser, and an editor to write the JavaScript code.
Browser
Mostly, you will have a browser already installed on your PC, Microsoft Edge on the Windows
platform, and Safari on Mac OS.
You can also install the following browser as per your preference:
Microsoft Edge
Google Chrome
Mozilla FireFox
Safari
Opera
Page 139 of
IDEs for JavaScript Application Development
You can write JavaScript code using a simple editor like Notepad. However, you can install any
open-sourced or licensed IDE (Integrated Development Environment) to get the advantage of
IntelliSense support for JavaScript and syntax error/warning highlighter for rapid development.
Use the online editor to quickly execute the JavaScript code without any installation. The
followings are free online editors:
jsfiddle.net
jsbin.com
playcode.io
A runtime environment is where your program will be executed. It determines what global
objects your program can access and it can also impact how it runs. This article covers the two
JavaScript runtime environments:
The most common place where JavaScript code is executed is in a browser. For example,
using any text editor, you could create a file on your own computer called my_website.html
and put the following HTML code inside:
Page 140 of
<!-- my_website.html -->
<html>
<body>
<h1> My Website </h1>
<script> window.alert('Hello World'); </script>
</body>
</html>
Save your file, then open your favorite browser. Most browsers will allow you to load websites
that you have created locally by going to the menu File > Open File > my_website.html.
Upon loading, the embedded <script></script> will execute and the window.alert() method will
create a pop-up box in your browser with the text "Hello World". How is this possible? Where
did the window.alert() method come from and how can it control your browser?
The answer is that you are executing this code in the browser’s runtime environment.
The window.alert() method is built into this environment and any program executed in a
browser has access to this method. In fact, the window object provides access to a huge
amount of data and functionality relating to the open browser window beyond just .alert().
The Node runtime environment was created for the purpose of executing JavaScript code without
a browser, thus enabling programmers to create full-stack (front-end and back-end) applications
using only the JavaScript language.
Node is an entirely different runtime environment, meaning that browser-environment data values
and functions, like window.alert(), can’t be used. Instead, the Node runtime environment gives
back-end applications access to a variety of features unavailable in a browser, such as access to
the server’s file system, database, and network.
For example, suppose you created a file called my-app.js. We can check to see the directory that
this file is located in using the Node runtime environment variable
Page 141 of
Properties of a Linked List
Linked lists are dynamic, which means they can grow or shrink during the runtime
of a program.
Linked lists can be accessed only sequentially.
The nodes are not stored in contiguous memory locations.
Node contains the data and pointer.
A particular node is pointed and can be accessed by the pointer stored in
the previous node.
The first node of the linked list is pointed by a specific pointer called the head.
The last node of the linked list points to null, which specifies the end of the list.
Implementation
A linked list is a data structure that consists of a sequence of elements, each of which contains a
reference (or "link") to the next element in the sequence. The first element is called the head and
the last element is called the tail.
Linked lists have many advantages over other data structures. Now we shall look at how to
implement Linked list using JavaScript.
This is basically the prerequisite in order to implement a linked list in JavaScript. In this step, 2
classes namely one for the nodes and the other for the linked list need to be created.
1. The Node class represents a single node in the linked list. It has two properties
which are data and next. The data property is used to store the actual data of
the node, whereas the next property is a reference to the next node in the list.
The Node class consists of a constructor that initializes the data and next property
when creating a new Node.
class Node {
constructor(data) {
Page 142 of
this.data = data;
this.next = null;
}
}
2. The LinkedList class is a representation of the linked list itself. It has a head
property that refers to the first node in the list. The LinkedList class also has
a constructor that initializes the head property when creating a new
LinkedList.
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
}
3. The LinkedList class also consists of a method that allows you to insert, delete,
and search for nodes in the list while simultaneously allowing other operations
like printing the list, counting the elements, reversing the list and so on.
You can print the elements of a linked list by traversing through the list and printing the data of
each node.
printAll() {
let current = this.head;
while (current) {
console.log(current.data);
current = current.next;
}
}
There are multiple methods to add data to a linked list depending on where the new node has to
be inserted, and are as follows −
Page 143 of
Adding node to the beginning of the linked list
To add node/ element at the start of a linked list, once a new node is created with the data, simply
set its next property to the current head of the list. Then you can update the head of the list to the
new node. This is also known as Insertion at the head of the linked list and is the most basic type
of addition of data. It is simply done by calling the add function defined below.
add(data) {
const newNode = new Node(data);
if (!this.head) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
this.tail = newNode;
}
this.length++;
return this;
}
To add node/ element at the end of a linked list, we need to traverse the list and find the last node.
After which a new node with data is created and we set the next property of the last node to the
new node. This is also known as Insertion at the tail of the linked list and is the second most basic
type of addition of data. It is simply done by calling the addToTail function defined below.
addToTail(data) {
let newNode = new Node(data);
if (this.head === null) {
this.head = newNode;
return;
}
let current = this.head;
while (current.next !== null) {
current = current.next;
}
Page 144 of
current.next = newNode;
}
To add node/ element at a specific position in a linked list, you can traverse the list to find the
node at the position before the insertion point, create a new node with the data, set the next
property of the new node to the current node at the position, and set the next property of the
previous node to the new node.
addAtPosition(data, position) {
let newNode = new Node(data);
if (position === 1) {
newNode.next = this.head;
this.head = newNode;
return;
}
let current = this.head;
let i = 1;
while (i < position - 1 && current) {
current = current.next;
i++;
}
if (current) {
newNode.next = current.next;
current.next = newNode;
}
}
In the below example, we implement adding nodes at beginning, at end and at a specific position.
// this function is used to iterate over the entire linkedlist and print
it
printAll() {
let current = this.head;
Page 145 of
while (current) {
console.log(current.data);
current = current.next;
}
}
}
const list = new LinkedList();
// add elements to the linkedlist
list.add("node1");
list.add("node2");
list.add("node3");
list.add("node4");
console.log("Initial List:");
list.printAll();
console.log("List after adding nodex at position 2");
list.addAtPosition("nodex",2);
list.printAll();
console.log("List after adding nodey to tail");
list.addToTail("nodey");
list.printAll();
Output
Initial List:
node1
node2
node3
node4
List after adding nodex at position 2
node1
nodex
node2
node3
node4
List after adding nodey to tail
node1
nodex
Page 146 of
node2
node3
node4
nodey
Removing Node
Removal of data too, can be done via several methods depending upon the requirement.
To remove a specific node from a linked list, we need to traverse the list and find the node before
the one you want to remove, update its next property to skip over the node you want to remove,
and update the reference to the next node. This removes the node based upon the value.
remove(data) {
if (!this.head) {
return null;
}
if (this.head.data === data) {
this.head = this.head.next;
this.length--;
return this;
}
let current = this.head;
while (current.next) {
if (current.next.data === data) {
current.next = current.next.next;
this.length--;
return this;
}
current = current.next;
}
return null;
}
Page 147 of
Removing a node at a Specific Position
To remove a node at a specific position in a linked list, we need to traverse the list and find the
node before the one you want to remove, update its next property to skip over the node you want
to remove, and update the reference to the next node. This is basically removing the node based
upon the index value of it.
removeAt(index) {
if (index < 0 || index >= this.length) return null;
if (index === 0) return this.remove();
let current = this.head;
for (let i = 0; i < index - 1; i++) {
current = current.next;
}
current.next = current.next.next;
this.length--;
return this;
}
In the below example, we implement removing a specific node and a node at a specific position.
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
// function to add data to linked list
add(data) {
Page 148 of
const newNode = new Node(data);
if (!this.head) {
this.head = newNode;
this.tail = newNode;
}
else {
this.tail.next = newNode;
this.tail = newNode;
}
this.length++;
return this;
}
// function to remove data from linked list
remove(data) {
if (!this.head) {
return null;
}
if (this.head.data === data) {
this.head = this.head.next;
this.length--;
return this;
}
let current = this.head;
while (current.next) {
if (current.next.data === data) {
current.next = current.next.next;
this.length--;
return this;
}
current = current.next;
}
return null;
}
// function to remove from a particular index
removeAt(index) {
if (index < 0 || index >= this.length) return null;
Page 149 of
if (index === 0) return this.remove();
let current = this.head;
for (let i = 0; i < index - 1; i++) {
current = current.next;
}
current.next = current.next.next;
this.length--;
return this;
}
// this function is used to iterate over the entire linkedlist and print it
printAll() {
let current = this.head;
while (current) {
console.log(current.data);
current = current.next;
}
}
}
const list = new LinkedList();
// add elements to the linkedlist
list.add("node1");
list.add("node2");
list.add("node3");
list.add("node4");
console.log("Initial List:");
list.printAll();
console.log("List after removing node2");
list.remove("node2");
list.printAll();
console.log("List after removing node at index 2");
list.removeAt(2);
list.printAll();
Output
Initial List:
node1
Page 150 of
node2
node3
node4
List after removing node2
node1
node3
node4
List after removing node at index 2
node1
node3
Conclusion
Implementing a linked list in JavaScript involves creating a Node class to represent each node
in the list and a LinkedList class to represent the list itself, and adding methods to the
LinkedList class to perform operations such as adding and removing data, and printing the
list. It's important to also consider edge cases and handle them accordingly in your
implementation. There are several ways of adding or removing data from a LinkedList based
upon the use case.
https://www.w3resource.com/javascript-exercises/linkedlist/javascript-singly-linked-list-exercise-
4.php
https://www.tutorialspoint.com/implementation-of-linkedlist-in-javascript
2. Array
The JavaScript Array object lets you store multiple values in a single variable. An array is used
to store a sequential collection of multiple elements of same or different data types. In JavaScript,
arrays are dynamic, so you don't need to specify the length of the array while defining the array.
The size of a JavaScript array may decrease or increase after its creation.
Syntax
When you pass the single numeric argument to the Array() constructor, it defines the array of
argument length containing the undefined values. The maximum length allowed for an array is
4,294,967,295.
You can add multiple comma separated elements inside square brackets to create an array using
the array literal −
You will use ordinal numbers to access and to set values inside an array as follows.
Array Properties
Here is a list of the properties of the Array object along with their description −
constructor
1
Returns a reference to the array function that created the object.
length
2
Reflects the number of elements in an array.
prototype
3
The prototype property allows you to add properties and methods to an
object.
Array Methods
Page 152 of
Here is a list of the methods of the Array object along with their description −
1 from()
Creates a shallow copy of the array.
2 isArray()
Returns boolean values based on the argument is an array.
3 Of()
Creates an array from multiple arguments.
In the example below, the array 'strs' is initialized with the string values passed as an Array()
constructor's argument.
The 'cars' array contains 20 undefined elements. If you pass multiple numeric values, it defines
the array containing those elements but needs to be careful with a single numeric argument to the
array() constructor.
<html>
<head>
<title> JavaScript - Array() constructor </title>
</head>
<body>
<p id = "demo"> </p>
<script>
const output = document.getElementById("demo");
let strs = new Array("Hello", "World!", "Tutorials Point");
output.innerHTML += "strs ==> " + strs + "<br>";
Page 153 of
let cars = new Array(20);
output.innerHTML += "cars ==> " + cars + "<br>";
</script>
</body>
</html>
Output
strs ==> Hello,World!,Tutorials Point
cars ==> ,,,,,,,,,,,,,,,,,,,
In the example below, we have created different arrays. The arr1 array contains the numbers, the
arr2 array contains the strings, and the arr3 array contains the boolean values.
<html>
<head>
<title> JavaScript - Array literals </title>
</head>
<body>
<p id = "output"> </p>
<script>
const arr1 = [10, 40, 50, 60, 80, 90]; // Array of numbers
const arr2 = ["Hello", "Hi", "How", "are", "you?"]; // Array of strings
const arr3 = [true, false, true, true]; // Array of booleans
document.getElementById("output").innerHTML =
"arr1 ==> " + arr1 + "<br>" +
"arr2 ==> " + arr2 + "<br>" +
"arr3 ==> " + arr3;
</script>
</body>
</html>
Output
arr1 ==> 10,40,50,60,80,90
arr2 ==> Hello,Hi,How,are,you?
arr3 ==> true,false,true,true
Page 154 of
Accessing JavaScript Array Elements
The array index starts from 0. So, you can access the array element using its index.
In the above syntax, 'arr' is an array, and 'index' is a number from where we need to access the
array element.
Example
In the example below, we have created the array of numbers and accessed the elements from the
0th and 2nd index of the array. The element at the 0th index is 1, and the element at the 2nd index
is 6.
<html>
<head>
<title> JavaScript - Accessing array elements </title>
</head>
<body>
<p id = "output"> </p>
<script>
const nums = [1, 5, 6, 8, 90];
document.getElementById("output").innerHTML =
"Element at 0th index is : " + nums[0] + "<br>" +
"Element at 2nd index is : " + nums[2];
</script>
</body>
</html>
Output
Element at 0th index is : 1
Element at 2nd index is : 6
The 'length' property of the array is used to find the length of the array.
Page 155 of
Example
In the example below, the 'length' property returns 5, as array contains 5 elements.
<html>
<head>
<title> JavaScript - Array length </title>
</head>
<body>
<p id = "output"> </p>
<script>
const nums = [1, 5, 6, 8, 90];
document.getElementById("output").innerHTML =
"Array length is : " + nums.length;
</script>
</body>
</html>
Output
Array length is : 5
You can use the push() method to insert the element at the end of the array. Another solution is
that you can insert the array at the index equal to the array length.
arr.push(el
e) OR
arr[arr.length] = ele;
In the above syntax, 'ele' is a new element to insert into the array. Here, if the array length is N,
the array contains elements from 0 to N – 1 index. So, we can insert the new element at the Nth
index.
Page 156 of
Example
In the example below, we insert 6 to the array using the push() method. Also, we used the 'length'
property to insert the element at the end.
<html>
<body>
<p id = "output"> </p>
<script>
const output = document.getElementById("output");
const nums = [1, 2, 3, 4, 5];
nums.push(6); // Inserting 6 at the end
output.innerHTML += "Updated array is : " + nums + "<br>";
nums[nums.length] = 7; // Inserting 7
output.innerHTML += "Updated array is : " + nums + "<br>"
</script>
</body>
</html>
Output
Updated array is : 1,2,3,4,5,6
Updated array is : 1,2,3,4,5,6,7
To update any array element, you can access the array index and change its value.
arr[index] = ele;
In the above syntax, 'index' is an index where we need to update a value with the 'ele' value.
Example
In the example below, we update the element at the first index in the array.
<html>
<body>
Page 157 of
<p id = "output"> </p>
<script>
const nums = [1, 2, 3, 4, 5];
nums[0] = 100; // Updating first element
document.getElementById("output").innerHTML =
"Updated array is : " + nums;
</script>
</body>
</html>
Output
Updated array is : 100,2,3,4,5
You can use the loop to traverse through each array element. However, some built-in methods
exist to traverse the array, which we will see in later chapters.
In the below code, the array contains 5 numbers. We used the for loop to traverse the array and
print each element.
However, while and do-while loops can also be used to traverse the array.
<html>
<body>
Page 158 of
</script>
</body>
</html>
Output
nums[0] ==> 1
nums[1] ==> 2
nums[2] ==> 3
nums[3] ==> 4
nums[4] ==> 5
https://www.tutorialspoint.com/javascript/javascript_arrays_object.htm
Queue
Implementation of Queue in Javascript
A Queue works on the FIFO(First in First Out) principle. Hence, it performs two basic
operations which are the addition of elements at the end of the queue and the removal of
elements from the front of the queue. Like Stack, Queue is also a linear data structure.
Now, we will see the practical implementation of these queue operations, which are as
follows: https://www.geeksforgeeks.org/implementation-queue-javascript/
1) enqueue (): The queue operation which is used for adding elements to the queue.
Example:
enqueue(ele) {
if(this.rear < this.size ) {
this.data[this.rear] = ele;
thisthis.rear = this.rear + 1;
}
}
Page 159 of
}
In the above code, we have added elements to the queue using the push function.
2) dequeue (): The queue operation which is used for removing or popping out the existing
values from the queue.
Example:
dequeue() {
if(this.isEmpty() === false) {
thisthis.rear = this.rear-1;
return this.data.shift();
}
}
In the above code, firstly, we have checked if the queue is already empty or not. It is because if
the queue has no value, it will return "Underflow". Else, it will check and return the element.
3) Length (): The queue operation is used to return the length of the queue.
Example:
length() {
return this.rear;
}
The statement this.rear will help to fetch the length of the queue.
4) isEmpty (): The queue operation is used to check whether the queue is empty or not. If the
queue is found empty, it returns true. Otherwise, it returns false.
Example:
isEmpty() {
return this.rear === 0;
}
Page 160 of
In the above code, it will check if the value of the rear, i.e., the end, is equal to 0 or not. If it is
true, it will return true else false will be returned.
5) print (): The queue operation is used to print the elements of the queue from the index value 0
to the rear position of the queue.
Example:
print() {
for(let i =0; i < this.rear; i++) {
console.log(this.data[i]);
}
}
In the above code, using for loop and beginning from the 0 indexes to the queue's rear position, it
will print the value and put it in the data array.
6) clear (): The queue operation is used to clear or delete all the elements of the queue and makes
the value of the rear equal to 0.
Example:
clear() {
this.data.length = 0;
this.rear = 0;
}
In the above code, using the clear () operation, the value in the data array becomes 0 and sets the
rear value to 0.
class Queue {
constructor(){
this.data = [];
this.rear = 0;
this.size = 20;
Page 161 of
}
enqueue(ele) {
if(this.rear < this.size ) {
this.data[this.rear] = ele;
thisthis.rear = this.rear + 1;
}
}
length() {
return this.rear;
}
isEmpty() {
return this.rear === 0;
}
getFront() {
if(this.isEmpty() === false) {
return this.data[0];
}
}
getLast() {
if(this.isEmpty() === false) {
return this.data[ this.rear - 1 ] ;
}
}
dequeue() {
if(this.isEmpty() === false) {
thisthis.rear = this.rear-1;
return this.data.shift();
}
}
print() {
for(let i =0; i < this.rear; i++) {
console.log(this.data[i]);
}
}
clear() {
this.data.length = 0;
Page 162 of
this.rear = 0;
}
}
https://www.javatpoint.com/javascript-queue
Another example:
class Queue {
constructor() {
this.items = {}
this.frontIndex = 0
this.backIndex = 0
enqueue(item) {
dequeue() {
delete this.items[this.frontIndex]
this.frontIndex++
Page 163 of
return item
peek() {
return this.items[this.frontIndex]
get printQueue() {
return this.items;
console.log(queue.enqueue(7))
console.log(queue.enqueue(2))
console.log(queue.enqueue(6))
console.log(queue.enqueue(4))
console.log(queue.dequeue())
console.log(queue.peek())
console.log(str)
In this article, we are going to discuss how to create the stack data structure in JavaScript. It is a
linear data structure where the push and popping of elements follow the LIFO (last in first out
and FILO (first in last out) sequence.
Page 164 of
Though Arrays in JavaScript provide all the functionality of a Stack, let us implement our own
Stack class. Our class will have the following functions.
Let's start by defining a simple class with a constructor that takes the max size of the stack and a
helper function display() that'll help us when we implement the other functions for this class. We
have also defined 2 more functions, isFull and isEmpty to check if the stack is full or empty.
The isFull function just checks if the length of the container is equal to or more than maxSize and
returns accordingly.
These will be helpful when we define other operations. The functions we define from this point
onwards will all go inside the Stack class.
Example 1
The following example demonstrates how to create the Stack Data Structure in JavaScript. In this
example, we are going to discuss the use of push(), and the pop() methods. We create a stack and
add the elements to it and display the stack elements.
<!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>Creating Stack Data Structure</title>
</head>
<body>
Page 165 of
<script type="text/javascript">
class Stack {
constructor() {
this.stkArr = [];
}
// add element to the stack
add(element) {
return this.stkArr.push(element);
}
// remove element from the stack
remove() {
if (this.stkArr.length > 0) {
document.write("<br>");
return "The Popped element is : " + this.stkArr.pop();
}
}
// view the last element
peek() {
document.write("<br>");
return (
"The Peek element of the stack is : " +
this.stkArr[this.stkArr.length - 1]
);
}
// check if the stack is empty
isEmpty() {
document.write("<br>");
return this.stkArr.length == 0;
}
// the size of the stack
size() {
document.write("<br>");
return "The size of the stack is : " + this.stkArr.length;
}
display() {
if (this.stkArr.length !== 0) {
Page 166 of
return "The stack elements are : " + this.stkArr + "<br>";
} else {
document.write("The Stack is Empty..! <br>");
}
}
// empty the stack
clear() {
document.write("The stack is cleared..!" + "<br>");
this.stkArr = [];
}
}
let stack = new Stack();
stack.add(1);
stack.add(2);
stack.add(3);
stack.add(4);
stack.add(5);
document.write(stack.display());
document.write(stack.size());
</script>
</body>
</html>
Example 2
class Stack {
constructor(maxSize) {
if (isNaN(maxSize)) {
maxSize = 10;
}
this.maxSize = maxSize;
this.container = [];
}
display() {
Page 167 of
console.log(this.container);
}
push(element) {
this.container.push(element);
}
}
const obj = new Stack(10);
obj.push(10);
obj.push(44);
obj.push(55);
obj.display();
https://www.tutorialspoint.com/Creating-a-Stack-in-Javascript
Tree
Height (h) of the tree is the distance (edge count) between the farthest leaf to the root.
Page 168 of
o A has a height of 3
o I has a height of 0
Depth or level of a node is the distance between the root and the node in question.
o H has a depth of 2
o B has a depth of 1
As we saw earlier, a tree node is just a data structure with a value and links to its descendants.
1 class TreeNode {
2 constructor(value) {
3 this.value = value;
4 this.descendants = [];
5 }
6}
Page 169 of
1 // create nodes with values
2 const abe = new TreeNode('Abe');
3 const homer = new TreeNode('Homer');
Page 170 of
4 const bart = new TreeNode('Bart');
5 const lisa = new TreeNode('Lisa');
6 const maggie = new TreeNode('Maggie');
7 // associate root with is descendants
8 abe.descendants.push(homer);
9 homer.descendants.push(bart, lisa, maggie);
Depending on how nodes are arranged in a binary tree, it can be full, complete and perfect:
Full binary tree: each node has exactly 0 or 2 children (but never 1).
Complete binary tree: when all levels except the last one are full with nodes.
Perfect binary tree: when all the levels (including the last one) are full of nodes.
Page 171 of
Look at these examples:
These properties are not always mutually exclusive. You can have more than one:
o Perfect binary trees have precisely 2k−12𝑘-1 nodes, where k is the last level
of the tree (starting with 1).
o Like in our “complete” example, since it has a parent with only one child. If we
remove the rightmost gray node, then we would have a complete and full tree but
not perfect.
Each node in a tree data structure must have the following properties:
: Thekey
key of the node
value: The value of the node
parent: The parent of the node (null if there is none)
children: An array of pointers to the node's children
Implementation
Page 172 of
class TreeNode {
constructor(key, value = key, parent = null) {
this.key = key;
this.value = value;
this.parent = parent;
this.children = [];
}
get isLeaf() {
return this.children.length === 0;
}
get hasChildren() {
return !this.isLeaf;
}
}
class Tree {
constructor(key, value = key) {
this.root = new TreeNode(key, value);
}
*preOrderTraversal(node = this.root) {
yield node;
if (node.children.length) {
for (let child of node.children) {
yield* this.preOrderTraversal(child);
}
}
}
*postOrderTraversal(node = this.root) {
if (node.children.length) {
for (let child of node.children) {
yield* this.postOrderTraversal(child);
}
}
yield node;
}
insert(parentNodeKey, key, value = key) {
for (let node of this.preOrderTraversal()) {
Page 173 of
if (node.key === parentNodeKey) {
node.children.push(new TreeNode(key, value,
node)); return true;
}
}
return false;
}
remove(key) {
for (let node of this.preOrderTraversal()) {
const filtered = node.children.filter(c => c.key !==
key); if (filtered.length !== node.children.length) {
node.children = filtered;
return true;
}
}
return false;
}
find(key) {
for (let node of this.preOrderTraversal())
{ if (node.key === key) return node;
}
return undefined;
}
}
Create a class for the TreeNode with a constructor that initializes the
appropriate key, value, parent and children properties.
Define an isLeaf getter, that uses Array.prototype.length to check if children is empty.
Define a hasChildren getter, that is the reverse of the isLeaf getter.
Create a class for the Tree with a constructor that initializes the root of the tree.
Define a preOrderTraversal() generator method that traverses the tree in pre-order,
using the yield* syntax to recursively delegate traversal to itself.
Define a postOrderTraversal() generator method that traverses the tree in post-order,
using the yield* syntax to recursively delegate traversal to itself.
Define an insert() method, that uses the preOrderTraversal() method
and Array.prototype.push() to add a new TreeNode to the tree.
Page 174 of
Define a remove() method, that uses the preOrderTraversal() method
and Array.prototype.filter() to remove a TreeNode from the tree.
Define a find() method, that uses the preOrderTraversal() method to retrieve the
given node in the tree.
Hash Table
Hash table is one of the most important data structures that uses a special function known as a
hash function that maps a given value with a key to access the elements faster.
A Hash table is a data structure that stores some information, and the information has basically
two main components, i.e., key and value. The hash table can be implemented with the help of an
associative array. The efficiency of mapping depends upon the efficiency of the hash function
used for mapping.
For example, suppose the key value is John and the value is the phone number, so when we pass
the key value in the hash function shown as below:
Hash(key)= index;
When we pass the key in the hash function, then it gives the index.
Hash(john) = 3;
A Hash function assigns each value with a unique key. Sometimes hash table uses an imperfect
hash function that causes a collision because the hash function generates the same key of two
different values.
In Hashing technique, the hash table and hash function are used. Using the hash function, we can
calculate the address at which the value can be stored.
The main idea behind the hashing is to create the (key/value) pairs. If the key is given, then the
algorithm computes the index at which the value would be stored. It can be written as:
Index = hash(key)
Page 175 of
Hash tables are made up of two parts:
Object: An object with the table where the data is stored. The array holds all the key-
value entries in the table. The size of the array should be set according to the amount
of data expected.
Hash function (or mapping function): This function determines the index of our key-value
pair. It should be a one-way function and produce the a different hash for each key.
To implement a hash table using JavaScript, we will do three things: create a hash
table class, add a hash function, and implement a method for adding key/value pairs to
our table.
First, let’s create the HashTable class.
class HashTable
{ constructor()
{ this.values =
{}; this.length
= 0;
this.size = 0;
}
The constructor contains an object in which we’re going to store the values, the length of the
values, and the entire size of the hash table: meaning how many buckets the hash table contains.
We will be storing our data in these buckets.
Page 176 of
Next, we have to implement a simple hashing function.
calculateHash(key) {
return key.toString().length % this.size;
}
This function takes the provided key and returns a hash that’s calculated using an arithmetic
modulus.
Finally, we need a method to insert key/value pairs. Take a look at the code and see this in action:
add(key, value) {
const hash = this.calculateHash(key);
if (!this.values.hasOwnProperty(hash)) {
this.values[hash] = {};
}
if (!this.values[hash].hasOwnProperty(key)) {
this.length++;
}
this.values[hash][key] = value;
}
The first thing we do here is calculate a hash for our key. If the hash does not already exist, we
save it to our object store. The next check we perform is on the hash. If it doesn’t have a key
saved, we save the key and value and increment the size of our hash table.
Searching in a hash table goes very fast. Unlike with an array where we have to go through all of
the elements until we reach the item we need, with a hash table we simply get the index. I’ll add
the complete code for our hash table implementation below.
class HashTable {
constructor() {
this.values = {};
this.length = 0;
this.size = 0;
}
calculateHash(key) {
return key.toString().length % this.size;
Page 177 of
}
add(key, value) {
const hash = this.calculateHash(key);
If (!this.values.hasOwnProperty(hash)) {
this.values[hash] = {};
}
if (!this.values[hash].hasOwnProperty(key)) {
this.length++;
}
this.values[hash][key] = value;
}
search(key) {
const hash = this.calculateHash(key);
if (this.values.hasOwnProperty(hash) && this.values[hash].hasOwnProperty(key)) {
return this.values[hash][key];
} else {
return null;
}
}
}
//create object of type hash table
const ht = new HashTable();
//add data to the hash table ht
ht.add("Canada", "300");
ht.add("Germany", "100");
ht.add("Italy", "50");
//search
console.log(ht.search("Italy"));
https://www.educative.io/blog/data-strucutres-hash-table-javascript
Perform sorting operations
Bubble
We have an unsorted array arr = [ 1, 4, 2, 5, -2, 3 ], and the task is to sort the array using bubble
sort in ascending order.
Page 178 of
Bubble sort compares the element from index 0 and if the 0th index value is greater than
1st index value, then the values get swapped and if the 0th index value is less than the 1st
index value, then nothing happens.
Next, the 1st index value compares to the 2nd index value, and then the 2nd index value
compares to the 3rd index value, and so on…
Syntax
BubbleSort(array) {
for i -> 0 to arrayLength
for j -> 0 to (arrayLength - i - 1)
if arr[j] > arr[j + 1]
swap(arr[j], arr[j + 1])
}
// Bubble sort Implementation using Javascript
// Creating the bblSort function
function bblSort(arr) {
for (var i = 0; i < arr.length; i++) {
Page 179 of
// This is our unsorted array
var arr = [234, 43, 55, 63, 5, 6, 235, 547];
// Now pass this array to the bblSort() function
bblSort(arr);
Note: This implementation is not optimized. We will see the optimized solution next.
Optimized Solution
As we discussed the implementation of bubble sort earlier that is not optimized. Even if the array
is sorted, the code will run with O(n^2) complexity. Let’s see how to implement an optimized
bubble sort algorithm in javascript.
Page 180 of
}
}
// If no two elements were swapped in the inner loop, array is sorted
if (!isSwapped)
break;
}
return array;
}
Quick sort is one of the sorting algorithms that works on the idea of divide and conquer. It
takes an element as a pivot and partitions the given array around that pivot by placing it in the
correct position in the sorted array. The pivot element can be selected in the following ways:
First, create a recursive function that takes array, low value and high value as input and
calls the partition fucntion for recursive call for partitioned arrays.
Page 181 of
Define a partition function for last element as pivot and give the partition index of array.
Partition function iterate the given array and compare elements to pivot. If smallar
then swap them to a sequential postion else no swap is performed.
At the end for iteration the pivot element is swapped to its correct position stored in i
for the exact place.
Example: Here is the complete code for the Quick Sort algorithm using JavaScript.
Page 182 of
console.log("Sorted array: " + arr);
Output
Original array: 10,80,30,90,40
Sorted array: 10,30,40,80,90
https://www.geeksforgeeks.org/javascript-program-for-quick-sort/
Binary Search is a searching technique that works on the Divide and Conquer approach. It is used
to search for any element in a sorted array. Compared with linear, binary search is much faster
with a Time Complexity of O(logN), whereas linear search works in O(N) time complexity
Examples:
Recursive Approach:
BASE CONDITION: If the starting index is greater than the ending index return false.
Compare the middle element with the number x. If equal return true.
If greater, call the same function with ending index = middle-1 and repeat step 1.
If smaller, call the same function with starting index = middle+1 and repeat step 1.
Page 183 of
let recursiveFunction = function (arr, x, start, end) {
// Base Condition
if (arr[mid] > x)
else
// Driver code
let x = 5;
console.log("Element found!");
Page 184 of
else { console.log("Element not found!"); }
x = 6;
console.log("Element found!");
Output
Element found!
Element not found!
Iterative Approach:
In this iterative approach, instead of recursion, we use a while loop, and the loop runs until it hits
the base condition, i.e. start becomes greater than end.
Page 185 of
// If element is present at
start = mid + 1;
else
end = mid - 1;
return false;
// Driver code
let x = 5;
console.log("Element found!");
else {
x = 8;
Page 186 of
if (iterativeFunction(arr, x, 0, arr.length - 1)) {
console.log("Element found!");
else {
Output
Element found!
Element found!
https://www.geeksforgeeks.org/binary-search-in-javascript/
Linear
The algorithm for linear search can be broken down into the following steps:
Page 187 of
In Linear Search Algorithm,
Every element is considered as a potential match for the key and checked for the same.
If any element is found equal to the key, the search is successful and the index of
For example: Consider the array arr[] = {10, 50, 30, 70, 80, 20, 90, 40} and key = 30
Time Complexity:
Best Case: In the best case, the key might be present at the first index. So the best
case complexity is O(1)
Worst Case: In the worst case, the key might be present at the last index i.e., opposite
to the end from which the search has started in the list. So the worst-case complexity is
O(N) where N is the size of the list.
Average Case: O(N)
Auxiliary Space: O(1) as except for the variable to iterate through the list, no other variable is
used.
Unsorted Lists: When we have an unsorted array or list, linear search is most
Page 188 of
Linear search can be used irrespective of whether the array is sorted or not. It can be
used on arrays of any data type.
Does not require any additional memory.
It is a well-suited algorithm for small datasets.
Linear search has a time complexity of O(N), which in turn makes it slow for
large datasets.
Not suitable for large arrays.
https://www.geeksforgeeks.org/linear-search/
Speedy Browsing: Rendering engines are like superchargers for websites, making
them load faster and smoother. The quicker the engine, the zippier your browsing
experience!
Consistent Look: Imagine a website that stretches and squishes on different devices.
Not cool! Rendering engines ensure websites appear exactly as intended, no matter if
you’re on a phone, laptop, or giant screen.
Page 189 of
Works Everywhere: Don’t worry about Windows, Mac, or Linux – rendering engines
speak the language of all devices, making sure websites work flawlessly regardless of
your setup.
Modern Goodies: Think of fancy animations, 3D graphics, and cool new features.
Rendering engines are always learning, constantly adding support for the latest
and greatest web technologies.
Your Browser, Your Way: Some engines love customization! They let you tweak your
browser to your liking, adding extensions, and themes, and even building entirely new
things. It’s like having a toolbox for your browser!
Creating DOM tree: The rendering engine’s parse the HTML code of the web page.
This involves breaking down the HTML elements and their attributes into a the
Document Object Model (DOM) tree. The DOM tree is a hierarchical representation
of the web page’s content.
Appling styles: The rendering engine parses the CSS styles of the web page. CSS rules
such as font styles, colors, margins, and positioning define how HTML elements
should be visually presented, . The rendering engine applies these styles to the DOM
tree, transforming the structural representation into a styled representation.
Layout Construction: Once the DOM tree is styled, the rendering engine enters
the layout phase. It calculates the exact position and dimensions of each element on
the screen. Some complex layout algorithms are used for calculating the
relationships between elements such that the web page’s content is displayed as
intended by the developer.
DOM to pixels: The rendering engine starts the rasterization stage where it converts the
vector-based DOM tree into a grid of pixels. Each pixel is assigned a color with respect
to the element. This results in a rasterized image representation of the web page.
Page 190 of
Pixels to Display: The compositing is then done where the rasterized image is layered
on top of other visual elements such as the background and browser controls.
Compositing make sure that the visual elements are correctly blended and displayed on
the screen.
There are three primary rendering engines that power the majority of web browsers today:
WebKit: WebKit is an open-source rendering engine initially developed by Apple for its
Safari browser. It is also used by the iOS version of the Chrome browser and serves as
the basis for the Qt WebEngine framework.
Page 191 of
Other Engines: Beyond these giants, a constellation of niche engines exists, catering
to specific needs and platforms. WebKit variations like Presto (Opera Mini) and
Goanna (Vivaldi) offer unique mobile experiences. WebRender (Android WebView)
prioritizes efficiency on low-powered devices. Each engine, like a specialist chef,
brings its own flavor and expertise to the table, enriching the web’s diversity and
adaptability.
Developer tools (or "development tools" or short "DevTools") are programs that allow a
developer to create, test and debug software.
Current browsers provide integrated developer tools, which allow to inspect a website. They let
users inspect and debug the page's HTML, CSS, and JavaScript, allow to inspect the network
traffic it causes, make it possible to measure its performance, and much more.
Page 192 of
Sublime Text
Vim
Notepad++
Atom
Django
Vue
Ruby on Rails
Foundation
Ember
REST Assured
HoppScotch
Svelte
Meteor
Figma
ProtoPie
Using IDE Terminal
An Integrated Development Environment (IDE) is a code editor or compiler that helps web app
development. It is used for code editing, assembling, debugging, and automation, making the
developer's work easier.
1. Atom
Atom is an easy editor for developing JavaScript code that runs on Windows, Mac OS X, and
Linux. It's the best free IDE for JavaScript since it can be modified to do anything without
changing a configuration file. As you type, this tool automatically completes the code.
Page 193 of
2. Tabnine
Tabnine's AI assistant is the best IDE for learning JavaScript as it avoids the need for time-
consuming code searches by automating repetitive tasks. It offers an AI guide educated on your
team's repositories, code patterns, and best practices to provide quick inline code completions in
all popular languages and IDEs.
3. GoormIDE
GoormIDE is an open source IDE for JavaScript for configuring your development environment.
This best JavaScript IDE can be used for editing and collaborating with others in real-time.
4. Sublime Text
Sublime Text is an integrated development environment (IDE) for developing JavaScript code.
You can jump to a symbol, word, or line in the JS IDE using a keyboard shortcut. Also, it is a
shareware, and the functionalities can be increased using plugins.
Auto Indentation
Page 194 of
Syntax Highlight
Sidebar with files of mentioned directory
Macros
File Type Recognition
Plug-in and Packages
5. PLAYCODE. IO
PLAYCODE.io is a JavaScript code editor that you may use online. It has a quick and easy
application. You can save your progress by logging in to this program.
You can use it to add CSS, jQuery, and HTML code to your website.
Playcode provides real-time program output.
Simply copy the URL from your browser to share your creation.
Libraries like jQuery, FabricJS, and Underscore are available for writing JavaScript code.
6. JSFiddle
JSFiddle is a free JavaScript editor online. It allows you to incorporate CSS and HTML in
JavaScript. It is one of the best JavaScript IDEs for creating new programs using existing code as
a starting point.
7. CodePen
CodePen is a tool that allows you to create a JavaScript project rapidly. You can use this
application to create a browser-based program. Front-end languages such as CSS and HTML are
supported.
Page 195 of
Features of CodePen JavaScript IDE are:
8. Observable
Observable is a JavaScript IDE with a wide range of web technologies and libraries. It enables
you to work with other programmers in your organization.
9. Aptana
Aptana is a JavaScript text editor that is open-source. It helps you to create JavaScript
applications quickly. This free JavaScript IDE aids developers in increasing their productivity.
It has a code deployment wizard that allows you to publish your program online.
Variables may be inspected, breakpoints can be set, and execution controlled.
A command-line terminal is available in the IDE.
It enables you to personalize the IDE.
Github integration is possible (a site to discover, share, and build applications).
This program well supports HTML and JavaScript.
Page 196 of
10. Amazon Web Services9
Cloud9 is a browser-based JavaScript editor that lets you write, run, and debug code. It's one of
the greatest JavaScript code editors, allowing you to work from any computer with an internet
connection. For quick access, this tool supports keyboard shortcuts.
Panels can be moved in any direction, simply dragging and dropping them.
It contains a built-in debugger that allows you to set a breakpoint.
This includes a built-in terminal to view the server's command output.
Your development environment can be shared with your development team.
Cloud9 has a wide range of themes.
It has an image editor that allows you to resize, crop, and rotate images.
11. Codeanywhere
Codeanywhere supports over 75 languages. This application is available on any device and in any
browser. This IDE makes it simple to handle the code.
12. Eclipse
The Eclipse CDT framework is a JavaScript website development tool. You can easily debug the
program with this JavaScript IDE for Windows.
Page 197 of
You can use Eclipse to manage the project remotely.
This editor is compatible with Windows, Linux, and Mac OS X.
13. Codenvy
It supports multiple languages like HTML, CSS, JavaScript, PHP, Python, Java, Ruby,
etc.
It allows you to operate your cloud whichever way you want
Comes with containerized workspaces that enable you to use any stack
One-click project onboarding makes it easier to start
You can work offline or online with CLI sync
14. WebStorm
This JavaScript IDE helps you debug your client-side apps easily. The renowned IDE
development company JetBrains has built this IDE. It supports technologies like HTML, CSS,
JavaScript, Node.js, React, Angular JS, etc., and is compatible with multiple platforms like
Windows, Mac, and Linux.
Page 198 of
15. Sourcelair
SourceLair is one of the top JavaScript IDEs that allows developers to build various web
applications using HTML5, PHP, and Node.js. Using this IDE, you can develop a JavaScript
application from the browser. It also allows you to edit and run your code in a web browser,
without installing any application.
Key features:
All the projects developed at Sourcelair are equipped with a dedicated server
You can connect it to your GitHub account which allows you to work with your
GitHub repository
Comes with a fully-featured Linux terminal
Real-time error reporting helps you detect and remove bugs instantly
Enables you to install libraries, customize files and run commands
16. BBEdit
BBEdit is a leading HTML and text editor for the mac operating system. It enables web
developers to edit and manipulate the program seamlessly. This JavaScript IDE comes with an
array of features for editing, searching, and manipulating the source codes, and textual data. As of
now, it works only on the MAC and does not support Windows.
17. PSPad
PSPad is a simple IDE for JavaScript that you can use immediately without any customization. It
has templates, macros, and clip files to automate repetitive tasks. This text editor supports
multiple file languages and file types.
Page 199 of
Key features:
18. SlickEdit
SlickEdit is a cross-platform JavaScript IDE that supports more than 60 languages. It supports
platforms like Windows, Linux, macOS, and others. Using this tool, you can load large files.
With a wide range of features, this IDE helps developers create, modify, navigate and debug code
fast and accurately.
Angular IDE is faster and supports advanced editing of TypeScript 3.0. This JavaScript IDE is a
simple code editing tool specially developed for the Angular framework. It comes with real-time
validation of errors that allows you to preview code while writing the program.
Key features:
Page 200 of
You can use customized themes
It shows a real-time preview of the changes you made
Allows opening files and running code quickly
Real-time error detection while you type code
Visual Studio is a JavaScript IDE developed by Microsoft Corporation. You can use it for
creating GUIs, Web applications, consoles, mobile apps, cloud services, and many others. This
IDE has code completion and code refractory features. It supports languages like C#, C++,
JavaScript, VB (Visual Basic), Python, etc.
21. IntelliJ
Built with a focus on boosting developer productivity, this JavaScript IDE has an ergonomic
design and is easy to use. It can automatically add relevant tools and supports multiple
programming languages apart from JavaScript and Java. It comes in two versions; Community
and Ultimate. The community edition is free to use, while the ultimate edition requires
purchasing a license.
Key features:
Helps in detecting duplicate code fragments and providing suggestions to the user
Offers suggestions to auto-correct a mistake in the code
Smart code completion
Keyboard shortcuts for quick selection and switching between the editor and
windows tool windows
The smart search option helps you find all the controls available in the IDE
Supports advanced frameworks like Struts, Grails, Hibernate, Play, etc.
Page 201 of
22. Komodo IDE
Komodo IDE is another best JavaScript IDE available for web and mobile app development. It
comes with functionalities like unit testing, debugging, and custom workspaces. This single
polyglot IDE has multiple frameworks and integrations and is compatible with multiple
programming and markup languages, including PHP, Python, HTML, CSS, XML, Ruby,
JavaScript, Node.Js, etc.
23. Brackets
Brackets is a lightweight and fast JavaScript IDE designed specifically for web designers
and front-end developers. This browser-based design tool is written using HTML, CSS, and
JavaScript, focusing mainly on visual tools. It supports Windows, Linux, and MAC.
Key features:
The live preview allows you to see the changes on the screen immediately
Pre-processor support to use Quick Edit and SCSS files
Inline editors support working on code without having to manage popups
The Apache NetBeans JS IDE supports JavaScript, HTML5, and CSS3 in web development and
Cordova/PhoneGap framework for developing mobile apps based on JavaScript. This open-
source software is available for free. The latest version of NetBeans has improved support for
AngularJS, Node.Js Express, Gulp, Jade, Mocha, Selenium, and Knockout.js.
Key features:
Page 202 of
Has features like user settings customization, storage monitoring, and Visual
Library integration
Provides team server integration for sites that use Kenai infrastructure
It has a registered task repository where you can save searches and update tasks
https://www.turing.com/kb/top-24-javascript-ides-full-features
Test Time and space complexity
Key concepts of measuring time and space complexity
Time complexity and space complexity are two measures of the efficiency of an algorithm.
O(n log n)
The notation O(n log n) is used to describe the time complexity of an algorithm. It provides an
upper bound on the growth of the running time of the algorithm as the size of the input (n) grows.
The "O" stands for "order of" and provides a rough estimate of the maximum number of steps the
algorithm will take to solve the problem. The "n log n" part of the notation describes the rate at
which the number of steps grows as the size of the input (n) grows.
For an algorithm with O(n log n) time complexity, the number of steps grows proportional to n
log n as the size of the input increases. This means that the running time of the algorithm will
increase at a slower rate than an algorithm with O(n^2) time complexity, but faster than an
algorithm with O(n) time complexity.
Algorithms with O(n log n) time complexity are often used in a variety of computational
problems, such as sorting, searching, and merging, as they provide a good balance between time
Page 203 of
efficiency and accuracy. For example, the QuickSort and MergeSort algorithms have a time
complexity of O(n log n).
O(n)
The "O" notation is used in big O analysis, a way of measuring the performance of algorithms
and data structures. In big O analysis, the "O" notation represents the upper bound on the growth
rate of the running time of an algorithm or data structure.
The "n" in "O(n)" is a variable that represents the size of the input to the algorithm. When the
running time of an algorithm is expressed as "O(n)," it means that the running time of the
algorithm grows linearly with the size of the input. In other words, if the size of the input doubles,
the running time will roughly double as well.
So, "O(n)" is an expression that describes the time complexity of an algorithm that grows linearly
with the size of the input. It is often used to describe the best-case, average-case, or worst-case
scenario of an algorithm, depending on the context.
There are some libraries and 3rd party tools that could aid you in measuring JavaScript execution
time and memory usage.
Navigate to the "Performance" panel. You can capture a snapshot of all the actions on the
webpage for a certain period by clicking the record button at the top left of the panel. While
recording, interact with your web page in a way that triggers the JavaScript operation you're
interested in, then stop recording.
After that, DevTools will provide a comprehensive breakdown of everything that happened,
including JavaScript execution, painting, layout, system, and loading. Look for long bars in the
Page 204 of
“Main” row for possible inefficiencies. Additionally, you can click on these bars to get more
detailed information.
Another tool useful for checking JavaScript execution time is the "JavaScript Profiler" panel. In
this panel, you can start a new CPU profiling by clicking the Start button. After collecting the
profile data, stop recording.
Benchmark.js
Benchmarkify
Stats.js: A library providing a simple way to measure and display runtime performance
in an application.
jsPerf: A public website where you can create test cases to compare the performance
of different JavaScript snippets.
Plural sight: It is a tool that allows you to run tests, perform debugging, and analyze
performance for JavaScript applications.
A unit test verifies the behavior of a software unit in the system. It verifies whether a small and
isolated piece of the codebase called “unit” behaves as the developer intended.
Page 205 of
Why write Unit Tests?
Usually, developers write unit tests first, then write the software code. This approach is known as
test-driven development (TDD).
In TDD, the requirements are turned into specific test cases; then the software
is improved to pass the new tests.
In the case of unit tests, it allows for code modification without affecting the
functionality of other units or the software. This makes the job easier for developers as
the bugs are easy to locate at this stage, which saves time and money.
Also, within unit test environments, the individual modules of a product become
isolated from one another and have their area of responsibility.
In this scenario, tests are more reliable because they are run in a contained
environment. The code, too, because of said reliability, becomes reliable.
Along with the above facts, let’s explore the various benefits of unit tests.
The main advantage of unit tests is their laser-sharp focus. Since they test a single function, they
give precise feedback. If a unit test fails, in most cases, testers can be sure that the specific
function being tested is the problem.
Unit tests help to find and fix bugs quickly and easily.
Unit tests contribute to higher code quality.
Unit tests contribute to better application architecture.
Unit tests act as documentation.
Unit tests are also known for their speed. Since they’re fast, they’re executed more often, making
them a source of nearly constant valuable feedback.
The following best practices should be followed when creating unit tests:
1. Tests should be fast and simple, meaning developers need the test cases to be run at a
higher speed as it serves the purpose of unit testing. If they are slow, developers
won’t
Page 206 of
run the test cases as often as they should. Also, the simpler the unit test cases, the more
accurate the test results.
2. Test cases should not duplicate the implementation logic.
3. Test cases should be deterministic – exhibit the same behavior as long as their code
is unchanged.
4. QAs must execute tests on real browsers and devices, not emulators and simulators to
keep tests deterministic. Without exposure to actual production environments (real,
functional real devices), test results will be nowhere close to deterministic or
accurate.
5. Adapt an influential naming convention for the test cases
JavaScript Unit Testing is a method in which JavaScript test code is written for a
web page or application module.
It is then combined with HTML as an inline event handler and executed in the browser
to test if all functionalities work as desired. These unit tests are then organized in the test
suite.
The following JavaScript Testing Frameworks are helpful for unit testing in JavaScript.
They are as follows:
1. Unit.js
An assertion library for Javascript runs on Node.js and the browser. It works with any test
runner and unit testing framework like Mocha, Jasmine, Karma, protractor (E2E test
framework for Angular apps), QUnit, etc.
2. Mocha
Mocha is a test framework running both in Node.js and in the browser. This framework
makes asynchronous testing simple by running tests serially.
3. Jest
4. Jasmine
Page 207 of
Jasmine is a popular JavaScript behavior-driven development framework for unit testing
JavaScript applications. It provides utilities that run automated tests for both synchronous
and asynchronous code. It is also highly beneficial for front-end testing.
5. Karma
Karma is a node-based test tool allowing you to test your JavaScript codes across
multiple browsers. It makes test-driven development fast, fun, and easy and is termed as a
test- runner technically.
6. Cypress
7. NightwatchJS
Page 208 of