0% found this document useful (0 votes)
6 views

Unit 3 Javascript

JavaScript is a high-level, interpreted programming language primarily used for creating interactive web pages, with features like dynamic typing and asynchronous programming. It supports various applications, including web and mobile app development, and uses variables, functions, and objects for coding. The document also covers key concepts such as variable scope, hoisting, and different types of dialog boxes.

Uploaded by

roshan46g
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Unit 3 Javascript

JavaScript is a high-level, interpreted programming language primarily used for creating interactive web pages, with features like dynamic typing and asynchronous programming. It supports various applications, including web and mobile app development, and uses variables, functions, and objects for coding. The document also covers key concepts such as variable scope, hoisting, and different types of dialog boxes.

Uploaded by

roshan46g
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

UNIT-3

JAVASCRIPT

JAVASCRIPT: INTRODUCTION
JavaScript (JS) is a high-level, interpreted programming language used primarily to make web pages
interactive. It is a client-side scripting language but can also be used on the server-side with platforms like
Node.js.
Key Features of JavaScript:
1. Lightweight & Interpreted – No need for compilation; runs directly in the browser.
2. Object-Oriented – Supports objects and prototypal inheritance.
3. Event-Driven – Handles user actions like clicks, keypresses, and form submissions.
4. Cross-Platform – Runs on any browser or device with JavaScript support.
5. Dynamic Typing – Variables can hold different types of values.
6. Asynchronous Programming – Uses callbacks, promises, and async/await for non-blocking execution.
7. Manipulates HTML & CSS – Modifies webpage content dynamically using the DOM.

Where is JavaScript Used?

• Web Development – Enhances interactivity and UI responsiveness.


• Game Development – Used for browser-based games .
• Server-Side Development – With Node.js for backend programming.
• Mobile App Development – Using frameworks like React Native.
Machine Learning & AI – TensorFlow.js enables ML in the browser.

Why is it called JavaScript?

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.
HELLO WORLD PROGRAM OF JAVASCRIPT
document.write() method is used to print output directly onto the webpage.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Hello World</title>
</head>
<body>

<script>
// Writing "Hello, World!" on the webpage
document.write("Hello, World!");
</script>

</body>
</html>
document.write() vs console.log()

document.write() is used when you want to display text on a webpage.


console.log() is used for debugging purposes while developing JavaScript programs.

DIFFERENCE BETWEEN CLIENT-SIDE AND SERVER-SIDE SCRIPTING

JAVASCRIPT VARIABLES AND CONSTANTS


A variable is like a container that holds data that can be reused or updated later in the program. In JavaScript,
variables are declared using the keywords var, let, or const.
1. var Keyword
The var keyword is used to declare a variable. It has a function-scoped or globally-scoped behaviour.
var n = 5;
console.log(n);

var n = 20; // reassigning is allowed


console.log(n);
2. let Keyword
The let keyword is introduced in ES6, has block scope and cannot be re-declared in the same scope.
let n= 10;
n = 20; // Value can be updated
// let n = 15; //can not redeclare
console.log(n)
3. const Keyword
The const keyword declares variables that cannot be reassigned. It’s block-scoped as well.
const n = 100;
// n = 200; This will throw an error
console.log(n)

DATA TYPES
JavaScript supports various datatypes, which can be broadly categorized into primitive and non-primitive
types.
Primitive Datatypes
Primitive datatypes represent single values and are immutable.
1. Number: Represents numeric values (integers and decimals).
let n = 42;
let pi = 3.14;
2. String: Represents text enclosed in single or double quotes.
let s = "Hello, World!";
3. Boolean: Represents a logical value (true or false).
let bool= true;
4. Undefined: A variable that has been declared but not assigned a value.
let notAssigned;
console.log(notAssigned);
5. Null: Represents an intentional absence of any value.
let empty = null;
6. Symbol: Represents unique and immutable values, often used as object keys.
let sym = Symbol('unique');
7.BigInt: Represents integers larger than Number.MAX_SAFE_INTEGER.
let bigNumber = 123456789012345678901234567890n;

Non-Primitive Datatypes
Non-primitive types are objects and can store collections of data or more complex entities.
1. Object: Represents key-value pairs.

let obj = {
name: "Amit",
age: 25
};
2. Array: Represents an ordered list of values.
let a = ["red", "green", "blue"];
3. Function: Represents reusable blocks of code.
function fun() {
console.log("Hello");
}

