0% found this document useful (0 votes)
60 views52 pages

JavaScript Basics and DOM Manipulation

Java script notes

Uploaded by

sric29356
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)
60 views52 pages

JavaScript Basics and DOM Manipulation

Java script notes

Uploaded by

sric29356
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

MODULE-IV

JAVASCRIPT BASICS AND DOM MANIPULATION

JavaScript Language Basics:


Introduction to JavaScript:
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.

A "Hello, World!" program is the simplest way to get started with any programming language. Here’s
how you
can write one using JavaScript.

Example:
<html>
<head></head>
<body>
<h1>Check the console for the message!</h1>
<script>
// This is our first JavaScript
program [Link] ("Hello,
World!");
</script>
</body>
</html>

Output:
Hello,
World!

 The<script> tag is used to include JavaScript code inside an HTML document.


 [Link]() prints messages to the browser's developer console. Open the browser
console to see the "Hello, World!" message.
Uses of JavaScript:

1. JavaScript can be used as an alternative to java applets.


2. JavaScript can get embedded in XHTML
3. Using DOM JavaScript can access and modify the properties of CSS(Cascading style
Sheets) and contents of XHTML document.
4. JavaScript can be used to detect the visitors browsers and load the page accordingly.
5. JavaScript can be used to create cookies.

Features of JavaScript:

 Client-Side Scripting:JavaScript runs on the user's browser, so has a faster response time
without needing to communicate with the server.
 Versatile: JavaScript can be used for a wide range of tasks, from simple calculations to complex
server-side applications.
 Event-Driven: JavaScript can respond to user actions (clicks, keystrokes) in real-time.

 Asynchronous: JavaScript can handle tasks like fetching data from servers without freezing the user
interface.
 Rich Ecosystem: There are numerous libraries and frameworks built on JavaScript, such as
React, Angular, and [Link], which make development faster and more efficient.

Applications of JavaScript
JavaScript is used in a wide range of applications, from enhancing websites to building complex
applications. Here are some examples:
 Web Development: JavaScript adds interactivity and dynamic behavior to static websites,
with popular frameworks like AngularJS enhancing development.

 Web Applications: JavaScript powers robust web applications, leveraging APIs, React, and
Electron to create dynamic user experiences like Google Maps.
 Server Applications: [Link] brings JavaScript to the server side, enabling powerful server
applications and full-stack development.

 Game Development: JavaScript, combined with HTML5 and libraries like Ease JS,
enables the creation of interactive games for the web.
 Smartwatches: Pebble JS allows JavaScript to run on smartwatches, supporting apps that
require internet connectivity.
Limitations of JavaScript

Despite its power, JavaScript has some limitations to consider:

 Security Risks: JavaScript can be used for attacks like Cross-Site Scripting (XSS), where
malicious scripts are rejected into a website to steal data by exploiting elements like <img>,
<object>, or <script> tags.
 Performance: JavaScript is slower than traditional languages for complex tasks, but for
simple tasks in a browser, performance is usually not a major issue.
 Complexity: To write advanced JavaScript, programmers need to understand core
programming concepts, objects, and both client- and server-side scripting, which can be
challenging.

 Weak Error Handling and Type Checking: JavaScript is weakly typed, meaning variables don’t
require

explicit types. This can lead to issues as type checking is not strictly enforced.

JavaScript Data Types:

Data Type : - A data type is a classification that specifies the type of value a variable can hold, such as
integer, floating- point number, or character. It also defines the operations that can be performed on that
data and how the data is stored in memory.

In JavaScript, each value has a data type, defining its nature (e.g., Number, String, Boolean) and
operations. Data types are categorized into Primitive (e.g., String, Number) and Non-Primitive (e.g.,
Objects, Arrays).

Primitive Data Type

1. Number

The Number data type in JavaScript includes both integers and floating-point numbers. Special values like
Infinity, - Infinity, and NaN represent infinite values and computational errors, respectively.

Example:

const a = 3;
const b = 4;
[Link] (a + b);

Output:
7
2. String

A String in JavaScript is a series of characters that are surrounded by quotes. There are three types of
quotes in JavaScript, which are.
Example:

let s1 = "Hello There";


[Link](s1);
let s2 = 'Single quotes work fine';
[Link](s2);
let s3 = `can embed ${s1}`;
[Link](s3);

Output:
Hello There
3. Boolean
The Boolean type has only two values i.e. true and false.

Example:
let b1 = true;
[Link](1);
let b2 = false; [Link](b2);

Output:
true
false
4. Null

The special null value does not belong to any of the default data types. It forms a separate type of its own
which contains only the null value.
Example:
let age = null;
[Link](age) ;

Output:
Null
5. Undefined

A variable that has been declared but not initialized with a value is automatically assigned theundefined
value. It means the variable exists, but it has no value assigned to it.
Example:

let a;
[Link](a);

Output:
undefined

6. Symbol (Introduced in ES6)

Symbols, introduced in ES6, are unique and immutable primitive values used as identifiers for object
properties. They help create unique keys in objects, preventing conflicts with other properties.
Example:
let s1 = Symbol("Geeks");
let s2 = Symbol("Geeks");

[Link](s1 == s2);

Output:
False
Non-Primitive Data Types
The data types that are derived from primitive data types are known as non-primitive data types. It is also
known as derived data types or reference data types.

1. Object
JavaScript objects are key-value pairs used to store data, created with {} or the new keyword. They are
fundamental as nearly everything in JavaScript is an object.
Example:
let gfg = {type: "Company", location: "Noida"};
[Link]([Link]);

Output:
Company

2. Arrays
An Array is a special kind of object used to store an ordered collection of values, which can be of any data type.
Example:
let a1 = [1, 2, 3, 4, 5];
[Link](a1);
let a2 = [1, "two", { name: "Object" }, [3, 4, 5]];
[Link](a2);

Output:
[ 1, 2, 3, 4, 5 ]
[ 1, 'two', { name: 'Object' }, [ 3, 4, 5 ] ]

3. Function
A function in JavaScript is a block of reusable code designed to perform a specific task when called.
Example:
// Defining a function to greet a user
function greet(name) { return "Hello, " + name + "!"; }
// Calling the
function
[Link](greet("A
jay"));
Output
Hello,
Ajay!
4. Date Object
The Date object in JavaScript is used to work with dates and times, allowing for date creation,
manipulation, and formatting.
Example:
// Creating a new Date object for the current date
and time let currentDate = new Date();
// Displaying the current date and time
[Link](currentDate);

Output:
2025-03-08T[Link].202Z

5. Regular Expression
A RegExp (Regular Expression) in JavaScript is an object used to define search patterns for matching text in
strings.
Example:
// Creating a regular expression to match the word
"hello" let pattern = /hello/;
// Testing the pattern against a string
let result = pattern. Test("Hello, world!"); // Returns true because "Hello" matches the pattern
[Link](result);

Output:
False
Variables Declaration:
Variables in JavaScript can be declared using var, let, or const. JavaScript is dynamically typed, so
variable types are determined at runtime without explicit type definitions.

 JavaScript var keyword


 JavaScript let keyword
 JavaScript const

Keyword var a=10//Old style


let b = 20; // Preferred for non-const
const c = 30; // Preferred for const (cannot be changed)
[Link](a);
[Link](b);
[Link](c);

Output:
10
20
30
Declaring Variables in JavaScript
1. JavaScript var keyword

var is a keyword in JavaScript used to declare variables and it is Function-scoped and hoisted, allowing
redeclaration but can lead to unexpected bugs.

Example:
var a = "Hello";
var b = 10;
[Link](a);
[Link](b);

Output:
Hello

10

2. JavaScript let keyword

let is a keyword in JavaScript used to declare variables and it is Block-scoped and not hoisted to the top,
suitable for mutable variables.

Example:
let a = 12
let b = "Nikitha";
[Link](a);
[Link](b);

Output:
12

Nikitha

3. JavaScript const keyword

const is a keyword in JavaScript used to declare variables and it is Block-scoped, immutable bindings that
can't be reassigned, though objects can still be mutated.

Example:

const a = 5

let b = " Nikitha ";


[Link](a);
[Link](b);
Output:
5

Nikitha

Variable Scope in JavaScript

Scope determines the accessibility of variables in your code. JavaScript supports the following types of scope

1. Global Scope

Variables declared outside any function or block are globally scoped. While var, let, and const can all have
global scope when declared outside a function, their behavior differs:

 let and const do not attach to the window object, making them safer for modern usage.
var globalVar = "I am global";
let globalLet = "I am also global";
const globalConst = "I am global too";

2. Function Scope

Variables declared inside a function are accessible only within that function. This applies to var, let, and const:
function test() {
var localVar = "I am local";
let localLet = "I am also local";
const localConst = "I am local too";
}
[Link](localVar); // Error: not defined

3. Block Scope

Variables declared with let or const inside a block (e.g., inside {}) are block-scoped, meaning they cannot
be accessed outside the block. var, however, is not block-scoped and will leak outside the block.

{
let blockVar = "I am block-scoped";
const blockConst = "I am block-scoped too";
}
[Link](blockVar); // Error: not defined
When to Use var, let, or const
 We declare variables using const if the value should not be changed

 We should use let if we want mutable value or we can not use const

 We use var only if we support old browser.

Comparison of properties of let, var, and const keywords in JavaScript:

Property Var Let Const

Scope Function scoped Block scoped Block scoped

Updation Mutable Mutable Immutable

Redeclaration Can be redeclared Cannot be redeclared Cannot be redeclared

Hoisting Hoisted at top Hoisted at top Hoisted at top

Origins Pre ES2015 ES2015(ES6) ES2015(ES6)


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.

JavaScript Operators
There are various operators supported by JavaScript.
1. JavaScript Arithmetic Operators

Arithmetic Operators perform mathematical calculations like addition, subtraction, multiplication, etc.
Example:
const sum = 5 + 3; // Addition
const diff = 10 - 2; // Subtraction
const p = 4 * 2; // Multiplication
const q = 8 / 2; // Division
[Link] (sum, diff, p, q);

Output:
8
8
8
4
2. JavaScript Assignment Operators

Assignment operators are used to assign values to variables. They can also perform operations
like addition or multiplication while assigning the value.
Example:
let n = 10;
n += 5;
n *= 2;
[Link](n);

Output: 30
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.
Example:
[Link](10 > 5);
[Link](10 === “10”);

Output:
true
false
4. JavaScript Logical Operators

Logical operators are mainly used to perform the logical operations that determine the equality or
difference between the values.

Example:
const a = true, b = false;
[Link](a && b); // Logical
AND [Link](a || b); //
Logical OR

Output:
false
true
5. JavaScript Bitwise Operators

Bitwise operators perform operations on binary representations of numbers.


Example:
const res = 5 & 1; // Bitwise AND
[Link](res);

Output:
1
6. JavaScript Ternary Operator

The ternary operator is a shorthand for conditional statements. It takes three operands.
Example:
const age = 18;
const status = age >= 18 ? "Adult" : "Minor";
[Link](status);
Output:
Adult
7. JavaScript Unary Operators

Unary operators operate on a single operand (e.g., increment, decrement).


Example:
let x = 5;
[Link](++x); // Pre-increment
[Link](x--); // Post-decrement (Output: 6, then x becomes 5)

Output:
6
6

8. JavaScript Relational Operators

JavaScript Relational operators are used to compare its operands and determine the relationship between
them. They return a Boolean value (true or false) based on the comparison result.
Example:
const obj = { length: 10 };
[Link]("length" in obj);
[Link]([] instanceof Array);

Output:
true
true
9. JavaScript String Operators

JavaScript String Operators include concatenation (+) and concatenation assignment (+=), used to join strings
or combine strings with other data types.
Example:
const s = "Hello" + " " + "World";
[Link](s);

Output
Hello World
JavaScript Expressions:
JavaScript's expression is a valid set of literals, variables, operators, and expressions that evaluate a single
value that is an expression. This single value can be a number, a string, or a logical value depending on the
expression.
JavaScript Primary Expression

Expressions Description

Async/Await Checks that we are not breaking the execution thread.


Function

Object They have properties and methods attached to them and properties are in the
initializer form of key-value pairs.

Grouping The Grouping operator consists of a pair of parentheses around an


operator expression.

async function The async function is declared using the async keyword.

Regular The search pattern can be used for text search and text to replace operations.
Expressions
function*
Expression Define a generator function inside an expression.

Function Define a function inside an expression.


Expression

class The class name is used internally, but not outside of the class.
Expression

JavaScript Grouping Operator:


The Grouping operator consists of a pair of parentheses around an expression or sub-expression to
override the normal operator precedence so that expressions with lower precedence can be evaluated
before an expression with higher priority. This operator can only contain expressions. The parameter list
is passed to a function within this operator which will treat it as an expression.
Syntax:
()
This () operator controls the precedence of evaluation in expressions

Example 1: Below is an example of the Grouping operator.


function gfg(){
// 3 * (2 + 3)
let value1 = 3 * (2 + 3);
// (3 + 2) * 3
let value2 = (3 + 2) * 3;
[Link](value1);
[Link](value2);
}
gfg();

Output:
15
15

Example 2: Function as a statement and exception. In the below code, JavaScript considers a function as
a statement if it is not preceded by any other statement. But applying a grouping operator that has the
highest precedence over any other operator considers the function as an expression and hence it gets
fully evaluated.

function(x) { return x };
// SyntaxError: Function statements
// require a function name
// function as expression
(function (x) { return x });
// This will run without any exception.
Output:
Uncaught SyntaxError: Function statements require a function name
JavaScript RegExp (Regular Expression)
A regular expression is a special sequence of characters that defines a search pattern, typically used for
pattern matching within text. It's often used for tasks such as validating email addresses, phone numbers, or
checking if a string contains
certain patterns (like dates, specific words, etc.).

In JavaScript, RegExp is an object that is used to create regular expressions, which are patterns used to
match character combinations in strings.
// The /i flag makes the pattern case-insensitive

const patt = /Nikitha/i;


const s1 = "sunny";
const s2 = "cherry";
[Link]([Link](s1));
[Link]([Link](s2));

Output
true
true
JavaScript Function Expression
A function expression is a way to define a function as part of an expression making it versatile for
assigning to variables, passing as arguments, or invoking immediately.

 They are not hoisted, meaning they are accessible only after their definition.
 Frequently used in callbacks, closures, and dynamic function creation.
 Enable encapsulation of functionality within a limited scope.

JavaScript function* expression


The function* is an inbuilt keyword in JavaScript which is used to define a generator function inside an
expression.
Syntax:
function* [name]([param1[, param2[, ..., paramN]]]) { statements}

Parameters: This function accepts the following parameter as mentioned above and described below:
 name: This parameter is the function name.
 paramN: This parameter is the name of an argument to be passed to the function.
 statements: These parameters comprise the body of the function.

Example 1: Below examples illustrate the function* expression in JavaScript:


// Illustration of function* expression
// use of function* keyword

function* func() {
yield 1;
yield 2;
yield 3;
yield " - Nikitha";
}
let obj = '';
// Function calling for (const i of func()) {
obj = obj + i;
}

// Output [Link](obj);
Output:
123 – Nikitha
JS Class Expression
JavaScript class is a type of function declared with a class keyword, that is used to implement an
object-oriented paradigm. Constructors are used to initialize the attributes of a class.
There are 2 ways to create a class in JavaScript.
 Class Declaration
 Class Expression

In this article, we will discuss class expression to declare classes in JavaScript and how to use them.
Class Expression
The class expression is another way of creating classes in JavaScript and they can be named or unnamed.
If named, the class name is used internally, but not outside of the class.
Syntax
 Using named class expression:
const variable_name = new Class_name {
// class body
}
 Using unnamed class expression:
const variable_name = class{
//class body
}
Example 1: Named class expression const Website = class Geek {
constructor(name) { [Link] = name;
}
websiteName() {
return [Link];
}
};

const x = new Website("MallaReddyInstutite");


[Link]([Link]());

Output
MallaReddyInstitute
Control Structures in JavaScript:
JavaScript control statement is used to control the execution of a program based on a specific condition.
If the condition meets then a particular block of action will be executed otherwise it will execute another
block of action that satisfies that particular condition.

Types of Control Statements in JavaScript


 Conditional Statement: These statements are used for decision-making, a decision
n is made by the conditional statement based on an expression that is passed. Either YES or NO.
 Iterative Statement: This is a statement that iterates repeatedly until a condition is met. Simply
said, if we have an expression, the statement will keep repeating itself until and unless it is
satisfied.
Using If Statement
In this approach, we are using an if statement to check a specific condition, the code block gets executed
when the given condition is satisfied.
Syntax
if ( condition_is_given_here )
{
// If the condition is met,
//the code will get executed.
}
Now let's understand this with the help of example:

const num = 5;
if (num > 0)
{
[Link]("The number is positive.");
};

Output:
The number is positive.
Using If-Else Statement
The if-else statement will perform some action for a specific condition. If the condition meets then a
particular code of action will be executed otherwise it will execute another code of action that satisfies
that particular condition.

Syntax
if (condition1) {
// Executes when condition1 is
true if (condition2) {
// Executes when condition2 is true
}
}

Now let's understand this with the help of example:

let num = -10;


if (num > 0)
[Link]("The number is positive.");
else
[Link]("The number is negative");

Output:
The number is negative
Using Switch Statement
The switch case statement in JavaScript is also used for decision-making purposes. In some cases, using
the switch case statement is seen to be more convenient than if-else statements.
Syntax
switch (expression)
{ case value1:
statement
1; break;
case value2:
statement
2; break;
case valueN:
statement
N; break;
default:
statementDefault;
}
Now let's understand this with the help of example:
let num = 5; switch (num) {
case 0:
[Link]("Number is zero."); break;
case 1:
[Link]("Number is one."); break;
case 2:
[Link]("Number is two."); break;
default:
[Link]("Number is greater than 2.");
};
Output:
Number is greater than 2.
Using the Ternary Operator (Conditional 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

Now let's understand this with the help of example

let num = 10;


let result = num >= 0 ? "Positive" : "Negative";
[Link](`The number is ${result}.`);

Output:
The number is Positive.

Using For loop


In this approach, we are using for loop in which the execution of a set of instructions repeatedly until some
condition evaluates and becomes false

Syntax
for (statement 1; statement 2; statement 3) {
// Code here . . .
}
Now let's understand this with the help of example:
for (let i = 0; i <= 10; i++)
{
if (i % 2 === 0)
{
[Link](i);
}
};

Output:
0
2
4
6
8
10
Using While loop
The while loop repeats a block of code as long as a specified condition is true.
Syntax
while (condition)
{
// code block
}
Now let's understand this with the help if example

let i = 1;
while (i <= 5)
{
[Link](i);
i++;
}
Output:
1
2
3
4
5
Using Do-While loop
The do-while loop is similar to the while loop, except that the condition is evaluated after the execution
of the loop's body. This means the code block will execute at least once, even if the condition is false.
Syntax
do {
// code block
} while
(condition);
Now let's understand this with the help of example:
let i = 1;
do
{
[Link](i);
i++;
} while (i <= 5);
Output
1
2
3
4
5
JavaScript - Conditional Statements:
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.
Types of Conditional Statements
 if statement
 if...else statement
 if...else if...else statement
 switch statement
 ternary (conditional) operator
1. if Statement

The if statement evaluates a condition inside parentheses. If the condition is true, the block of code inside the curly
braces {} runs. If it’s false, it skips that block.
Syntax
if (condition) {
// code runs if condition is true
}
Now let's understand this with the help of example:
let x = 20;
if (x % 2 === 0) {
[Link]("Even");
}
if (x % 2 !== 0) {
[Link]("Odd");
};

Output
Even
2. 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.
let age = 25;
if (age >= 18)
{
[Link]("Adult");
}
Else
{
[Link]("Not an Adult");
};

Output
Adult
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.
const x = 0;
if (x > 0)
{
[Link]("Positive.");
}
else if (x < 0)
{
[Link]("Negative.");
}
Else
{
[Link]("Zero.");
};

Output
Zero.
4. Using Switch Statement (JavaScript Switch Case)

The switch statement is a control structure in JavaScript that allows you to execute different blocks of
code based on the value of a single expression. It’s a cleaner, more readable alternative to multiple
if...else if statements when you need to compare one variable against many possible values.

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;
}
[Link](`Student Branch name is : ${Branch}`);

Output
Student Branch name is : Mechanical engineering

5. Using Ternary Operator ( ?: )


The ternary operator is a compact shorthand for an if...else statement. It is called “ternary” because it takes three
operands:
Syntax
condition ? expression If True : expression If False let age = 21;
const result =(age >= 18) ? "You are eligible to vote.": "You are not eligible to vote.";
[Link](result);

Output:
You are eligible to vote.
6. Nested if...else

A nested if...else statement is an if...else structure placed inside another if or else block. This
allows you to check multiple conditions in a hierarchical or layered way, making complex
decision trees possible.

let weather = "sunny";


let temp = 25;
if (weather === "sunny")
{
if (temp > 30)
{
[Link]("It's a hot day!");
}
else if (temp > 20)
{
[Link]("It's a warm day.");
}
Else
{
[Link]("It's a bit cool today.");
}
} else if (weather === "rainy")
{
[Link]("Don't forget your umbrella!");
}
else
{
[Link]("Check the weather forecast!");
};

Output:
It's a warm day.
Summary

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 Allows for multiple conditions to be checked in a hierarchical manner.
statement

Why Use Conditional Statements?

Here are the some reasons for using conditional statements:

 Control Program Flow: Decide which code to execute based on different situations.

 Make Decisions: React differently to user input, data values, or system states.

 Enhance Interactivity: Enable dynamic behavior in apps and websites.

 Handle Multiple Scenarios: Manage different outcomes or error handling paths.

JavaScript Loops

Loops in JavaScript are used to reduce repetitive tasks by repeatedly executing a block of code as long
as a specified condition is true. This makes code more concise and efficient. Suppose we want to print
'Hello World' five times. Instead of manually writing the print statement repeatedly, we can use a loop
to automate the task and execute it based on the given condition.
Example:

for (let i = 0; i < 5; i++)


{
[Link]("Hello World!");
}

Output:
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Let’s now discuss the different types of loops available in JavaScript
1. JavaScript for Loop

The for loop repeats a block of code a specific number of times. It contains initialization, condition, and
increment/decrement in one line.

Syntax
for (initialization; condition; increment/decrement) {
// Code to execute
}

for (let I = 1; I <= 3; i++) {


[Link](“Count:”, i);
}

Output:
Count: 1
Count: 2
Count: 3
In this example
 Initializes the counter variable (let i = 1).
 Tests the condition (i <= 3); runs while true.
 Executes the loop body and increments the counter (i++).
2. JavaScript while Loop

The while loop executes as long as the condition is true. It can be thought of as a repeating if statement.
Syntax
while (condition) {
// Code to execute
}

let i = 0;
while (i < 3)
{
[Link]("Number:", i);
i++;
}

Output:
Number: 0
Number: 1
Number: 2
In this example
 Initializes the variable (let i = 0).
 Runs the loop body while the condition (i < 3) is true.
 Increments the counter after each iteration (i++).

3. JavaScript do-while Loop

The do-while loop is similar to while loop except it executes the code block at least once before checking the
condition.
Syntax
do {
// Code to execute
} while (condition);
let i = 0;
do
{
[Link]("Iteration:", i);
i++;
} while (i < 3);

Output:
Iteration: 0
Iteration: 1
Iteration: 2
4. JavaScript for-in Loop

The for...in loop is used to iterate over the properties of an object. It only iterate over keys of an object which have
their enumerable property set to “true”.
Syntax
for (let key in object) {
// Code to execute
}
const obj = { name: "Ashish", age: 25 }; for (let key in obj) {
[Link](key, ":", obj[key]);
}

Output:
name : Ashish age : 25

5. JavaScript for-of Loop

The for...of loop is used to iterate over iterable objects like arrays, strings, or sets. It directly iterate the
value and has more concise syntax than for loop.
Syntax
for (let value of iterable) {
// Code to execute
}
let a = [1, 2, 3, 4, 5];
for (let val of a)
{
[Link](val);
}

Output:
1
2
3
4
5
Choosing the Right Loop
 Use for loop when the number of iterations is known.
 Use while loop when the condition depends on dynamic factors.
 Use do-while loop to ensure the block executes at least once.
 Use for...in loop to iterate over object properties.
 Use for...of loop for iterating through iterable objects.

Functions in JavaScript
Functions in JavaScript are reusable blocks of code designed to perform specific tasks. They allow you to
organize, reuse, and modularize code. It can take inputs, perform actions, and return outputs.
Example:
function
sum(x,y) {

return x + y;
}
[Link](sum(6, 9)); // output: 15
Function Syntax and Working
A function definition is sometimes also termed a function declaration or function statement. Below are the
rules for creating a function in JavaScript:
 Begin with the keyword function Keyword
 A user-defined function name (In the above example, the name is sum)
 A list of parameters enclosed within parentheses and separated by commas (In the above
example, parameters are x and y)
 A list of statements composing the body of the function enclosed within curly braces {} (In the
above example, the statement is "return x + y").
Return Statement

A function can return a result using the return keyword. This is optional but useful when you want to send
data back from the function.
Function Parameters
Parameters are input passed to a function. In the above example, sum(x , y) takes two parameters, x and y.
Calling Functions
After defining a function, the next step is to call them to make use of the function. We can call a function
by using the function name separated by the value of parameters enclosed between the parenthesis.
// Function Definition

function welcomeMsg(name) {
return ("Hello " + name + " welcome to MallaReddyInstitute");
}
let nameVal = "User";
// calling the function [Link](welcomeMsg(nameVal));

Output
Hello User welcome to MallaReddyInstitute
Why Functions?
 Functions can be used multiple times, reducing redundancy.
 Break down complex problems into manageable pieces.
 Manage complexity by hiding implementation details.
 Can call themselves to solve problems recursively.
Function Invocation
The function code you have written will be executed whenever it is called.
 Triggered by an event (e.g., a button click by a user).
 When explicitly called from JavaScript code.
 Automatically executed, such as inself-invoking functions.

Function Expression
It is similar to a function declaration without the function name. Function expressions can be
stored in a variable assignment.
Syntax:
let webapplication= function (paramA, paramB) {
// Set of statements
}
const mul = function (x, y) {
return x * y;
};
[Link](mul(4, 5));

Output:
20
Arrow Functions
Arrow functions are a concise syntax for writing functions, introduced in ES6, and they do not bind
their own this context.
Syntax:
let function_name = (argument1, argument2 ,..) => expression
const a = ["Hydrogen", "Helium", "Lithium", "Beryllium"];
const a2 = [Link](function (s) {
return [Link];
});
[Link]("Normal way ", a2); const a3 = [Link]((s) => [Link]);
[Link]("Using Arrow Function ", a3);

Output:
Normal way [ 8, 6, 7, 9]
Using Arrow Function [ 8, 6, 7, 9]
Immediately Invoked Function Expression (IIFE)
IIFE functions are executed immediately after their definition. They are often used to create
isolated scopes. (function () {
[Link]("This runs immediately!");
})();

Output:
This runs immediately!
Callback Functions
A callback function is passed as an argument to another function and is executed after the completion of that
function.

function num(n, callback) {


return callback(n);
}
const double = (n) => n * 2;
[Link](num(5, double));

Output:
10
Anonymous Functions
Anonymous functions are functions without a name. They are often used as arguments to other functions.
setTimeout(function () {
[Link]("Anonymous function executed!");
}, 1000);
Nested Functions
Functions defined within other functions are callednested functions. They have access to the variables
of their parent function.

function outerFun(a)
{
function innerFun(b)
{
return a + b;
}
return innerFun;
}
const addTen = outerFun (10);
[Link](addTen(5));

Output:
15

Key Characteristics of Functions


 Parameters vs Arguments: Parameters are placeholders for function and arguments are actual
value for those placeholders.
 Return Values: Functions can return a value using the return keyword.
 Default Parameters: Default values can be assigned to function parameters.

Advantages of Functions in JavaScript


 Reusability: Write code once and use it multiple times.
 Modularity: Break complex problems into smaller, manageable pieces.
 Improved Readability: Functions make code easier to understand.
 Maintainability: Changes can be made in one place without affecting the entire codebase.
Parameter passing

JavaScript Function Parameters:


Function parameters are variables defined in the function declaration that receive values
(arguments) when the function is called. They play a key role in making functions reusable and
dynamic.
 Values are assigned to parameters in the order they are passed.
 You can assign default values to parameters if no arguments are provided.
 Allows capturing an indefinite number of arguments into an array.
 Primitive types are passed by value, whereas objects are passed by

reference. Function greet(name) {


return `Hello, ${name}!`;
}
[Link](greet(“Meeta”));

Output:
Hello, Meeta!
 Parameter: name in the function definition.
 Argument: "Meeta" passed when calling the function.
Types of Parameters in JavaScript
1. Required Parameters
These are the basic parameters expected by the function. If not provided, they will be undefined.

function add(a, b)
{
return a + b;
}

[Link](add(5, 3));
[Link](add(5));

Output:
8
NaN
2. Default Parameters
Introduced in ES6, default parameters allow you to assign a default value to a parameter if no
argument is passed or if the argument is undefined.

function mul(a, b = 1)
{
return a * b;
}
[Link](mul(5));
[Link](mul(5, 2));

Output:
5
10
2. Rest Parameters

Rest parameters allow a function to accept an indefinite number of arguments as an array. Use
the ... syntax to capture all additional arguments.
function sum(...numbers)
{
return [Link]((total, num) => total + num, 0);
}
[Link](sum(1, 2, 3, 4));

Output:
10
3. Destructured Parameters

You can destructure arrays or objects passed as arguments into individual


variables.
function displayUser({ name, age })
{
return `${name} is ${age} years old.`;
}
const user = { name: "Meeta", age: 25 };
[Link](displayUser(user));

Output:

Meeta is 25 years old.


6. Passing Functions as Parameters (Higher-Order Functions)
Functions in JavaScript can accept other functions as parameters, making it easy to create reusable
code.
Function executeTask(task, callback)
{ [Link](`Task: ${task}`);
callback();
}
executeTask(“Clean the room”, () =>
{

[Link](“Task Completed!”);
});

Output:
Task: Clean the room Task Completed!

DOCUMENT OBJECT MODEL:

Dom Hierarchy:
The DOM hierarchy in JavaScript refers to the tree-like structure of HTML elements in a web
page, as represented by the Document Object Model (DOM). This hierarchy allows JavaScript to
interact with and manipulate HTML
content dynamically.

Basic DOM Hierarchy


The hierarchy starts at the top-most object and flows downward like this:

php-template
CopyEdit Window
└──Document
└──<html> ([Link])
├──<head> ([Link])
│ └──<title>, <meta>, <link>, etc.
└──<body> ([Link])
├──<div>, <p>, <h1>, etc.
│ ├──<span>, <a>, <img>, etc.
│ └──text nodes
Key Objects

Accessing Elements in the DOM

JavaScript provides several ways to navigate the DOM tree:

By ID
JavaScript CopyEdit
let title = [Link]('page-title');

By Class Name
javascript CopyEdit
let items = [Link]('item');
By Tag Name
javascript CopyEdit
let paragraphs = [Link]('p');
Using CSS Selectors
javascript CopyEdit
let firstItem = [Link]('.item'); // first match
let allItems = [Link]('.item'); // all matches
DOM Tree Navigation
You can move around the hierarchy using properties:

 [Link]

 [Link]

 [Link]

 [Link]

 [Link]

 [Link]

 [Link]
Example:
javascript CopyEdit
let body = [Link]; [Link]([Link]); // <html>
[Link]([Link]); // HTMLCollection of body’s children

Summary

 The DOM is a hierarchical, tree-like structure.

 The root is the window, followed by document, and then the HTML elements.

 JavaScript can navigate and manipulate the DOM to change content, styles, structure, etc.

Element Selection Methods:

Selecting DOM (Document Object Model) elements is a fundamental aspect of web development with
JavaScript. It allows developers to interact with and manipulate elements on a webpage dynamically.
Proper selection of elements is crucial for tasks such as updating content, adding event listeners, or
modifying styles.

Below are the approaches to select DOM elements in JavaScript:


Table of Content

 Using getElementById
 Using getElementsByClassName
 Using getElementsByTagName
 Using querySelector
 Using querySelectorAll

Using getElementById

This method selects a single element by its unique ID attribute.


Syntax: [Link]('id')
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>getElementById Example</title>
</head>
<body>
<h1 id="gfg">MallaReddyInstitute</h1>
<script>
// styling the h1 tag
const element = [Link]('gfg'); [Link] = "green"; [Link] =
"center"; [Link] = "30px"; [Link] = "30px";
</script>
</body>
</html>

Output:
MallaReddyInstitute
Using getElementsByClassName
This method selects elements based on their class attribute. It returns a collection of elements with the
specified class name.

Syntax: [Link]('class')

Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>getElementsByClassName Example</title>
</head>
<body>
<h1 class="selector"> MallaReddyInstitute </h1>
<h2 class="selector">DOM selector in JavaScript</h2>
<script>
const elements = [Link]('selector'); elements[0].[Link] = "green";
elements[1].[Link] = "red"; elements[0].[Link] = "center"; elements[1].[Link] = "center";
elements[0].[Link] = "60px";
</script>
</body>
</html>

Output:
MallaReddyInstitute
Dom Selector in JavaScript
Using getElementsByTagName
This method selects elements based on their tag name. It returns a collection of elements with the specified tag
name.
Syntax: [Link]('tag')

Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>getElementsByTagName Example</title>
</head>
<body>
<p>Thanks for visiting GFG</p>
<p>This is showing how to select DOM element using tag name</p>
<script>
const paragraphs = [Link]('p'); paragraphs[0].[Link] = "green";
paragraphs[1].[Link] = "blue"; paragraphs[0].[Link] = "25px"; paragraphs[0].[Link] =
"center"; paragraphs[1].[Link] = "center"; paragraphs[0].[Link] = "60px";
</script>
</body>
</html>

Output:
Thanks for visiting GFG
This is showing how to select DOM element using tag name
Using querySelector
This method selects the first element that matches a specified CSS selector. It returns only one element.

Syntax: [Link]('selector')

Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>querySelector Example</title>
</head>
<body>
<div class="gfg"> MallareddyInstitute</div>
<script>
const element = [Link]('.gfg'); [Link] = "green"; [Link] =
"center"; [Link] = "30px"; [Link] = "30px";
</script>
</body>
</html>

Output:
MallaReddyInstitute

Using querySelectorAll
Similar to querySelector, but it returns a NodeList containing all elements that match the specified CSS selector.

Syntax: [Link]('selector')
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>querySelectorAll Example</title>
</head>
<body>
<h1 class="selector"> MallareddyInstitute </h1>
<p class="selector">
This is showing how to select DOM element using tag name
</p>
<script>
const elements = [Link]('.selector'); elements[0].[Link] = "green";
elements[1].[Link] = "red"; elements[0].[Link] = "center"; elements[1].[Link] = "center";
elements[0].[Link] = "60px";
</script>
</body>
</html>

Output:
MallareddyInstitute
This is showing how to select DOM element using tag name

Node Properties:

In DOM (Document Object Model) manipulation, a node represents any object in the DOM tree —
elements, attributes, text, comments, etc.

Here are the main node properties used in DOM manipulation with JavaScript:

1. nodeType
Returns the type of the node (as a number). Common values:
1: Element
3: Text
8: Comment Example:
[Link]([Link]); // e.g., 1

2. nodeName
returns the name of the node (tag name for elements, #text for text nodes). Example:
[Link]([Link]); // e.g., "DIV", "#text"
3. nodeValue
Returns or sets the value of a text or comment node. For element nodes, it returns null.
Example:
[Link]([Link]);

4. parentNode
Returns the parent node of the current node. Example:
[Link]([Link]);

5. childNodes
Returns a NodeList of all child nodes (including text nodes). Example:
[Link]([Link]);

6. firstChild / lastChild
Returns the first or last child node (could be an element, text, etc.) Example:
[Link]([Link]);

7. nextSibling / previousSibling
Returns the next or previous sibling node (includes text nodes). Example:
[Link]([Link]);

8. ownerDocument
Returns the document object associated with the node. Example:
[Link]([Link] === document); // true

9. textContent
Gets or sets the text content of a node and its descendants. Example:
[Link]([Link]);
[Link] = "New text";
Would you like the same explained with a diagram or practical example in HTML + JS?
JavaScript – Text Content Manipulate DOM Elements
The DOM stands for the Document Object Model (DOM), which allows us to interact with the
document and change its structure, style, and content. We can use the DOM to change the content and
style of an HTML element by changing its properties.

In this article, we will discuss how to manipulate the DOM elements.


How to Manipulate DOM Elements?
We can manipulate or change the DOM elements by using the following methods:
1. Change the Content of an Element

You can change the content inside an HTML element using JavaScript. The two most common
properties for this are innerHTML and textContent:
 innerHTML: Allows you to get or set the HTML content inside an element.
 textContent: Allows you to get or set the text content inside an element, ignoring any HTML tags.
<body>
<div id="example1">This is the original content using innerHTML.</div>
<div id="example2">This is the original text content using textContent.</div>
<button onclick="changeContent()">Change Content</button>
<script>
// Function to change content
function changeContent() { [Link]("example1").innerHTML = "<strong>This is
changed using innerHTML! </strong>"; [Link]("example2").textContent = "This is
changed using textContent!";
}
</script>
</body>

DOM Manipulation -
Change the Content of an Element
Manipulate the Class Attribute
You can add, remove, or toggle classes on an element using JavaScript. This is helpful for styling or applying
animations.
[Link](): Adds a class to an element.
[Link](): Removes a class from an element.
[Link](): Toggles a class (adds it if it's not present, removes it if it is).
<html>
<head>
<style>
.highlight {
color: red;
font-weight: bold;
}
.bold {
font-weight: bold;
}
</style>
</head>
<body>
<div id="example" class="bold">This is a text element with the "bold" class.</div>
<button onclick="addClass()">Add 'highlight' Class</button>
<button onclick="removeClass()">Remove 'bold' Class</button>
<button onclick="toggleClass()">Toggle 'highlight' Class</button>
<script>
function addClass() { [Link]("example").[Link]("highlight");
} function removeClass() { [Link]("example").[Link]("bold");
}
function toggleClass() { [Link]("example").[Link]("highlight");
}
</script>
</body>
</html>

Output:

DOM Manipulation - Manipulate the Class Attribute


In this example
 Adding a Class (addClass()): When you click the "Add 'highlight' Class" button, the highlight
class is added to the div element with the id="example". This changes the text color to red and
makes it bold (as defined in the CSS).
 Removing a Class (removeClass()): When you click the "Remove 'bold' Class" button,
the bold class is removed from the div, which removes the bold styling from the text.
 Toggling a Class (toggleClass()): When you click the "Toggle 'highlight' Class" button, the highlight
class is
either added or removed, depending on whether it's already present. If the class is present, it will
be removed; if not, it will be added.
2. Set CSS Styles Using JavaScript

You can directly manipulate the CSS styles of an element using the style property. This allows you to
dynamically change how elements appear on the page.

// Changing multiple CSS properties [Link]("demo").[Link] = "red";


[Link]("demo").[Link] = "20px";
// Adding more than one style
[Link]("demo").[Link] = "color: blue; font-size: 18px;";

3. Create, Add, and Remove Elements

Sometimes, you need to create new elements, add them to the DOM, or remove existing ones. You can do
this easily with the following methods
 [Link](): Creates a new element.
 appendChild(): Adds a new element to a parent element.
 removeChild(): Removes a child element from a parent.

4. Insert Elements at a Specific Position

You can insert new elements at specific positions relative to existing elements using methods like insertBefore().
// Create a new element
let newDiv = [Link]("div");
[Link] = "This is a new div";
// Find an existing element to insert before
let referenceNode = [Link]("referenceElement");
// Insert the new element before the reference element
[Link](newDiv, referenceNode);
5. Manipulate Element Attributes

You can easily get, set, or remove the attributes of an HTML element using the following methods:
 getAttribute(): Retrieves the value of an attribute.
 setAttribute(): Sets a new value for an attribute.
 removeAttribute(): Removes an attribute.

// Get the value of an attribute


let src = [Link]("image").getAttribute("src");
// Set a new value for an attribute
[Link]("image").setAttribute("src", "[Link]");
// Remove an attribute
[Link]("image").removeAttribute("src");
Attribute Modification :

Attribute modification in JavaScript refers to the process of adding, changing, or removing attributes
of HTML elements using JavaScript. Attributes are key-value pairs in HTML tags that define properties
or behavior—like id, class, src, href, disabled, etc

What Is Attribute Modification?

It means using JavaScript to:


 Add a new attribute
 Change the value of an existing attribute
 Remove an attribute
 Check if an attribute exists
 Read the value of an attribute
 Common Methods for Attribute Modification
setAttribute()

The setAttribute() method sets a new value to an


attribute. If the attribute does not exist, it is
created first.

Example:
Add a class attribute to an element:
[Link]("class",
"democlass"); Before:

The Element Object


After:

The Element Object


getAttribute()
The getAttribute() method returns the value of an element's
attribute. See Also:

Example:
Get the value of the class attribute of an element:
let text = [Link]("class");
removeAttribute()
The removeAttribute() method removes an attribute from an element.
Example:
Remove the class attribute from an <h1> element:

[Link]("H1")[0].removeAttribut
e("class"); hasAttributes()
The hasAttributes() method returns true if a node has attributes, otherwise false.
The hasAttributes() method always returns false if the node is not an element node.

Example:

Does the <body> element have attributes? let answer = [Link]();


Style Property Access :
Style property access in JavaScript refers to the ability to read and modify CSS styles of HTML
elements directly using the .style property. This allows developers to dynamically change the appearance
of elements without needing to reload or rewrite the HTML or CSS files.

What Is the .style Property?


The .style property returns a CSSStyleDeclaration object that represents the inline styles of an element.
You can use it to:
 Set new styles
 Modify existing styles
 Read inline style values

How to Use Style Property Access


Setting Styles
const heading = [Link]("myHeading"); [Link] = "blue";
[Link] = "24px"; [Link] = "yellow";

Note: CSS properties with hyphens (e.g., background-color) become camelCase in JavaScript (backgroundColor).
Reading Inline Styles
[Link]([Link]); // "blue"

This only works for styles set inline or via JavaScript. To read computed styles (from CSS files),

use:

const computedStyles = [Link](heading);

[Link]([Link]); // e.g., "rgb(0, 0, 255)"


Removing Styles
[Link] = "";
Setting a style to an empty string removes it from the inline style.
Example
Hello

World

Change

Style
What Is the .style Property?
The .style property returns a CSSStyleDeclaration object that represents the inline styles of an element.
You can use it to:
 Set new styles
 Modify existing styles
 Read inline style values
How to Use Style Property Access

Setting Styles

const heading = [Link]("myHeading");


[Link] = "blue";
[Link] ="24px"; [Link] = "yellow";

Note: CSS properties with hyphens (e.g., background-color) become camelCase in JavaScript
(backgroundColor).

Reading Inline Styles

[Link]([Link]); // "blue"

This only works for styles set inline or via JavaScript. To read computed styles (from CSS files),

use:
const computedStyles = [Link](heading);
[Link]([Link]); // e.g., "rgb(0, 0, 255)"
Removing Styles
[Link] = "";
Setting a style to an empty string removes it from the inline style.
Example
Hello World

Would you like to see how to toggle styles interactively, like switching themes or animations?

const heading = [Link]("myHeading");


[Link] = "blue";
[Link] = "24px";
[Link] = "yellow";
Note: CSS properties with hyphens (e.g., background-color) become camelCase in JavaScript (backgroundColor).
Reading Inline Styles
[Link]([Link]); // "blue"
This only works for styles set inline or via JavaScript. To read computed styles (from CSS files),
use:
const computedStyles = [Link](heading);
[Link]([Link]); // e.g., "rgb(0, 0, 255)"

Removing Styles [Link] = "";

Example
Hello World

You might also like