Data Structures and Algorithm
Data Structures and Algorithm
DATA
STRUCTURES &
ALGORITHM
IN JAVASCRIPT
Jayson N. Reales
Instructor
1 | Page
COMPUTER ARTS AND TECHNOLOGICAL COLLEGE, INC.
Balintawak St,. Albay District, Legaspi City
What is JavaScript
JavaScript was initially created to “make web pages alive”.
The programs in this language are called scripts. They can be written right in a web page’s
HTML and run automatically as the page loads.
Scripts are provided and executed as plain text. They don’t need special preparation or
compilation to run.
In this aspect, JavaScript is very different from another language called Java.
When JavaScript was created, it initially had another name: “LiveScript”. But Java was very
popular at that time, so it was decided that positioning a new language as a “younger
brother” of Java would help.
But as it evolved, JavaScript became a fully independent language with its own specification
called ECMAScript, and now it has no relation to Java at all.
Today, JavaScript can execute not only in the browser, but also on the server, or actually
on any device that has a special program called the JavaScript engine.
The browser has an embedded engine sometimes called a “JavaScript virtual machine”.
⮚ SpiderMonkey – in Firefox.
⮚ …There are other codenames like “Chakra” for IE, “JavaScriptCore”, “Nitro” and
The terms above are good to remember because they are used in developer articles on the
internet. We’ll use them too. For instance, if “a feature X is supported by V8”, then it probably
works in Chrome, Opera and Edge.
2 | Page
COMPUTER ARTS AND TECHNOLOGICAL COLLEGE, INC.
Balintawak St,. Albay District, Legaspi City
The engine applies optimizations at each step of the process. It even watches the compiled
script as it runs, analyzes the data that flows through it, and further optimizes the machine
code based on that knowledge.
Modern JavaScript is a “safe” programming language. It does not provide low-level access
to memory or the CPU, because it was initially created for browsers which do not require it.
JavaScript’s capabilities greatly depend on the environment it’s running in. For instance,
Node.js supports functions that allow JavaScript to read/write arbitrary files, perform network
requests, etc.
⮚ Add new HTML to the page, change the existing content, modify styles.
⮚ React to user actions, run on mouse clicks, pointer movements, key presses.
⮚ Send requests over the network to remote servers, download and upload files
⮚ Get and set cookies, ask questions to the visitor, show messages.
JavaScript’s abilities in the browser are limited to protect the user’s safety. The aim is to
prevent an evil webpage from accessing private information or harming the user’s data.
⮚ JavaScript on a webpage may not read/write arbitrary files on the hard disk, copy
3 | Page
COMPUTER ARTS AND TECHNOLOGICAL COLLEGE, INC.
Balintawak St,. Albay District, Legaspi City
⮚ Modern browsers allow it to work with files, but the access is limited and only
provided if the user does certain actions, like “dropping” a file into a browser window
or selecting it via an <input> tag.
⮚ There are ways to interact with the camera/microphone and other devices, but they
⮚ Different tabs/windows generally do not know about each other. Sometimes they do,
for example when one window uses JavaScript to open the other one. But even in
this case, JavaScript from one page may not access the other page if they come
from different sites (from a different domain, protocol or port).
⮚ This is called the “Same Origin Policy”. To work around that, both pages must agree
for data exchange and must contain special JavaScript code that handles it. We’ll
cover that in the tutorial.
⮚ This limitation is, again, for the user’s safety. A page from http://anysite.com which a
user has opened must not be able to access another browser tab with the URL
http://gmail.com, for example, and steal information from there.
⮚ JavaScript can easily communicate over the net to the server where the current page
came from. But its ability to receive data from other sites/domains is crippled. Though
possible, it requires explicit agreement (expressed in HTTP headers) from the remote
side. Once again, that’s a safety limitation.
4 | Page
COMPUTER ARTS AND TECHNOLOGICAL COLLEGE, INC.
Balintawak St,. Albay District, Legaspi City
Such limitations do not exist if JavaScript is used outside of the browser, for example on a
server. Modern browsers also allow plugins/extensions which may ask for extended
permissions.
JavaScript is the only browser technology that combines these three things.
That’s what makes JavaScript unique. That’s why it’s the most widespread tool for creating
browser interfaces.
That said, JavaScript can be used to create servers, mobile applications, etc.
5 | Page
COMPUTER ARTS AND TECHNOLOGICAL COLLEGE, INC.
Balintawak St,. Albay District, Legaspi City
The syntax of JavaScript does not suit everyone’s needs. Different people want different
features.
That’s to be expected, because projects and requirements are different for everyone.
So, recently a plethora of new languages appeared, which are transpiled (converted) to
JavaScript before they run in the browser.
Modern tools make the transpilation very fast and transparent, actually allowing developers
to code in another language and auto-converting it “under the hood”.
us to write clearer and more precise code. Usually, Ruby devs like it.
⮚ Flow also adds data typing, but in a different way. Developed by Facebook.
⮚ Dart is a standalone language that has its own engine that runs in non-browser
environments (like mobile apps), but also can be transpiled to JavaScript. Developed
by Google.
⮚ Kotlin is a modern, concise and safe programming language that can target the
browser or Node.
There are more. Of course, even if we use one of these transpiled languages, we should
also know JavaScript to really understand what we’re doing.
Language Syntax
6 | Page
COMPUTER ARTS AND TECHNOLOGICAL COLLEGE, INC.
Balintawak St,. Albay District, Legaspi City
Language syntax refers to the set of rules that dictate how programs written in a
particular programming language must be structured. This can include rules for how to
declare variables, how to call functions, how to structure control flow statements, and
so on. Syntax varies significantly between different programming languages, so it is critical
to grasp the specific syntax of the language you are using. It’s similar to grammar in human
languages - putting words in the wrong order or including extraneous punctuation can make
a sentence hard to understand, and the same applies to programming. Incorrect syntax
leads to syntax errors which prevent your code from executing.
JavaScript Syntax
JavaScript syntax comprises a set of rules that define how to construct a JavaScript code.
JavaScript can be implemented using JavaScript statements that are placed within the
<script> ... </script> HTML tags in a web page. You can place the <script> tags, containing
your JavaScript, anywhere within your web page, but it is normally recommended that you
should keep it within the <head> tags. The <script> tag alerts the browser program to start
interpreting all the text between these tags as a script. A simple syntax of your JavaScript
will appear as follows.
<script>
</script>
JavaScript Values
JavaScript Literals
7 | Page
COMPUTER ARTS AND TECHNOLOGICAL COLLEGE, INC.
Balintawak St,. Albay District, Legaspi City
JavaScript Variables
⮚ var
⮚ let
⮚ const
You can use the assignment operator (equal sign) to assign values to the variable.
In the below code, variable a contains the numeric value, and variable b contains the text
(string).
<script>
let a = 5; // Variable Declaration
document.write(a); // Using variable
document.write("<br>");
let b = "One";
document.write(b);
</script>
Output???
8 | Page
COMPUTER ARTS AND TECHNOLOGICAL COLLEGE, INC.
Balintawak St,. Albay District, Legaspi City
JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs. You can
use spaces, tabs, and newlines freely in your program and you are free to format and indent
your programs in a neat and consistent way that makes the code easy to read and
understand.
Case Sensitivity
JavaScript is a case-sensitive language. This means that the language keywords, variables,
function names, and any other identifiers must always be typed with a consistent
capitalization of letters.
So the identifiers Time and TIME will convey different meanings in JavaScript.
9 | Page
COMPUTER ARTS AND TECHNOLOGICAL COLLEGE, INC.
Balintawak St,. Albay District, Legaspi City
Comments in JavaScript
● Any text between a // and the end of a line is treated as a comment and is ignored by
JavaScript.
● Any text between the characters /* and */ is treated as a comment. This may span
multiple lines.
● JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript
treats this as a single-line comment, just as it does the // comment.
● The HTML comment closing sequence --> is not recognized by JavaScript so it
should be written as //-->.
10 | Page
COMPUTER ARTS AND TECHNOLOGICAL COLLEGE, INC.
Balintawak St,. Albay District, Legaspi City
JAVASCRIPT
OPERATORS
11 | Page
COMPUTER ARTS AND TECHNOLOGICAL COLLEGE, INC.
Balintawak St,. Albay District, Legaspi City
Operators in JavaScript
JavaScript contains various arithmetic, logical, bitwise, etc. operators. We can use any
operator in JavaScript.
1. Arithmetic Operators
1. +
2. –
3. /
4. *
5. %
2. Logical Operator
1. AND Operator or &&
2. OR Operator or ||
3. NOT Operator or !
Example
In this example, we have defined var1 and va2 and initialized them with number values. After
that, we use the ‘*’ operator to get the multiplication result of var1 and var2.
<script>
var1 = 10
var2 = 20
var4 = 10 + 20;
</script>
Output???
12 | Page
COMPUTER ARTS AND TECHNOLOGICAL COLLEGE, INC.
Balintawak St,. Albay District, Legaspi City
JAVASCRIPT
CONTROL
STRUCTURES
13 | Page
COMPUTER ARTS AND TECHNOLOGICAL COLLEGE, INC.
Balintawak St,. Albay District, Legaspi City
Control Structures
⮚ If Statement
Approach 1: If Statement
In this approach, we are using an if statement to check a specific condition, the code block
gets executed when the given condition is satisfied.
Syntax:
if ( condition_is_given_here ) {
The if-else statement will perform some action for a specific condition. If the condition met,
then a particular code of action will be executed otherwise it will execute another code of
action that satisfies that particular condition.
14 | Page
COMPUTER ARTS AND TECHNOLOGICAL COLLEGE, INC.
Balintawak St,. Albay District, Legaspi City
Syntax:
if (condition1) {
} else {
The switch case statement in JavaScript is also used for decision-making purposes. In some
cases, using the switch case statement is seen to be more convenient than if-else
statements.
switch (expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
case valueN:
statementN;
break;
default:
15 | Page
COMPUTER ARTS AND TECHNOLOGICAL COLLEGE, INC.
Balintawak St,. Albay District, Legaspi City
statementDefault;
16 | Page
COMPUTER ARTS AND TECHNOLOGICAL COLLEGE, INC.
Balintawak St,. Albay District, Legaspi City
The conditional operator, also referred to as the ternary operator (?:), is a shortcut for
expressing conditional statements in JavaScript.
Syntax:
In this approach, we are using for loop in which the execution of a set of instructions
repeatedly until some condition evaluates and becomes false
Syntax:
// Code here . . .
Programming Fundamentals
Programming Fundamentals are the basic concepts and principles that form the foundation
of any computer programming language. These include understanding variables, which store
data for processing, control structures such as loops and conditional statements that direct
the flow of a program, data structures which organize and store data efficiently, and
algorithms which step by step instructions to solve specific problems or perform specific
tasks.
17 | Page
COMPUTER ARTS AND TECHNOLOGICAL COLLEGE, INC.
Balintawak St,. Albay District, Legaspi City
JAVASCRIPT
FUNCTIONS
18 | Page
COMPUTER ARTS AND TECHNOLOGICAL COLLEGE, INC.
Balintawak St,. Albay District, Legaspi City
Functions
Functions in programming are named sections of a program that perform a specific task.
They allow us to write a piece of code once and reuse it in different places throughout the
program, making our code more modular and easier to maintain. Functions often take in
input, do something with it, and return output. Functions can be categorized into four main
types: built-in functions (like print(), provided by the programming language), user-defined
functions (written by the user for a specific use case), anonymous functions (also known as
lambda functions, which are not declared using the standard def keyword), and higher-order
functions (functions that take other functions as arguments or return a function).
JavaScript Function
Example: A basic JavaScript function, here we create a function that divides the 1st element
by the second element.
Output: 4
Syntax:
To create a function in JavaScript, we have to first use the keyword function, separated by
the name of the function and parameters within parenthesis. The part of the function inside
19 | Page
COMPUTER ARTS AND TECHNOLOGICAL COLLEGE, INC.
Balintawak St,. Albay District, Legaspi City
the curly braces {} is the body of the function. In JavaScript, functions can be used in the
same way as variables for assignments, or calculations.
Function Invocation:
Function Definition:
Before, using a user-defined function in JavaScript we have to create one. We can use the
above syntax to create a function in JavaScript. A function definition is sometimes also
termed a function declaration or function statement. Below are the rules for creating a
function in JavaScript:
⮚ Every function should begin with the keyword function followed by,
⮚ A list of statements composing the body of the function enclosed within curly braces
{}.
Example Declaration
Output: 15
1. This function accepts two numbers as parameters and returns the addition of these
two numbers.
20 | Page
COMPUTER ARTS AND TECHNOLOGICAL COLLEGE, INC.
Balintawak St,. Albay District, Legaspi City
2. Accessing the function with just the function name without () will return the function
object instead of the function result.
21 | Page