STATEMENTS IN JAVASCRIPT
In JavaScript, statements are instructions that are executed by the browser or Node.js. A statement can be a
simple or complex operation that performs an action, such as assigning a value to a variable, calling a function,
or controlling program flow with conditional statements.
Declaration Statements
Declaration statements are variables, functions, or classes that are introduced into a program. These statements
begin with a keyword followed by its identifier or name.
Example
var x = 5;
var y = 6;
var X = 4;
var z = x + y;
Expression Statements
Expression statements, such as function calls or assignments, evaluate an expression and generate a value in
JavaScript. They can be assigned to a variable or used as part of a larger expression and are then discarded.
var x = 5;
x = 6;
console.log(x);
Conditional Statements
Conditional statements, such as if statements or switch statements, control program flow based on a condition:
Example
// If statement
var x = 10;
if (x > 5) {
console.log('x is greater than 5');
}
Loop Statements
Loop statements, such as while loops or for loops, repeat a block of code while a condition is true:
/ While loop
var x = 4;
while (x < 5) {
document.write(x);
x++;
}

// For loop
for (let i = 0; i < 5; i++) {
document.write(i);
}
Jump Statements
Jump statements, such as break or return statements, transfer control to another part of the program.

COMMENTS
JavaScript comments can be used to explain JavaScript code, and to make it more readable.
JavaScript comments can also be used to prevent execution, when testing alternative code.
Single Line Comments
Single line comments start with //.
Any text between // and the end of the line will be ignored by JavaScript (will not be executed).
Multi-line Comments
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored by JavaScript.

FUNCTIONS
A function in JavaScript is a block of reusable code that performs a specific task. It helps in modular
programming, making the code more organized and manageable.
1. Function Declaration (Named Function)
A function can be declared using the function keyword, followed by the function name, parameters (optional),
and a body enclosed in {}.
Syntax:
function functionName(parameters) {
// Function body
return value; // Optional
}
Example
function greet(name) {
return "Hello, " + name + "!";
}

document.write(greet("John"));
Output
Hello, John!

2. Function Expression (Anonymous Function)


A function expression is a function stored in a variable. It can be anonymous (without a name).
Example
var sum = function(a, b) {
return a + b;
};

document.write("Sum: " + sum(5, 10));


Output:
Sum: 15
3. Function with Default Parameters
JavaScript allows setting default parameter values.
Example
function greetUser(name = "Guest") {
return "Welcome, " + name + "!";
}

document.write(greetUser());
document.write("<br>");
document.write(greetUser("Alice"));
Output
Welcome, Guest!
Welcome, Alice!

VARIABLE SCOPE
In JavaScript, the concept of scope refers to the visibility and accessibility of variables in different parts of
your code. There are two primary types of scope: global scope and local scope.
Global Scope
A variable declared outside of any function or block has global scope, meaning it can be accessed from
anywhere in the code. This includes inside functions, loops, and conditional statements.
Example:
var globalVar = "I am a global variable";

function displayGlobalVar() {
document.write(globalVar); // Accessing global variable
}
displayGlobalVar(); // Output: I am a global variable
In this example, globalVar is accessible inside the displayGlobalVar function because it is declared in the
global scope.
Local Scope
A variable declared within a function is considered to have local scope. It can only be accessed from within
that function. Local variables are not visible outside their defining function.
Example:
function displayLocalVar() {
var localVar = "I am a local variable";
document.write(localVar); // Accessing local variable
}

displayLocalVar(); // Output: I am a local variable


// document.write(localVar); // This would cause an error since localVar is not accessible here.
In this case, localVar is only accessible within the displayLocalVar function.
Variable Shadowing
If a local variable has the same name as a global variable, the local variable will "shadow" the global one
within its scope.
Example:
var scope = "I am global";

function checkScope() {
var scope = "I am local";
document.write(scope); // Output: I am local
}

checkScope();
document.write(scope); // Output: I am global
Here, the scope variable inside checkScope shadows the global scope variable.

