[go: up one dir, main page]

0% found this document useful (0 votes)
6 views24 pages

Unit - III

JavaScript is a versatile programming language essential for web development, allowing dynamic interaction with HTML and CSS. It was created by Brendan Eich in 1995 and has evolved to become a fundamental technology used by approximately 95% of websites. Key features include its ability to manipulate the Document Object Model (DOM), handle events, and define functions for reusable code.

Uploaded by

sarfraz ahamed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views24 pages

Unit - III

JavaScript is a versatile programming language essential for web development, allowing dynamic interaction with HTML and CSS. It was created by Brendan Eich in 1995 and has evolved to become a fundamental technology used by approximately 95% of websites. Key features include its ability to manipulate the Document Object Model (DOM), handle events, and define functions for reusable code.

Uploaded by

sarfraz ahamed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

UNIT III

Javascript
Introduction
●​ JavaScript is the programming language of the web.
●​ It can update and change both HTML and CSS.
●​ It can calculate, manipulate and validate data.
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
JavaScript is a versatile, dynamically typed programming language used for interactive web
applications, supporting both client-side and server-side development, and integrating
seamlessly with HTML, CSS, and a rich standard library.
●​ JavaScript is a single-threaded language that executes one task at a time.
●​ It is an Interpreted language which means it executes the code line by line.
●​ The data type of the variable is decided at run-time in JavaScript that’s why it is
called dynamically typed.
JavaScript Can Change HTML Content
One of many JavaScript HTML methods is getElementById().
The example below "finds" an HTML element (with id="demo"), and changes the
element content (innerHTML) to "Hello JavaScript":
document.getElementById("demo").innerHTML = "Hello JavaScript";
Note: JavaScript accepts both double and single quotes
document.getElementById('demo').innerHTML = 'Hello JavaScript';
History of Javascript
JavaScript, designed to add interactivity to web pages, was created by Brendan Eich
at Netscape in 1995, initially named Mocha, then LiveScript, and finally JavaScript, aiming
to capitalize on Java's popularity.

Early Development (1995):

●​ Brendan Eich, working at Netscape Communications Corporation, developed


JavaScript in just 10 days in May 1995.
●​ The initial goal was to create a scripting language that could add interactivity to web
pages and enable developers to create dynamic content.
●​ The language was initially named "Mocha" internally, but was later renamed
"LiveScript".
●​ Netscape ultimately chose the name "JavaScript" to capitalize on the popularity of the
Java programming language
JavaScript was first implemented in Netscape Navigator, the most popular browser at
the time. Microsoft quickly adopted it for Internet Explorer. Its ease of use and unique
position as the only client-side scripting language made JavaScript popular among web
developers.

Over the years, JavaScript’s popularity grew, and it was used to create a variety of web
applications, including online games, dynamic menus, and form validation. A new version,
ECMAScript 4, was planned in 2002 but was abandoned due to disagreements among
browser vendors.

Today, JavaScript is one of the most popular programming languages, used by about
95% of websites. It is not only crucial for web development but also for creating server-side
applications, desktop and mobile apps, and even programming robots and hardware.

Hello World Webpage

