Unit - III
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.
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.
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>
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 = () => {
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
Output:
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.document Refers to the Document object representing the HTML document shown in the window.
The location attribute makes reference to the Location object, which has data about the
window.location
page’s current URL.
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.
Provides the ability to store key/value pairs in a web browser. Contains data for a single
window.sessionStorage
session.
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.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
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
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
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