HOISTING
Variables declared with var are hoisted to the top of their function or global context. If you try to access a
variable before its declaration, it will return undefined.
Example:
javascript
document.write(myVar); // Output: undefined
var myVar = "I am hoisted";
document.write(myVar); // Output: I am hoisted
In this example, myVar is hoisted but not initialized until after the first document.write() call.
Function Hoisting
Function declarations are also hoisted. You can call a function before it is defined in your code.Example:
javascript
greet(); // Output: Hello!
function greet() {
document.write("Hello!");
}
In this case, the greet() function can be called before its declaration due to hoisting.
STRICT MODE IN JAVASCRIPT
Strict mode is a way to opt into a restricted variant of JavaScript, which helps catch common coding errors
and "unsafe" actions such as defining global variables unintentionally. It can be enabled by adding "use
strict"; at the beginning of a script or function.
Benefits of Strict Mode
1. Prevents Accidental Globals: Variables must be declared with var, let, or const.
2. Eliminates this coercion: In strict mode, if you use this in a function without an explicit context, it
remains undefined.
3. Disallows Duplicate Parameter Names: Functions cannot have duplicate parameter names.
Example of Strict Mode:
javascript
"use strict";

function myFunction() {
undeclaredVar = "This will cause an error"; // ReferenceError: undeclaredVar is not defined
}

myFunction();
In this example, attempting to assign a value to undeclaredVar without declaring it first results in an error due
to strict mode.

JAVASCRIPT OBJECTS
An object in JavaScript is a data structure used to store related data collections. It stores data as key-value
pairs, where each key is a unique identifier for the associated value. Objects are dynamic, which means the
properties can be added, modified, or deleted at runtime.
There are two primary ways to create an object in JavaScript: Object Literal and Object Constructor.
1. Creation Using Object Literal
The object literal syntax allows you to define and initialize an object with curly braces {}, setting properties
as key-value pairs.
let obj = {
name: "Sheetal",
age: 23,
job: "Developer"
};
console.log(obj);
Output
{ name: 'Sheetal', age: 23, job: 'Developer' }
2. Creation Using new Object() Constructor
let obj = new Object();
obj.name= "Sourav",
obj.age= 23,
obj.job= "Developer"

console.log(obj);

Output
{ name: 'Sourav', age: 23, job: 'Developer' }
Basic Operations on JavaScript Objects
1. Accessing Object Properties
You can access an object’s properties using either dot notation or bracket notation
let obj = { name: "Sourav", age: 23 };

// Using Dot Notation


console.log(obj.name);
// Using Bracket Notation
console.log(obj["age"]);

Output
Sourav
23
2. Modifying Object Properties
Properties in an object can be modified by reassigning their values.
let obj = { name: "Sourav", age: 22 };
console.log(obj);

obj.age = 23;
console.log(obj);

Output
{ name: 'Sourav', age: 22 }
{ name: 'Sourav', age: 23 }
3. Adding Properties to an Object
You can dynamically add new properties to an object using dot or bracket notation.
let obj = { model: "Tesla" };
obj.color = "Red";

console.log(obj);

Output
{ model: 'Tesla', color: 'Red' }
4. Removing Properties from an Object
The delete operator removes properties from an object.
let obj = { model: "Tesla", color: "Red" };
delete obj.color;

console.log(obj);

Output
{ model: 'Tesla' }
5. Checking if a Property Exists
You can check if an object has a property using the in operator or hasOwnProperty() method.
let obj = { model: "Tesla" };
console.log("color" in obj);
console.log(obj.hasOwnProperty("model"));

Output
false
true

VOID KEYWORD IN JAVASCRIPT


In JavaScript, the void keyword is used to evaluate an expression and return undefined. It prevents a function
or expression from returning any other value.
Syntax:
void(expression)
The expression is evaluated but its result is discarded, and undefined is returned.
• The void keyword is often used in href attributes to prevent navigation when clicking a link.
• <a href="javascript:void(0);">Click me</a>

DIALOG BOXES IN JAVASCRIPT


Dialogue boxes are a kind of popup notification, this kind of informative functionality is used to show success,
failure, or any particular/important notification to the user.
JavaScript uses 3 kinds of dialog boxes:
• Alert
• Prompt
• Confirm
These dialog boxes can be of very much help in making our website look more attractive.
Alert Box: An alert box is used on the website to show a warning message to the user that they have entered
the wrong value other than what is required to fill in that position. Nonetheless, an alert box can still be used
for friendlier messages. The alert box gives only one button “OK” to select and proceed.

<script>
alert("Hello! This is an alert box.");

</script>

Confirm box: A confirm box is often used if you want the user to verify or accept something. When a confirm
box pops up, the user will have to click either “OK” or “Cancel” to proceed. If the user clicks on the OK
button, the window method confirm() will return true. If the user clicks on the Cancel button, then confirm()
returns false and will show null.