A “Hello, World!” program is the simplest way to get started with any programming
language. Here’s how you can write one using JavaScript.
<html>
<head></head>
<body>
<h1>Check the console for the message!</h1>
<script>
// This is our first JavaScript program
console.log("Hello, World!");
</script>
</body>
</html>
In this example
●​ The <script> tag is used to include JavaScript code inside an HTML document.
●​ console.log() prints messages to the browser’s developer console. Open the browser
console to see the “Hello, World!” message.
“Hello World” Program in Server Console
We can also print the “Hello World” program directly into the console terminal
without embedded it into HTML. Create an index.js file and add the code to it.
/*
This is a multi-line comment.
It can span several lines.
*/
console.log("Hello, World!"); // Prints Hello, World! to the console
In this example
●​ console.log(): The console.log() method is used to print messages to the browser’s
developer console. Open the console (usually with F12 or Ctrl + Shift + J) to see the
message “Hello, World!” displayed.
●​ Comments in the Code:
​ Multi-line Comment: The /* */ syntax is used to write a comment spanning multiple
lines.
​ Single-line Comment: The // syntax is used for short, inline comments, like the one
explaining the console.log function.
JavaScript Button
JavaScript button is one of the JavaScript elements which gives effects to web pages.
JavaScript buttons give a good look and feel to the website. These JavaScript buttons can be
used to send or receive data; fire clicks events, change the color or text, etc. HTML tag
<button> is used in JavaScript frameworks that define a clickable button. When a button is
rendered onto the web page, an event is fired to perform a functionality. We shall look into
the creation of JavaScript buttons by using createElement() and an HTML tag, which is used
for JavaScript frameworks.
Syntax:
Using <button> HTML tag for JavaScript Buttons
●​ <button onclick="sampleFunction()">Sample Text</button>
Example #1
Creating a JavaScript Button using <button> tag
Code:
<!DOCTYPE html>
<html>
<body>
<h3>Creation of a JavaScript Button using HTML tag</h3>
<p>As there is no functionality or any event linked, clicking button will not work</p>
<button type="button" id="btn">Click Here!</button>
<p id="samplebtn"></p>
<script>
</script>
</body>
</html>

Different types of Buttons.


Functions in Javascript
A function is a "subprogram" that can be called by code external (or internal, in the
case of recursion) to the function. Like the program itself, a function is composed of a
sequence of statements called the function body. Values can be passed to a function as
parameters, and the function will return a value.
In JavaScript, functions are first-class objects, because they can be passed to other
functions, returned from functions, and assigned to variables and properties. They can also
have properties and methods just like any other object. What distinguishes them from other
objects is that functions can be called.

Description
Function values are typically instances of Function. See Function for information on
properties and methods of Function objects. Callable values cause typeof to
return "function" instead of "object".

Return Value
By default, if a function's execution doesn't end at a return statement, or if
the return keyword doesn't have an expression after it, then the return value is undefined.
The return statement allows you to return an arbitrary value from the function. One function
call can only return one value, but you can simulate the effect of returning multiple values by
returning an object or array and destructuring the result.
Passing arguments
Parameters and arguments have slightly different meanings, but in MDN web docs,
we often use them interchangeably. For a quick reference:
function formatNumber(num) {
return num.toFixed(2);
}
formatNumber(2);
In this example, the num variable is called the function's parameter: it's declared in
the parenthesis-enclosed list of the function's definition. The function expects
the num parameter to be a number — although this is not enforceable in JavaScript without
writing runtime validation code. In the formatNumber(2) call, the number 2 is the
function's argument: it's the value that is actually passed to the function in the function call.
The argument value can be accessed inside the function body through the corresponding
parameter name or the arguments object.
Arguments are always passed by value and never passed by reference. This means
that if a function reassigns a parameter, the value won't change outside the function. More
precisely, object arguments are passed by sharing, which means if the object's properties are
mutated, the change will impact the outside of the function.
There are three main types of functions in JavaScript: named functions, anonymous
functions, and arrow functions. Let’s take a closer look at each one.
Named Functions
Named functions are function declarations that include a name. They are also
sometimes referred to as traditional functions or function declarations. Here is an example:
function helloWorld() {
console.log('Hello World!');
}
Named functions are typically used when the same code needs to be executed
multiple times throughout a program. They should always be declared before they are used.

Anonymous Functions
Anonymous functions are function expressions that do not have a name associated with them.
They are also sometimes referred to as lambda functions or function expressions. Here is an
example:
let helloWorld = function () {
console.log('Hello World!');
}
Anonymous functions are typically used when the same code needs to be executed only once
or twice throughout a program. They can be assigned to variables or passed as parameters to
other functions.
Arrow Functions
Arrow functions are a shorthand syntax for anonymous functions that was introduced
in ECMAScript 6 (ES6). They are also sometimes referred to as fat arrow functions or
lambda shorthand. Here is an example:
let helloWorld = () =&gt; {
console.log('Hello World!');
}
Arrow functions are typically used when writing concise code and when the same
code needs to be executed only once or twice throughout a program. They can be assigned to
variables or passed as parameters to other functions.
JavaScript functions are reusable blocks of code that perform a specific task, taking
some form of input and returning an output.
To define a function, you must use the function keyword, followed by a name,
followed by parentheses ( ). Then you have to write the function logic between curly
brackets { }
Here is an example of how to write a function in JavaScript:

EXAMPLE

function addTwoNumbers(x, y) {​
return x + y;​
}

DOMs

In JavaScript, the Document Object Model (DOM) is a programming interface that


represents a web page as a tree structure of objects, allowing JavaScript to interact with and
manipulate the content, structure, and style of a webpage.

The HTML DOM (Document Object Model) is a programming interface that


represents the structure of a web page in a way that programming languages like JavaScript
can understand and manipulate.
The DOM connects your webpage to JavaScript, allowing you to:
●​ Access elements (like finding an <h1> tag).
●​ Modify content (like changing the text of a <p> tag).
●​ React to events (like a button click).
●​ Create or remove elements dynamically.
Properties of the DOM
●​ Node-Based: Everything in the DOM is represented as a node (e.g., element nodes,
text nodes, attribute nodes).
●​ Hierarchical: The DOM has a parent-child relationship, forming a tree structure.
●​ Live: Changes made to the DOM using JavaScript are immediately reflected on the
web page.
●​ Platform-Independent: It works across different platforms, browsers, and
programming languages.
Example: In this example, We use HTML element id to find the DOM HTML element.
<html>
<body>
<h2>GeeksforGeeks</h2>
<!-- Finding the HTML Elements by their Id in DOM -->
<p id="intro">
A Computer Science portal for geeks.
</p>
<p>
This example illustrates the <b>getElementById</b> method.
</p>
<p id="demo"></p>
<script>
const element = document.getElementById("intro");
document.getElementById("demo").innerHTML =
"GeeksforGeeks introduction is: " + element.innerHTML;
</script>
</body>
</html>

Output:

Forms and Event Handlers


The form events in JavaScript are events that are associated with HTML forms. These
events are triggered by user actions when interacting with form elements like text fields,
buttons, checkboxes, etc. Form events allow you to execute JavaScript code in response to
these actions, enabling you to validate form data, perform actions on form submission or
reset, and enhance the user experience.
HTML events are "things" that happen to HTML elements.
When JavaScript is used in HTML pages, JavaScript can "react" on these events.
HTML Events
An HTML event can be something the browser does, or something a user does.
Here are some examples of HTML events:
●​ An HTML web page has finished loading
●​ An HTML input field was changed
●​ An HTML button was clicked
Often, when events happen, you may want to do something.
JavaScript lets you execute code when events are detected.
HTML allows event handler attributes, with JavaScript code, to be added to HTML
elements.
With single quotes:
<element event='some JavaScript'>
With double quotes:
<element event="some JavaScript">
In the following example, an onclick attribute (with code), is added to
a <button> element:
Example
<button onclick="document.getElementById('demo').innerHTML = Date()">The time
is?</button>
In the example above, the JavaScript code changes the content of the element with
id="demo".
In the next example, the code changes the content of its own element
(using this.innerHTML):
Example
<button onclick="this.innerHTML = Date()">The time is?</button>
JavaScript code is often several lines long. It is more common to see event attributes calling
functions:
Example
<button onclick="displayDate()">The time is?</button>
JavaScript form events are hooked onto the elements in the Document Object Model
also known as DOM where by default the bubbling propagation is used i.e. from bottom
(children) to top(parent).
List of Common Form Events

Example
Open Compiler
<!DOCTYPE html>
<html>
<body>
<label for="country">Select a country:</label>
<select id="country" onchange="handleChange()">
<option value="USA">USA</option>
<option value="Canada">Canada</option>
<option value="UK">UK</option>
<option value="India">India</option>
</select>
<p id="txt"></p>
<script>
function handleChange() {
// Perform actions when the dropdown selection changes
var selectedCountry = document.getElementById('country').value;
document.getElementById("txt").textContent=
​ ​ "Selected country: "+selectedCountry;
}
</script>
</body>
</html>

