What is JavaScript?
JavaScript is a lightweight, cross-platform, single-threaded, and
interpreted compiled programming language.
It is also known as the scripting language for webpages.
It is well-known for the development of web pages, and many non-
browser environments also use it.
JavaScript is a weakly typed language (dynamically typed). JavaScript
can be used for Client-side developments as well as Server-side developments.
JavaScript is both an imperative and declarative type of language.
JavaScript contains a standard library of objects, like Array, Date, and Math,
and a core set of language elements like operators, control structures, and
statements.
Client-side:
It supplies objects to control a browser and its Document Object Model
(DOM).
Like if client-side extensions allow an application to place elements on an
HTML form and respond to user events such as mouse clicks, form input, and
page navigation.
Useful libraries for the client side are AngularJS, ReactJS, VueJS, and
so many others.
Server-side:
It supplies objects relevant to running JavaScript on a server.
For if the server-side extensions allow an application to communicate with
a database, and provide continuity of information from one invocation to another
of the application, or perform file manipulations on a server.
The useful framework which is the most famous these days is node.js.
Why Study JavaScript?
JavaScript is one of the 3 languages all web developers must learn:
1. HTML to define the content of web pages
2. CSS to specify the layout of web pages
3. JavaScript to program the behavior of web pages
How to Link JavaScript File in HTML ?
JavaScript can be added to HTML file in two ways:
Internal JS: We can add JavaScript directly to our HTML file by writing the
code inside the <script> tag. The <script> tag can either be placed inside the
<head> or the <body> tag according to the requirement.
External JS: We can write JavaScript code in another files having an
extension.js and then link this file inside the <head> tag of the HTML file in
which we want to add this code.
Syntax:
<script>
// JavaScript Code
</script>
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>
Basic Example to Describe JavaScript
</title>
</head>
<body>
<!-- JavaScript code can be embedded inside
head section or body section -->
<script>
console.log("Welcome to Viswanathan”);
</script>
</body>
</html>
Output: The output will display on the console.
Welcome to Viswanathan
History of JavaScript
▪ It was created in 1995 by Brendan Eich while he was an engineer
at Netscape.
▪ It was originally going to be named LiveScript but was renamed.
▪ Finally, in May 1995, Marc Andreessen coined the first code of
Javascript named 'Mocha'.
▪ Later, the marketing team replaced the name with 'LiveScript'.
▪ But, due to trademark reasons and certain other reasons, in
December 1995, the language was finally renamed to 'JavaScript'.
Applications of JavaScript
Web Development: Adding interactivity and behavior to static sites JavaScript
was invented to do this in 1995. By using AngularJS that can be achieved so
easily.
Web Applications: With technology, browsers have improved to the extent that
a language was required to create robust web applications. When we explore a
map in Google Maps then we only need to click and drag the mouse. All detailed
view is just a click away, and this is possible only because of JavaScript. It uses
Application Programming Interfaces(APIs) that provide extra power to the
code. The Electron and React are helpful in this department.
Server Applications: With the help of Node.js, JavaScript made its way from
client to server and Node.js is the most powerful on the server side.
Games: Not only in websites, but JavaScript also helps in creating games for
leisure. The combination of JavaScript and HTML 5 makes JavaScript popular in
game development as well. It provides the EaseJS library which provides
solutions for working with rich graphics.
Smartwatches: JavaScript is being used in all possible devices and applications.
It provides a library PebbleJS which is used in smartwatch applications. This
framework works for applications that require the Internet for their functioning.
Art: Artists and designers can create whatever they want using JavaScript to draw
on HTML 5 canvas, and make the sound more effective also can be used p5.js
library.
Machine Learning: This JavaScript ml5.js library can be used in web
development by using machine learning.
Advantages of JavaScript
The merits of using JavaScript are:
Less server interaction: You can validate user input before sending the page
off to the server. This saves server traffic, which means less load on your server.
Immediate feedback to the visitors: They don't have to wait for a page reload
to see if they have forgotten to enter something.
Increased interactivity: You can create interfaces that react when the user
hovers over them with a mouse or activates them via the keyboard.
Richer interfaces: You can use JavaScript to include such items as drag-and
drop components and sliders to give a Rich Interface to your site visitors.
Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the
following important features:
Client-side JavaScript does not allow the reading or writing of files. This has
been kept for security reason.
JavaScript cannot be used for networking applications because there is no such
support available.
JavaScript doesn't have any multithreading or multiprocessor capabilities.
Once again, JavaScript is a lightweight, interpreted programming language that
allows you to build interactivity into otherwise static HTML pages.
JavaScript language basics:
JavaScript Statements:
For Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p>A <b>JavaScript program</b> is a list of <b>statements</b> to
be executed by a computer.</p>
<p id="demo"></p>
<script>
let x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4
document.getElementById("demo").innerHTML =
"The value of z is " + z + ".";
</script>
</body>
</html>
Output:
JavaScript Statements
A JavaScript program is a list of statements to be executed by a
computer.
The value of z is 11.
The getElementById() method returns an element with a specified value.
The getElementById() method returns null if the element does not exist.
The getElementById() method is one of the most common methods in the HTML
DOM. It is used almost every time you want to read or edit an HTML element.
JavaScript Programs
• A computer program is a list of "instructions" to be "executed" by a
computer.
• In a programming language, these programming instructions are called
statements.
• A JavaScript program is a list of programming statements.
• In HTML, JavaScript programs are executed by the web browser.
JavaScript Statements
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
This statement tells the browser to write "Hello Dolly." inside an HTML element
with id="demo":
Example
document.getElementById("demo").innerHTML = "Hello Dolly.";
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p>In HTML, JavaScript statements are executed by the
browser.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello Dolly.";
</script>
</body>
</html>
Output:
JavaScript Statements
In HTML, JavaScript statements are executed by the browser.
Hello Dolly
Semicolons ;
Semicolons separate JavaScript statements.
Add a semicolon at the end of each executable statement:
Examples
let a, b, c; // Declare 3 variables
a = 5; // Assign the value 5 to a
b = 6; // Assign the value 6 to b
c = a + b; // Assign the sum of a and b to c
When separated by semicolons, multiple statements on one line are allowed:
a = 5; b = 6; c = a + b;
JavaScript White Space
JavaScript ignores multiple spaces. You can add white space to your script to
make it more readable.
The following lines are equivalent:
let person = "Hege";
let person="Hege";
A good practice is to put spaces around operators ( = + - * / ):
let x = y + z;
JavaScript Code Blocks
✓ JavaScript statements can be grouped together in code blocks, inside
curly brackets {...}.
✓ The purpose of code blocks is to define statements to be executed
together.
One place you will find statements grouped together in blocks, is in JavaScript
functions:
Example
function myFunction()
document.getElementById("demo1").innerHTML = "Hello Dolly!";
document.getElementById("demo2").innerHTML = "How are you?";
For Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p>JavaScript code blocks are written between { and }</p>
<button type="button" onclick="myFunction()">Click Me!</button>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
function myFunction() {
document.getElementById("demo1").innerHTML = "Hello Dolly!";
document.getElementById("demo2").innerHTML = "How are you?";
</script>
</body>
</html>
Output:
JavaScript Statements
JavaScript code blocks are written between { and }
Click Me!
Hello Dolly!
How are you?
JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript action
to be performed.
Our Reserved Words Reference lists all JavaScript keywords.
Keyword Description
var Declares a variable
let Declares a block variable
const Declares a block constant
if Marks a block of statements to be executed on a condition
switch Marks a block of statements to be executed in different cases
for Marks a block of statements to be executed in a loop
function Declares a function
return Exits a function
try Implements error handling to a block of statements
Java Script Variables:
Variables are Containers for Storing Data
JavaScript Variables can be declared in 4 ways:
Automatically
Using var
Using let
Using const
In this first example, x, y, and z are undeclared variables.
They are automatically declared when first used:
Example
x = 5;
y = 6;
z = x + y;
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>
<p>In this example, x, y, and z are variables.</p>
<p id="demo"></p>
<script>
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>
</body>
</html>
Output:
JavaScript Variables
In this example, x, y, and z are variables.
The value of z is: 11
JavaScript Events:
JavaScript events are actions or occurrences that happen in the browser,
which can be captured and handled by JavaScript.
Events are essential for making web pages interactive.
1. Event Types
Common event types include:
Mouse Events: click, dblclick, mousedown, mouseup, mouseover,
mouseout, mousemove
Keyboard Events: keydown, keyup, keypress
Form Events: submit, change, focus, blur
Window Events: load, resize, scroll, unload
2. Event Listeners
Event listeners are used to execute code when an event occurs.
Adding Event Listeners
The addEventListener method is used to attach an event handler to an element.
// Select the element
let button = document.getElementById("myButton");
// Add an event listener
button.addEventListener("click", function() {
alert("Button clicked!");
});
Removing Event Listeners
You can remove an event listener using the removeEventListener method.
function clickHandler() {
alert("Button clicked!");
// Add event listener
button.addEventListener("click", clickHandler);
// Remove event listener
button.removeEventListener("click", clickHandler);
3. Event Object
When an event occurs, an event object is created, containing properties and
methods related to the event.
button.addEventListener("click", function(event) {
console.log(event.type); // "click"
console.log(event.target); // The element that was clicked
});
4. Event Propagation
Events propagate through the DOM in three phases: capturing, target, and
bubbling.
Capturing Phase: The event starts from the document root and goes down to
the target element.
Target Phase: The event reaches the target element.
Bubbling Phase: The event bubbles up from the target element to the document
root.
Stopping Event Propagation
You can stop the event from propagating further using
event.stopPropagation().
let innerDiv = document.getElementById("innerDiv");
let outerDiv = document.getElementById("outerDiv");
innerDiv.addEventListener("click", function(event) {
event.stopPropagation();
alert("Inner div clicked!");
});
outerDiv.addEventListener("click", function() {
alert("Outer div clicked!");
});
5. Event Delegation
Event delegation involves using a single event listener to manage all
events of a particular type for child elements.
let list = document.getElementById("myList");
list.addEventListener("click", function(event) {
if (event.target.tagName === "LI") {
alert("List item clicked: " + event.target.textContent);
});
6. Common Events and Examples
Mouse Events
let box = document.getElementById("box");
// Click event
box.addEventListener("click", function() {
console.log("Box clicked!");
});
// Mouseover event
box.addEventListener("mouseover", function() {
console.log("Mouse over box!");
});
Keyboard Events
let input = document.getElementById("inputField");
// Keydown event
input.addEventListener("keydown", function(event) {
console.log("Key pressed: " + event.key);
});
// Keyup event
input.addEventListener("keyup", function(event) {
console.log("Key released: " + event.key);
});
Form Events
let form = document.getElementById("myForm");
// Submit event
form.addEventListener("submit", function(event) {
event.preventDefault(); // Prevent form submission
console.log("Form submitted!");
});
// Change event
let select = document.getElementById("mySelect");
select.addEventListener("change", function() {
console.log("Selected option: " + select.value);
});
Window Events
// Load event
window.addEventListener("load", function() {
console.log("Window loaded!");
});
// Resize event
window.addEventListener("resize", function() {
console.log("Window resized!");
});
Example for Click Event:
<!DOCTYPE html>
<html>
<head>
<title>Click Event Example</title>
</head>
<body>
<button id="clickButton">Click Me!</button>
<script>
document.getElementById("clickButton").addEventListener("click",
function() {
alert("Button was clicked!");
});
</script>
</body>
</html>
Output:
Click me
Example for Mouseover and Mouseout Events:
<!DOCTYPE html>
<html>
<head>
<title>Mouse Events Example</title>
</head>
<body>
<div id="hoverBox" style="width: 100px; height: 100px; background-color:
lightblue;">Hover over me!</div>
<script>
let hoverBox = document.getElementById("hoverBox");
hoverBox.addEventListener("mouseover", function() {
hoverBox.style.backgroundColor = "lightgreen";
});
hoverBox.addEventListener("mouseout", function() {
hoverBox.style.backgroundColor = "lightblue";
});
</script>
</body>
</html>
Output:
Hover over me!
Example for Keydown Event:
<!DOCTYPE html>
<html>
<head>
<title>Keydown Event Example</title>
</head>
<body>
<input type="text" id="inputField" placeholder="Type something...">
<script>
document.getElementById("inputField").addEventListener("keydown",
function(event) {
console.log("Key pressed: " + event.key);
});
</script>
</body>
</html>
Output:
Example for Submit Event:
<!DOCTYPE html>
<html>
<head>
<title>Form Submit Event Example</title>
</head>
<body>
<form id="myForm">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<button type="submit">Submit</button>
</form>
<script>
document.getElementById("myForm").addEventListener("submit",
function(event) {
event.preventDefault(); // Prevent form submission
alert("Form submitted!");
});
</script>
</body>
</html>
Output:
Username Password Submit
Data Types:
What are data types?
Data types in general define what specific kind of data we want to store in
and get manipulated within the program.
So mainly the categories of DataTypes in javascript are:
Primitive data type
Composite data type (Non-Primitve)
1.Primitive data type
These data types can hold only a single value. For example
String
Number
Boolean
a. String data type
To represent textual data we use String data type.
Let’s say we want to create a sequence of characters So this is how we create
them:
let name = “Siddhant”;
So you see above we used a variable let with variable name as name, our String
in double quotes “ ” or you can use single quotation ‘ ‘ marks also and last but
not least separating them with Assignment operator equal = symbol.
Quick Example:
let city = “New York”; // Using double quotes
let street_name = ‘E 5th Street’; // Using single quotes
Don’t be confused, In street_name the value is ‘E 5th Street’ String can have
digits, Alphabets, and Symbols unless and until they are inside the quotation
mark.
b. Number data type
To represent a numerical value we use the Number data type.
We can also define our numerical value as negative or positive, Integer, Float,
hexadecimal, octal or exponential value.
Always remember the first digit should always be an integer value in the number
data type.
And Most important do not use any quotation mark for the number data type.
So this is how we create them:
let x = 55;
So you see we used again a variable let with variable name as x, our number value
as 55 and separating them with Assignment operator equal = symbol.
Quick Example:
let ID = 2197; // positive integer
let score = 45.25; // Float
let blood_sugar = -20; // negative integer
let Title_Color = 0x854712; // Hexadecimal
let problem = 2.06e+3; // exponential
c. Boolean data type
In Boolean, we have two values either true or false.
Mostly this type is used for conditional statements like if-else, else-if, switch,
while, do...while, But it can also be defined as a value to a variable.
Now have a look at how it is created:
let alive = true;
So you see we used a variable let with variable name as alive and alive status
value as true and separating them with Assignment operator equal = symbol
Quick example:
let online_status = true;
let homework_submitted = false;
2. Composite data types
The composite data type is also known as the non-primitive data type. It can hold
more collections of complex values. For example
Array
Object
a. Array
• In Array, we can store multiple values using a single variable.
• Every element in the array has a numerical index value, which shows the
position of an element in the array.
• Arrays in javascript can have elements of different data types like String,
boolean, number, object, function, and other arrays too.
Important note: The index of an array starts with 0, not from 1.
let myArray = [10,20,30,40,50];
So to create an array we first declare the variable, then inside the [ ] square
brackets, there are elements separated by, comma.
b. Object
• Object in javascript is a non-primitive data type that allows us to store
multiple collections of data.
• For each data in an object, there is a property that is defined as a key-value
pair, But these keys can always be a string and its value can be any data type like,
number, string, boolean, array, function, and also other objects.
let myObj = {
“height-Cm”: 175,
“weight-lbs”: 275,
“distance-km”: 75
};
So you see we used curly brackets for our object inside that we defined property
in double-quotes and assigned a value separated with : colon.
We can skip the double-quote unless we write our object as shown below:
let myObj = {
heightCM: 175,
weightLBS: 275,
distanceKM: 75
};
3. Special data type
There are two special data types in javascript namely undefined and null.
a. Undefined data type
A variable that is declared but never assigned a value is undefined. Example :
let a;
console.log(a); // a is undefined
b. Null data type
• A variable that has only one value that is null itself.
• This clearly states that there is not value in the variable.
• And it is not the same as empty string or 0 or undefined.
• Null is specially passed to the variable.
Example:
let a = null;
console.log(a); // a gives us null
Conditional Statements in JavaScript
JavaScript conditional statements allow you to execute specific blocks of
code based on conditions.
If the condition is met, a particular block of code will run; otherwise,
another block of code will execute based on the condition.
There are several methods that can be used to perform Conditional Statements in
JavaScript.
Conditional Statement Description
if statement Executes a block of code if a specified condition is true.
else statement Executes a block of code if the same condition of the
preceding if statement is false.
else if statement Adds more conditions to the if statement, allowing for
multiple alternative conditions to be tested.
switch statement Evaluates an expression, then executes the case statement that
matches the expression’s value.
ternary operator Provides a concise way to write if-else statements in a single
line.
Nested if else statement Allows for multiple conditions to be checked in a
hierarchical manner.
JavaScript Conditional statements Examples:
1. Using if Statement
The if statement is used to evaluate a particular condition. If the condition holds
true, the associated code block is executed.
Syntax:
if ( condition ) {
// If the condition is met,
//code will get executed.
}
Example: In this example, we are using the if statement to find given number is
even or odd.
let num = 20;
if (num % 2 === 0) {
console.log("Given number is even number.");
if (num % 2 !== 0) {
console.log("Given number is odd number."); };
Output
Given number is even number.
Explanation: This JavaScript code determines if the variable `num` is even or odd
using the modulo operator `%`. If `num` is divisible by 2 without a remainder, it
logs “Given number is even number.” Otherwise, it logs “Given number is odd
number.”
2. Using if-else Statement
The if-else statement will perform some action for a specific condition.
Here we are using the else statement in which the else statement is written after
the if statement and it has no condition in their code block.
Syntax:
if (condition1) {
// Executes when condition1 is true
if (condition2) {
// Executes when condition2 is true
Example: In this example, we are using if-else conditional statement to check the
driving licence eligibility date.
let age = 25;
if (age >= 18) {
console.log("You are eligible of driving licence")
} else {
console.log("You are not eligible for driving licence")
};
Output
You are eligible of driving licence
Explanation: This JavaScript code checks if the variable `age` is greater than or
equal to 18. If true, it logs “You are eligible for a driving license.” Otherwise, it
logs “You are not eligible for a driving license.” This indicates eligibility for
driving based on age.
3. else if Statement
The else if statement in JavaScript allows handling multiple possible
conditions and outputs, evaluating more than two options based on whether the
conditions are true or false.
Syntax:
if (1st condition) {
// Code for 1st condition
} else if (2nd condition) {
// Code for 2nd condition
} else if (3rd condition) {
// Code for 3rd condition
} else {
// ode that will execute if all
// above conditions are false
Example: In this example, we are using the above-explained approach.
const num = 0;
if (num > 0) {
console.log("Given number is positive.");
} else if (num < 0) {
console.log("Given number is negative.");
} else {
console.log("Given number is zero.");
};
Output
Given number is zero.
Explanation: This JavaScript code determines whether the constant `num` is
positive, negative, or zero. If `num` is greater than 0, it logs “Given number is
positive.” If `num` is less than 0, it logs “Given number is negative.” If neither
condition is met (i.e., `num` is zero), it logs “Given number is zero.”
4. Using Switch Statement (JavaScript Switch Case)
As the number of conditions increases, you can use multiple else-if
statements in JavaScript. but when we dealing with many conditions, the switch
statement may be a more preferred option.
Syntax:
switch (expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
...
case valueN:
statementN;
break;
default:
statementDefault;
};
Example: In this example, we find a branch name Based on the student’s marks,
this switch statement assigns a specific engineering branch to the variable Branch.
The output displays the student’s branch name,
const marks = 85;
let Branch;
switch (true) {
case marks >= 90:
Branch = "Computer science engineering";
break;
case marks >= 80:
Branch = "Mechanical engineering";
break;
case marks >= 70:
Branch = "Chemical engineering";
break;
case marks >= 60:
Branch = "Electronics and communication";
break;
case marks >= 50:
Branch = "Civil engineering";
break;
default:
Branch = "Bio technology";
break;
console.log(`Student Branch name is : ${Branch}`);
Output
Student Branch name is : Mechanical engineering
Explanation:
This JavaScript code assigns a branch of engineering to a student based on their
marks. It uses a switch statement with cases for different mark ranges. The
student’s branch is determined according to their marks and logged to the console.
5. Using Ternary Operator ( ?: )
The conditional operator, also referred to as the ternary operator (?:), is a
shortcut for expressing conditional statements in JavaScript.
Syntax:
condition ? value if true : value if false
Example: In this example, we use the ternary operator to check if the user’s age
is 18 or older. It prints eligibility for voting based on the condition.
let age = 21;
const result =
(age >= 18) ? "You are eligible to vote."
: "You are not eligible to vote.";
console.log(result);
Output
You are eligible to vote.
Explanation: This JavaScript code checks if the variable `age` is greater than or
equal to 18. If true, it assigns the string “You are eligible to vote.” to the variable
`result`. Otherwise, it assigns “You are not eligible to vote.” The value of `result`
is then logged to the console.
6. Nested if…else
Nested if…else statements in JavaScript allow us to create complex conditional
logic by checking multiple conditions in a hierarchical manner. Each if statement
can have an associated else block, and within each if or else block, you can nest
another if…else statement. This nesting can continue to multiple levels, but it’s
important to maintain readability and avoid excessive complexity.
Syntax:
if (condition1) {
// Code block 1
if (condition2) {
// Code block 2
} else {
// Code block 3
} else {
// Code block 4
Example: This example demonstrates how nested if…else statements can be used
to handle different scenarios based on multiple conditions.
let weather = "sunny";
let temperature = 25;
if (weather === "sunny") {
if (temperature > 30) {
console.log("It's a hot day!");
} else if (temperature > 20) {
console.log("It's a warm day.");
} else {
console.log("It's a bit cool today.");
} else if (weather === "rainy") {
console.log("Don't forget your umbrella!");
} else {
console.log("Check the weather forecast!");
};
Output
It's a warm day.
Explanation: In this example, the outer if statement checks the weather variable.
If it’s “sunny,” it further checks the temperature variable to determine the type of
day it is (hot, warm, or cool). Depending on the values of weather and
temperature, different messages will be logged to the console.
JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for, while, do
while or for-in loops. It makes the code compact. It is mostly used in array.
There are four types of loops in JavaScript.
1. for loop
2. while loop
3. do-while loop
1) JavaScript For loop
The JavaScript for loop iterates the elements for the fixed number of times. It
should be used if number of iteration is known. The syntax of for loop is given
below.
for (initialization; condition; increment)
code to be executed
Example:
<!DOCTYPE html>
<html>
<body>
<script>
for (i=1; i<=5; i++)
document.write(i + "<br/>")
</script>
</body>
</html>
Output:
5
JavaScript while loop
The JavaScript while loop iterates the elements for the infinite number of times.
It should be used if number of iteration is not known. The syntax of while loop is
given below.
while (condition)
code to be executed
Let’s see the simple example of while loop in javascript.
<script>
var i=11;
while (i<=15)
document.write(i + "<br/>");
i++;
</script>
Output:
11
12
13
14
15
JavaScript do while loop
The JavaScript do while loop iterates the elements for the infinite number of times
like while loop. But, code is executed at least once whether condition is true or
false. The syntax of do while loop is given below.
do{
code to be executed
}while (condition);
Let’s see the simple example of do while loop in javascript.
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
Output:
21
22
23
24
25