<script>
var result = confirm("Are you sure you want to proceed?");
if (result) {
alert("You clicked OK!");
} else {
alert("You clicked Cancel!");
}
</script>
Prompt Box: A prompt box is often used if you want the user to input a value before entering a page. When
a prompt box pops up, the user will have to click either “OK” or “Cancel” to proceed after entering an input
value. If the user clicks the OK button, the window method prompt() will return the entered value from the
text box. If the user clicks the Cancel button, the window method prompt() returns null.
<script>

var name = prompt("What is your name?");


alert("Hello, " + name + "!");
</script>
JAVASCRIPT CODE TO IMPLEMENT VOID KEYWORD
<script>
function f()
{
return void 0;
}
document.write(f());
</script>

JAVASCRIPT CODE TO CHANGE BACKGROUND COLOR USING VOID


<html>
<head>
</head>
<body><a href="javascript:void(document.body.style.backgroundColor='lightblue')";>Click to change the
bgcolor</a>
</body>
</html>
JavaScript Operators

JavaScript operators are symbols or keywords used to perform operations on values and variables. They are
the building blocks of JavaScript expressions and can manipulate data in various ways.
1. JavaScript Arithmetic Operators
Arithmetic Operators perform mathematical calculations like addition, subtraction, multiplication, etc.
<script>
const x = 4 + 7;
document.write("x"+" "+x+"<br>");
const y = 6 * 7;
document.write("y" + " "+y);
</script>
2. JavaScript Assignment Operators
Assignment operators are used to assign values to variables. They can also perform operations like addition
or multiplication before assigning the value.
let n =8;
n+=9;
document.write(n+"<br>");
let r=8
r*=2;
document.write(r);
3. JavaScript Comparison Operators
Comparison operators compare two values and return a boolean (true or false). They are useful for making
decisions in conditional statements.
document.write(7==9);
document.write(9!=9);
u=parseInt(prompt("enter"));

v=parseInt(prompt("enter"));
document.write(v>u);
4. JavaScript Logical Operators
Comparison operators are mainly used to perform the logical operations that determine the equality or
difference between the values.
const c=true;
const d=false;
document.write(c && d);
document.write(c || d);
document.write(!c);
5.JavaScript Bitwise Operators
Bitwise operators perform operations on binary representations of numbers.
const res = 4 & 2; // Bitwise AND
document.write(res+"<br>");
const re = 4 | 2;
document.write(re);

CONDITIONAL STATEMENTS IN JAVASCRIPT


1. if Statement
Usage: Executes a block of code if a specified condition is true.
Syntax
if (condition) {
// code to be executed
}
Example
let age = 18;
if (age >= 18) {
console.log("You are an adult.");
}
2. if...else Statement
Usage: Executes one block if the condition is true, and another block if it’s false.
Syntax:
if (condition) {
// code if true
} else {
// code if false
}
Example
let age=parseInt(prompt("Enter your age"));
if(age>=18)
{
document.write("you are an adult");
}
else
{
document.write("you are not an adult");
}

3. if...else if...else Statement


Usage: Tests multiple conditions sequentially; executes the first one that is true.
Syntax:
if (condition1) {
// code if condition1 is true
} else if (condition2) {
// code if condition2 is true
} else {
// code if none are true
}
Example
let marks=parseInt(prompt("enter marks"));
if(marks>75)
{
document.write("grade A");
}
else if(marks>60)
{
document.write("grade B");
}
else
{
document.write("Grade C");
}
4. switch Statement
Usage: Evaluates an expression and matches it against cases to execute specific blocks of code.
Syntax:
switch (expression) {
case value1:
// code for value1
break;
case value2:
// code for value2
break;
default:
// code if no match
}
Example
let day=prompt("Enter day");
switch(day.toLowerCase())
{
case "monday":
document.write("Start of the week");
break;
case "friday":
document.write("Weekend");
break;
default:
document.write("Any other day");
break;
}

LOOPS IN JAVASCRIPT
Loops in JavaScript are used to repeatedly execute a block of code as long as a specified condition is true.
BENEFITS OF USING LOOPS
• Code Reusability: Loops reduce code repetition by executing the same block of code multiple times.
• Automation: They automate repetitive tasks, like iterating over arrays or objects.
• Efficiency: Loops save time and effort when performing operations on large datasets.
• Dynamic Control: Loops adapt to changing conditions during runtime, making programs more flexible.
TYPES OF LOOPS IN JAVASCRIPT
1.for loop
2.while loop
3.do-while loop
4.for in loop
5.for of loop