Window Object
The window object represents an open window in a browser.
If a document contain frames (<iframe> tags), the browser creates one
window object for the HTML document, and one additional window object for
each frame.

Window Object Properties


Property Name Description

window.document Refers to the Document object representing the HTML document shown in the window.

window.console Returns the window’s Console object.

The location attribute makes reference to the Location object, which has data about the
window.location
page’s current URL.

window.defaultStatus It is now Abandoned.

window.closed If a window is closed, it returns a true boolean value.

window.frameElement It gives the window’s current frame back.

window.frame returns every window item currently active in the window.

window.history Retrieves the window’s History object.

window.length It gives the number of iframe> elements currently present in the window.

window.localStorage provides the ability to store key/value pairs in a web browser. stores data without a time.
window.innerWidth and Without including the toolbars and scrollbars, these characteristics describe the width
window.innerHeight & height of the browser window.

window.opener It returns a pointer to the window that created the window in the opener function.

You can use outerHeight to return the height of the browser window, including toolbars and
window.outerHeight
scrollbars.

You can outerWidth to get the width of the browser window, including toolbars and
window.outerWidth
scrollbars.

window.name Returns or sets a window’s name.

window.parent Brings up the current window’s parent window.

Provides the ability to store key/value pairs in a web browser. Contains data for a single
window.sessionStorage
session.

window.scrollX It is a pageXOffset alias.

window.scrollY It is a pageYOffset alias.

window.self It provides the window’s current state.

window.status It is now Deprecated. Don’t employ it.

window.top It provides the top-most browser window back.

The screen attribute makes reference to the Screen object, which stands in for the screen that
window.screen
the browser is shown on.

The History object, which includes details about the current page’s browsing history, is the
window.history
subject of the history property.

window.pageXOffset The number of pixels that the current document has been scrolled horizontally.

window.pageYOffset The number of pixels that the current document has been scrolled vertically.

window.screenLeft: The x-coordinate of the current window relative to the screen.

window.screenTop The y-coordinate of the current window relative to the screen.

window.screenX The x-coordinate of the current window relative to the screen (deprecated).

window.screenY The y-coordinate of the current window relative to the screen (deprecated).
window.navigator An object representing the browser and its capabilities

Window Object Properties Examples


Example 1: We will use the console property in this example to show how it works.
// This is console property
console.log(window.location)
Output:
Location {ancestorOrigins: DOMStringList, href: 'chrome://new-tab-page/', origin:
'chrome://new-tab-page', protocol: 'chrome:', host: 'new-tab-page', …}
Window Object Methods:
Methods in JavaScript are functions associated with objects. They perform operations
or calculate values. Here are some methods of the Window object:
Syntax:
window.MethodName()
IF Statement
JavaScript if-else statement executes a block of code based on a condition. If the
condition evaluates to true, the code inside the “if” block executes; otherwise, the code inside
the “else” block, if present, executes.
Such control statements are used to cause the flow of execution to advance and branch
based on changes to the state of a program.
Example: This example describes the if-statement in JavaScript.
// JavaScript program to illustrate If statement
let i = 10;
if (i > 15) console.log("10 is less than 15");
// This statement will be executed
// as if considers one statement by default
console.log("I am Not in if");
Output
I am Not in if
JavaScript’s conditional statements
Types of IF Statement
●​ JavaScript if-statement
●​ JavaScript if-else statement
●​ JavaScript nested-if statement
●​ JavaScript if-else-if ladder statement

JavaScript IF-Statement
It is a conditional statement used to decide whether a certain statement or block of
statements will be executed or not i.e. if a certain condition is true then a block of statements
is executed otherwise not.
Syntax:
if(condition) ​
{​
// Statements to execute if​
// condition is true​
}
The if statement accepts boolean values – if the value is true then it will execute the
block of statements under it. If we do not provide the curly braces ‘{‘ and ‘}’ after if(
condition ) then by default if statement considers the immediate one statement to be inside its
block. For example,
if(condition)​
statement1;​
statement2;​
// Here if the condition is true, if block ​
// will consider only statement1 to be inside ​
// its block.
Flow Chart:

if-condition statement
Example: Here is a simple example demonstrating the if statement.
// JavaScript program to illustrate If statement
let age = 19;
if (age > 18)
console.log("Congratulations, You are eligible to drive");
Output
Congratulations, You are eligible to drive
JavaScript IF-Else Statement
The If statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But what if we want to do something else if
the condition is false? Here comes the else statement. We can use the else statement with the
if statement to execute a block of code when the condition is false.
Syntax:
if (condition)​
{​
// Executes this block if​
// condition is true​
}​
else​
{​
// Executes this block if​
// condition is false​
}
Flow Chart:

if-else statement
Example: This example describes the if-else statement in Javascript.
// JavaScript program to illustrate If-else statement
let i = 10;
if (i < 15)
console.log("i is less than 15");
else
console.log("I am Not in if");
Output
i is less than 15

JavaScript Nested-IF Statement


JavaScript allows us to nest if statements within if statements. i.e, we can place an if
statement inside another if statement. A nested if is an if statement that is the target of another
if or else.
Syntax:
if (condition1) ​
{​
// Executes when condition1 is true​
if (condition2) ​
{​
// Executes when condition2 is true​
}​
}
Flow Chart:

nested-if statement
Example: This example describes the nested-if statement in Javascript.
// JavaScript program to illustrate nested-if statement
let i = 10;
if (i == 10) { // First if statement
if (i < 15) {
console.log("i is smaller than 15");
// Nested - if statement
// Will only be executed if statement above
// it is true
if (i < 12)
Output
i is smaller than 15
i is smaller than 12 too
JavaScript If-Else-If Ladder Statement
Here, a user can decide among multiple options. The if statements are executed from
the top down. As soon as one of the conditions controlling the if is true, the statement
associated with that if is executed, and the rest of the ladder is bypassed. If none of the
conditions is true, then the final else statement will be executed.
Syntax:
if (condition)​
statement;​
else if (condition)​
statement;​
.​
.​
else​
statement;
Flow Chart:
if-else-if ladder statement
Example: This example describes the if-else-if ladder statement in Javascript.
// JavaScript program to illustrate nested-if statement
let i = 20;
if (i == 10)
console.log("i is 10");
else if (i == 15)
console.log("i is 15");
else if (i == 20)
console.log("i is 20");
else
console.log("i is not present");
Output
i is 20
JavaScript Strings
●​ A JavaScript String is a sequence of characters, typically used to represent text.
●​ In JavaScript, there is no character type (Similar to Python and different from C, C++
and Java), so a single character string is used when we need a character.
●​ Like Java and Python, strings in JavaScript are immutable.
Create using Literals
We can either use a single quote or a double quote to create a string. We can use either
of the two, but it is recommended to be consistent with your choice throughout your code.
// Using Single Quote
let s1 = 'abcd';
console.log(s1);
// Using Double Quote
let s2 = "abcd";
console.log(s2);
Output
abcd
abcd
Create using Constructor
The new String() constructor creates a string object instead of a primitive string. It is
generally not recommended because it can cause unexpected behavior in comparisons
let s = new String('abcd');
console.log(s);
Output
[String: 'abcd']
Template Literals (String Interpolation)
You can create strings using Template Literals. Template literals allow you to embed
expressions within backticks (`) for dynamic string creation, making it more readable and
versatile.
let s1 = 'gfg';
let s2 = `You are learning from ${s1}`;
console.log(s2);
Output
You are learning from gfg
Empty String
You can create an empty string by assigning either single or double quotes with no
characters in between.
let s1 = '';
let s2 = "";
console.log(s1);
console.log(s2);
Output
Since the strings are empty, console.log will print two blank lines.
Multiline Strings
You can create a multiline string using backticks (“) with template literals. The
backticks allows you to span the string across multiple lines, preserving the line breaks within
the string.
let s = `
This is a
multiline
string`;
console.log(s);

Output
This is a
multiline
string

Basic Operations on JavaScript Strings


1. Finding the length of a String
You can find the length of a string using the length property.
let s = 'JavaScript';
let len = s.length;
console.log("String Length: " + len);
Output
String Length: 10
2. String Concatenation
You can combine two or more strings using + Operator.
let s1 = 'Java';
let s2 = 'Script';
let res = s1 + s2;
console.log("Concatenated String: " + res);
Output
Concatenated String: JavaScript
3. Escape Characters
We can use escape characters in string to add single quotes, dual quotes, and backslash.
\' - Inserts a single quote
\" - Inserts a double quote
\\ - Inserts a backslash
const s1 = "\'GfG\' is a learning portal";
const s2 = "\"GfG\" is a learning portal";
const s3 = "\\GfG\\ is a learning portal";
console.log(s1);
console.log(s2);
console.log(s3);
Output
'GfG' is a learning portal
"GfG" is a learning portal
\GfG\ is a learning portal
4. Breaking Long Strings
Using a backslash (\) to break a long string is not recommended, as it is not supported
in strict mode. Instead, use template literals or string concatenation.

const s = "'GeeksforGeeks' is \
a learning portal";
console.log(s);
Output
'GeeksforGeeks' is a learning portal
Note: This method might not be supported on all browsers. A better way to break a string is
by using the string addition.
const s = "'GeeksforGeeks' is a"
+ " learning portal";
console.log(s);
Output
'GeeksforGeeks' is a learning portal
5. Find Substring of a String
We can extract a portion of a string using the substring() method.
let s1 = 'JavaScript Tutorial';
let s2 = s1.substring(0, 10);
console.log(s2);
Output
JavaScript
6. Convert String to Uppercase and Lowercase: Convert a string to uppercase and
lowercase using toUpperCase() and toLowerCase() methods.
let s = 'JavaScript';
let uCase = s.toUpperCase();
let lCase = s.toLowerCase();
console.log(uCase);
console.log(lCase);
Output
JAVASCRIPT
javascript
7. String Search in JavaScript
Find the first index of a substring within a string using indexOf() method.
let s1 = 'def abc abc';
let i = s1.indexOf('abc');
console.log(i);
Output
4
8. String Replace in JavaScript
Replace occurrences of a substring using the replace() method. By default, replace()
only replaces the first occurrence. To replace all occurrences, use a regular expression with
the g flag.
let s1 = 'Learn HTML at GfG and HTML is useful';
let s2 = s1.replace(/HTML/g, 'JavaScript');
console.log(s2);
Output
Learn JavaScript at GfG and JavaScript is useful
9. Trimming Whitespace from String
Remove leading and trailing whitespaces using trim() method.
let s1 = ' Learn JavaScript ';
let s2 = s1.trim();
console.log(s2);
Output
Learn JavaScript
10. Access Characters from String
Access individual characters in a string using bracket notation and charAt() method.
let s1 = 'Learn JavaScript';
let s2 = s1[6];
console.log(s2);
s2 = s1.charAt(6);
console.log(s2);
Output
J
J
11. String Comparison in JavaScript
There are some inbuilt methods that can be used to compare strings such as the
equality operator and another like localeCompare() method.
let s1 = "Ajay"
let s2 = new String("Ajay");
console.log(s1 == s2); // true (type coercion)
console.log(s1 === s2); // false (strict comparison)
console.log(s1.localeCompare(s2)); // 0 (means they are equal lexicographically)

Output
true
false
0
Note: The equality operator (==) may return true when comparing a string object with a
primitive string due to type coercion. However, === (strict equality) returns false because
objects and primitives are different types. The localeCompare() method compares strings
lexicographically.
12. Passing JavaScript String as Objects
We can create a JavaScript string using the new keyword.
const str = new String("GeeksforGeeks");
console.log(str);
Output
[String: 'GeeksforGeeks']
Are the strings created by the new keyword is same as normal strings?
No, the string created by the new keyword is an object and is not the same as normal strings.
const str1 = new String("GeeksforGeeks");
const str2 = "GeeksforGeeks";
console.log(str1 == str2);
console.log(str1 === str2);
Output
true
false

You might also like