1. while Loop
The while loop executes a block of code as long as the specified condition is true.
Syntax
while (condition) {
// Code to be executed
}
Example
let i=1;
while(i<=10)
{
document.write(i+"<br>");
i++;
}
2. for Loop
The for loop repeats a block of code a specific number of times.
Syntax:
for (initialization; condition; increment) {
// Code to be executed
}
Example
for(i=0;i<11;i++)
{
document.write(i+"<br>");
}

3. do...while Loop
The do...while loop executes the block of code at least once before checking the condition.
Syntax:
do {
// Code to be executed
} while (condition);
Example
let r=5;
do
{
document.write(r+ "<br>");
r--;
}
while(r<4)
4. for...in Loop
The for...in loop is used to iterate over the properties of an object.
Syntax:
for (key in object) {
// Code to be executed
}
Example
let ob={name:"rahul",age:56};
for(let key in ob)
{
document.write(key+" " + ob[key] + "<br>");
}
5. for...of Loop
The for...of loop is used to iterate over iterable objects like arrays, strings, or other collections.
Syntax
for (element of iterable) {
// Code to be executed
}

Example
let colors = ["Red", "Green", "Blue"];
for (let color of colors) {
document.write(color + "<br>");
}
Difference Between break and continue in JavaScript:
1. break:
o Terminates the loop entirely and exits it.
o No further iterations are executed.
2. continue:
o Skips the current iteration and moves to the next one.
o The loop continues running.

Using break
for (let i = 1; i <= 5; i++) {
if (i === 3) {
break; // Exit the loop when i is 3
}
document.write("Number: " + i + "<br>");
}
// Output: 1, 2

Using continue
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // Skip the iteration when i is 3
}
document.write("Number: " + i + "<br>");
}
// Output: 1, 2, 4, 5

WITH KEYWORD
The with statement in JavaScript is used to simplify the code when working with an object that has multiple
properties. It allows you to access an object's properties directly without repeatedly specifying the object name.
with (object) {
// Statements
}
Example Without with Statement
var person = { name: "John", age: 25, city: "New York" };

document.write("Name: " + person.name + "<br>");


document.write("Age: " + person.age + "<br>");
document.write("City: " + person.city + "<br>");
Example Using with Statement
var person = { name: "John", age: 25, city: "New York" };

with (person) {
document.write("Name: " + name + "<br>");
document.write("Age: " + age + "<br>");
document.write("City: " + city + "<br>");
}
Explanation in Points
1. The with statement allows you to access an object’s properties directly inside the block.
2. It helps to reduce code repetition and improves readability when dealing with objects with many
properties.
3. It is mostly used when working with deeply nested objects.
4. However, the with statement is not recommended because it makes code harder to understand and can
lead to unexpected errors.
5. JavaScript strict mode ("use strict") does not allow the use of the with statement.

Advantages of with Statement


Reduces Repetitive Code: You don’t have to write the object name multiple times.
Shorter and Cleaner Code: Makes the code look simpler when accessing multiple properties of the
same object.

Disadvantages of with Statement


Confusing Scope: JavaScript may get confused if variables exist both inside and outside the with block.
Strict Mode Restriction: It is not allowed in "use strict" mode.
Slower Performance: JavaScript engines find it difficult to optimize code that uses with.
Debugging Issues: Errors become harder to track because the scope is unclear.

NATIVE OBJECTS – ARRAY, STRING, DATE, MATH, NUMBER


JavaScript provides several native objects that are built into the language and available for use. These objects
include:
1. Number
2. String
3. Boolean
4. Array
5. Object
6. Function
7. Date
8. Math
9. RegExp
10. Set
11. Map
12. Symbol
13. BigInt

1. Number Object

Represents numeric values.

Syntax:
let num = new Number(10);
console.log(num.valueOf()); // 10
2. String Object
Represents a sequence of characters.
Syntax:
let str = new String("Hello");
console.log(str.toUpperCase()); // "HELLO"
3. Array Object
Used to store multiple values in a single variable.
Syntax:
let arr = new Array(1, 2, 3);
console.log(arr.length); // 3
4. Date Object
Works with dates and times.
Syntax:
let date = new Date();
console.log(date.toDateString()); // "Mon Feb 02 2025"
5. Math Object
Provides mathematical operations.
console.log(Math.sqrt(25)); // 5

REGEXP
Regular Expressions (RegExp) in JavaScript are used for pattern matching and string manipulation (e.g.,
searching, replacing, validating inputs).
Creating a RegExp
Using Literal Syntax:
var pattern = /hello/;
Using Constructor:
var pattern = new RegExp("hello");
RegExp Methods
1. test() – Checks if a pattern exists (returns true/false)
2. exec() – Returns first match as an array, else null
3. match() – Returns all matches in an array
4. replace() – Replaces matched pattern with a new string
5. search() – Returns index of first match, else -1
6. split() – Splits a string based on the pattern
BOM IN JAVASCRIPT
The Browser Object Model (BOM) allows JavaScript to interact with the browser. It provides objects that
control browser operations, such as windows, navigation, history, and screen properties.
BOM Properties and Methods
a) window Object (Global Object)
• Represents the browser window.
• All global variables and functions belong to window.
Example
console.log(window.innerWidth); // Width of the browser window
console.log(window.innerHeight); // Height of the browser window
b) navigator Object
• Provides information about the browser.
console.log(navigator.userAgent); // Browser details
console.log(navigator.language); // Language setting
c) screen Object
• Gives information about the user's screen.
console.log(screen.width); // Screen width
console.log(screen.height); // Screen height
d) location Object
• Handles the URL of the current page.
console.log(location.href); // Current URL
location.reload(); // Reloads the page
e) history Object
• Manages browser history.
history.back(); // Go back one page
history.forward(); // Go forward one page

JAVASCRIPT WINDOW OBJECT

The window object is the global object in JavaScript that represents the browser window. It provides properties
and methods to interact with the browser, such as opening new windows, displaying alerts, and getting screen
size.
1. Properties of window Object
The window object has several properties. Here are some important ones:
(i) window.innerWidth and window.innerHeight
• These properties return the width and height of the browser window (excluding toolbars and
scrollbars).
document.write("Width: " + window.innerWidth + "<br>");
document.write("Height: " + window.innerHeight + "<br>");
(ii) window.outerWidth and window.outerHeight
• These return the width and height of the browser window, including toolbars and scrollbars.
Example:
document.write("Outer Width: " + window.outerWidth + "<br>");
document.write("Outer Height: " + window.outerHeight + "<br>");
(iii) window.location
• The location property returns the URL of the current page.
document.write("Current URL: " + window.location.href + "<br>");
(iv) window.navigator
• This property gives information about the browser and operating system.
Example:
document.write("Browser Name: " + window.navigator.appName + "<br>");
document.write("Browser Version: " + window.navigator.appVersion + "<br>");
(v) window.screen
• It provides information about the user's screen.
Example:
document.write("Screen Width: " + window.screen.width + "<br>");
document.write("Screen Height: " + window.screen.height + "<br>");
JavaScript window Object
The window object is the global object in JavaScript that represents the browser window. It provides properties
and methods to interact with the browser, such as opening new windows, displaying alerts, and getting screen
size.

1. Properties of window Object


The window object has several properties. Here are some important ones:
(i) window.innerWidth and window.innerHeight
• These properties return the width and height of the browser window (excluding toolbars and
scrollbars).
Example:
javascript
CopyEdit
document.write("Width: " + window.innerWidth + "<br>");
document.write("Height: " + window.innerHeight + "<br>");

(ii) window.outerWidth and window.outerHeight


• These return the width and height of the browser window, including toolbars and scrollbars.
Example:
javascript
CopyEdit
document.write("Outer Width: " + window.outerWidth + "<br>");
document.write("Outer Height: " + window.outerHeight + "<br>");

(iii) window.location
• The location property returns the URL of the current page.
Example:
javascript
CopyEdit
document.write("Current URL: " + window.location.href + "<br>");

(iv) window.navigator
• This property gives information about the browser and operating system.
Example:
javascript
CopyEdit
document.write("Browser Name: " + window.navigator.appName + "<br>");
document.write("Browser Version: " + window.navigator.appVersion + "<br>");

(v) window.screen
• It provides information about the user's screen.
Example:
javascript
CopyEdit
document.write("Screen Width: " + window.screen.width + "<br>");
document.write("Screen Height: " + window.screen.height + "<br>");

(vi) window.document
• It represents the document object, which allows us to manipulate the HTML content.
Example:
javascript
CopyEdit
document.write("Document Title: " + window.document.title + "<br>");

2. Methods of window Object


The window object also provides various useful methods.
(i) window.alert()
• Displays an alert box with a message.
Example:
window.alert("Hello! This is an alert message.");
(ii) window.confirm()
• Displays a confirmation box with OK and Cancel buttons.
Example:
var result = window.confirm("Do you want to proceed?");
document.write("User selected: " + (result ? "OK" : "Cancel") + "<br>");
(iii) window.prompt()
• Displays a prompt box to get user input.
Example:
var name = window.prompt("Enter your name:");
document.write("Hello, " + name + "!<br>");
(iv) window.open()
• Opens a new browser window or tab.
Example:
1. <script type="text/javascript">
2. function msg(){
3. open("http://www.javatpoint.com");
4. }
5. </script>
6. <input type="button" value="javatpoint" onclick="msg()"/>
(v) window.close()
• Closes the current window (only if it was opened by window.open()).
Example:
function closeWindow() {
window.close();
}
<button onclick="closeWindow()">Close Window</button>
(vi) window.setTimeout()
• Executes a function after a specified delay.
function showMessage() {
document.write("This message appears after 3 seconds.<br>");
}
window.setTimeout(showMessage, 3000);
(vii) window.setInterval()
• Executes a function repeatedly at specified intervals.
Example:
function showTime() {
document.write(new Date().toLocaleTimeString() + "<br>");
}
window.setInterval(showTime, 1000);
(viii) window.scrollTo()
• Scrolls to a specific position in the page.
Example:
function scrollToBottom() {
window.scrollTo(0, document.body.scrollHeight);
}
document.write('<button onclick="scrollToBottom()">Scroll to Bottom</button>');

DOM in JavaScript
The Document Object Model (DOM) represents an HTML document as a structured tree, allowing JavaScript
to manipulate elements dynamically.
DOM Properties and Methods
a) document Object
• Represents the entire HTML document.
console.log(document.title); // Displays page title
document.title = "New Title"; // Changes title
b) Selecting Elements
• getElementById() – Selects an element by ID.
• getElementsByClassName() – Selects elements by class.
• getElementsByTagName() – Selects elements by tag.
• querySelector() – Selects the first matching element.
• querySelectorAll() – Selects all matching elements.
let element = document.getElementById("demo");
console.log(element.innerHTML);
c) Modifying Elements
• Changing Content
document.getElementById("demo").innerHTML = "Hello, DOM!";
Changing Styles:
document.getElementById("demo").style.color = "red";
d) Creating and Removing Elements
let newDiv = document.createElement("div");
newDiv.innerHTML = "New Element";
document.body.appendChild(newDiv); // Adds element to body

document.body.removeChild(newDiv); // Removes element


e) Handling Events
document.getElementById("btn").addEventListener("click", function() {
alert("Button Clicked!");
});
JavaScript Events are actions or occurrences that happen in the browser. he change in the state of an object is
known as an Event. In html, there are various events which represents that some activity is performed by the
user or by the browser. When javascript code is included in HTML, js react over these events and allow the
execution. This process of reacting over the events is called Event Handling. Thus, js handles the HTML
events via Event Handlers.
For example, when a user clicks over the browser, add js code, which will execute the task to be performed
on the event.
What is Event Handling in JavaScript?
Event handling in JavaScript refers to the process of responding to user actions or system-generated events on
a webpage. An event is an action like clicking a button, pressing a key, moving the mouse, resizing the window,
etc.
Event handling involves:
1. Capturing events (detecting user actions).
2. Executing a function when the event occurs.

Uses of Events in JavaScript

Events make web pages interactive and dynamic. They are used for:

Handling User Actions: Detecting clicks, key presses, form submissions, etc.
Validating Forms: Checking user input before submission.
Dynamic UI Changes: Showing/hiding elements, updating text, animations, etc.
Game Development: Handling keyboard and mouse inputs.
Asynchronous Tasks: Handling AJAX requests, API responses, and timers.
Tracking User Activity: Logging user behavior (e.g., Google Analytics).
1. onAbort (Deprecated)
This event was used when an image or media failed to load but is no longer widely supported. Use onError
instead.
<img src="invalid.jpg" onerror="alert('Image failed to load!')">
2. onBlur
Triggered when an element loses focus.
<input type="text" onblur="alert('Input lost focus!')" placeholder="Click and then click outside">
3. onChange
Fires when the value of an input element changes and loses focus.
<select onchange="alert('Selection changed!')">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
4. onClick
Occurs when an element is clicked.
5. onDblClick
Triggered when an element is double-clicked.
<button ondblclick="alert('Button double-clicked!')">Double Click Me</button>
6. onError
Fires when an error occurs, such as a failed image load.

7. onFocus
Occurs when an element gains focus.
<input type="text" onfocus="this.style.backgroundColor='yellow'">
8. onKeyDown
Triggered when a key is pressed down.
<input type="text" onkeydown="alert('Key pressed down!')">

10. onKeyUp
Fires when a key is released.
<input type="text" onkeyup="alert('Key released!')">

11. onLoad
Occurs when a page or an image is fully loaded.
<body onload="alert('Page Loaded!')">

12. onMouseDown
Triggered when the mouse button is pressed down.
<button onmousedown="alert('Mouse button pressed!')">Press Me</button>

13. onMouseMove
Fires when the mouse moves over an element.
<div onmousemove="alert('Mouse moving!')" style="width:200px; height:100px; border:1px solid black;">
Move Mouse Here
</div>

14. onMouseOut
Occurs when the mouse moves away from an element.
<button onmouseout="alert('Mouse left the button!')">Hover and Leave</button>

15. onMouseOver
Fires when the mouse enters an element.
<button onmouseover="alert('Mouse entered the button!')">Hover Over Me</button>

16. onMouseUp
Occurs when the mouse button is released.
<button onmouseup="alert('Mouse button released!')">Click and Release</button>

17. onReset
Triggered when a form reset button is clicked.
<form onreset="alert('Form reset!')">
<input type="text">
<button type="reset">Reset</button>
</form>
18. onResize
Occurs when the browser window is resized.
<body onresize="alert('Window resized!')">

19. onSelect
Triggered when text inside an input is selected.
<input type="text" onselect="alert('Text selected!')" value="Select this text">

20. onSubmit
Fires when a form is submitted.
<form onsubmit="alert('Form submitted!'); return false;">
<input type="text">
<button type="submit">Submit</button>
</form>

21. onUnload
Occurs when the page is about to be closed or reloaded.
22.onbeforeunload
The onbeforeunload event asks the user for confirmation before leaving the page.
The browser shows its own default message (custom messages are ignored in modern browsers).
<script>
window.onbeforeunload = function() {
return "Are you sure you want to leave?";
};
</script>

Write a javascript program that adds an event listener when a button is clicked.
<button id="myBtn">Click Me</button>
<script>
document.getElementById("myBtn").addEventListener("click", function() {
alert("Button clicked!");
});
</script>

BOM VS DOM
JAVASCRIPT CODE EXAMPLES
a. Using JavaScript, design a web page to accept a number from the user and print its Factorial.
<!-- USING JAVASCRIPT TO FIND THE FACTORIAL OF ANY NUMBER-->
<html>
<head>
<title>
JAVASCRIPT</title>
</head>
<body BGCOLOR="PINK">
<script language="javascript">
var x=parseInt(prompt("Enter any number" ," " ))
var fact=1
for(i=1;i<=x;i++)
fact=fact*i
document.write("<h1>Factorial of "+x+" is:" +fact+ "<h1>")
</script>

</body>
</html>

b. Using JavaScript, a web page that prints Fibonacci series/any given series.
<!-- PRINTING FIBONACCI SERIES-->
<html>
<head>
<title>
PRINTING FIBONACCI SERIES
</title>
<script language="javascript">
var a=0,b=1,c,n,i;
n=parseInt(prompt("Enter limit for fibonacci series"));
document.write("<h2> Fibonacci series</h2>")
document.write(a+" " +b+" ")
for(i=2;i<n;i++)
{
c=a+b;
document.write(c+" ");
a=b;
b=c;
}
</script>
</head>
<body>
</body>
</html>
c. Write a JavaScript program to display all the prime numbers between 1 and 100.
<!DOCTYPE html>
<html>
<head>
<title>prime number</title>
<script>
for(var i=2;i<=100;i++)
{
var flag=0;
for(var j=2;j<=i/2;j++)
{
if(i%j==0)
{
flag=1;
break;
}
}
if(flag==0)
{
document.write(i+"<br>");
}
}
</script>
</head>
</html>

OUTPUT

d. Write a JavaScript program to accept a number from the user and display the sum of its digits.
<!--Write a JavaScript program to accept a number from the
user and display the sum of its digits-->

<!DOCTYPE html>
<html>
<head>

<title>sum of digits</title>
<script>
var n=parseInt(prompt("Enter the number"," "));
var p=0,y;
while(n>0)
{
y=n%10;
n=parseInt(n/10);
p=p+y;
}
document.write("Sum of digits is: "+p);
</script>
</head>
</html>

You might also like