Javascript Class.docx
Javascript Class.docx
Introduction to JavaScript
Definition
JavaScript is a versatile programming language primarily used to add
interactivity to websites. It runs in the browser, interacts with HTML and
CSS, and is used in both frontend and backend development. It is a
lightweight, interpreted, or just-in-time compiled language that is one of
the core technologies of the World Wide Web, alongside HTML and CSS.
Examples:
// Simple greeting in JavaScript
console.log("Hello, JavaScript World!");
5. Open the terminal, navigate to the file location, and run:
node script.js
JavaScript Comment
The JavaScript comments are meaningful way to deliver message. It is used to
add information about the code, warnings or suggestions so that end user can
easily interpret the code.
Let’s see the example of single-line comment i.e. added before the statement.
<script>
// It is single line comment
document.write("hello javascript");
</script>
Example Code:
console.log("Age:", age);
Output:
Age: 25
Updated Age: 30
Exercises:
1. Declare a variable city using var and assign it the value "Delhi". Then
update it to "Mumbai".
2. Declare a variable price and assign it any number. Update it to a new
value.
Answers:
// Exercise 1
console.log("City:", city);
city = "Mumbai";
console.log("Price:", price);
price = 150;
Output:
City: Delhi
Price: 100
Example Code:
console.log("String:", data);
console.log("Number:", data);
console.log("Boolean:", data);
Output:
String: Kartik
Number: 25
Boolean: true
Exercises:
1. Create a variable status and assign it the value false. Change it to true.
2. Assign a number to a variable marks. Later, change its value to a
string.
Answers:
// Exercise 1
console.log("Status:", status);
status = true;
// Exercise 2
console.log("Marks:", marks);
marks = "Excellent";
Output:
Status: false
Marks: 85
4. let
Definition: let is used to declare variables with block scope. Unlike var, it
cannot be re-declared in the same scope.
Example Code:
console.log("Name:", name);
Output:
yaml
Name: Kartik
Exercises:
1. Declare a variable country using let and assign it the value "India". Try
updating it.
2. Use let in a block (e.g., an if statement) and try accessing it outside
the block.
Answers:
javascript
// Exercise 1
console.log("Country:", country);
country = "USA";
if (true) {
Output:
yaml
Country: India
5. const
Example Code:
javascript
const pi = 3.14;
Output:
lua
Answers:
javascript
// Exercise 1
// Exercise 2
console.log("Colors:", colors);
colors.push("yellow");
Output:
less
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
= Assign 10+10 = 20
Operator Description
JavaScript If-else
The JavaScript if-else statement is used to execute the code whether
condition is true or false. There are three forms of if statement in JavaScript.
1. If Statement
2. If else statement
3. if else if statement
JavaScript If statement
It evaluates the content only if expression is true. The signature of JavaScript if
statement is given below.
if(expression){
//content to be evaluated
}
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
Output of the above example
a is even number
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
JavaScript Switch
switch statement evaluates the condition to match the condition with the
series of cases and if the condition is matched then it executes the statement.
If the condition is not matched with any case then the default condition will
be executed.
switch (expression) {
case value1:
break;
case value2:
break;
default:
}
Break Statement
After the execution of the code block in a program break statement helps us
so it terminates the switch statement and prevents the execution from falling
through to subsequent cases.
let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
case 4:
console.log("Thursday");
break;
default:
console.log("Invalid day");
}
Output:
switch (fruit) {
case "apple":
case "banana":
case "grapes":
break;
default:
console.log("Unknown fruit.");
Output:
Output:
🔹 Code:
for (let i = 2; i <= 10; i += 2) {
console.log(i);
📌 Output:
2
6
8
10
Final Output:
10
2️⃣ Question 2: Sum of First 5 Numbers
let sum = 0;
sum = sum + i;
console.log("Sum:", sum);
📌 Output:
Sum: 15
🔹 Code:
for (let i = 5; i >= 1; i--) {
console.log(i);
📌 Output:
5
1
🔹 Loop Execution Step-by-Step:
Iteration i ki Value Condition Output i-- (Next Value)
(i >= 1)
1st 5 ✅ (true) 5 4
2nd 4 ✅ (true) 4 3
3rd 3 ✅ (true) 3 2
4th 2 ✅ (true) 2 1
5th 1 ✅ (true) 1 0
6th 0 ❌ (false) - -
Jab i = 0 hota hai, toh condition i >= 1 false ho jati hai aur
loop ruk jata hai.
🔹 Code:
let num = 3;
📌 Output:
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
3 x 10 = 30
1st 1 ✅ True 3 x 1 = 3 3 x 1 = 3
2nd 2 ✅ True 3 x 2 = 6 3 x 2 = 6
3rd 3 ✅ True 3 x 3 = 9 3 x 3 = 9
10th 10 ✅ True 3 x 10 = 30 3 x 10 = 30
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
3 x 10 = 30
🔹 Code:
let fruits = ["Apple", "Banana", "Mango", "Grapes"];
console.log(fruits[i]);
📌 Output:
Apple
Banana
Mango
Grapes
Jab humein ek kaam baar-baar repeat karna ho jab tak koi condition true
ho, tab hum while loop ka use karte hain.
while (condition) {
// Yeh code tab tak chalega jab tak condition true hai
}
👉 condition ko har baar check kiya jaata hai.
👉 Agar condition true hai, toh loop chalega.
👉 Jaise hi condition false ho gayi, loop ruk jayega.
Output:
Number is: 1
Number is: 2
Number is: 3
Number is: 4
Number is: 5
} while (condition);
● Pehle code execute hota hai, phir condition check hoti hai.
● Agar condition true hai, toh loop phir se chalega.
● Agar condition false hai, toh ek hi baar chalega aur ruk jayega.
Print 1 se 5 .
do {
console.log("Number:", count);
count++;
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
for...in loop object properties ya array indexes ko iterate karne ke liye use
hota hai. Yeh loop keys (properties) par focus karta hai, values par nahi.
CopyEdit
javascript
CopyEdit
let student = {
name: "Kartik",
age: 25,
Place: "SIKAR"
};
Output:
name: Kartik
age: 25
place: SIKAR
👉 Yeh loop object ke har ek property (key) ko access karta hai aur uski
value print karta hai.
3️⃣ for...in Loop with Arrays
Jab for...in loop ko array ke saath use karte hain, toh yeh indexes ko
return karta hai, values ko nahi.
Output:
0: Red
1: Green
2: Blue
👉 Yeh loop sirf index return karta hai, actual value nahi.
👉 Agar sirf values chahiye toh for...of loop better hai.
console.log(color);
Output:
Red
Green
Blue
JavaScript Functions
A function is a block of code that performs a specific task. Instead of writing
the same code multiple times, we write a function once and use it whenever
needed.
function sayHello() {
console.log("Hello, students!");
A function can take inputs and use them inside the code.
function greet(name) {
function add(a, b) {
return a + b;
return x * y;
};
console.log(multiply(4, 2));
// Output: 8
Syntax
console.log(square(6)); // Output: 36
Without parameters:
const greet = () => "Hello!";
console.log(getUser());
console.log(lengths);
console.log(doubled);
// Output: [2, 4, 6, 8]
javascript
CopyEdit
console.log(uppercaseWords);
function square(num) {
function sumOfSquares(a, b) {
function getSnack(snackNumber) {
Functions are useful in organizing the different parts of a script into the
several tasks that must be completed. There are mainly two advantages of
JavaScript functions.
1. Code reusability: We can call a function several times in a script to perform
their tasks so it saves coding.
2. Less coding: It makes our program compact. We don't need to write many
lines of code each time to perform a common task.
function multiplyNumbers(a, b, c) {
return a * b * c;
console.log(square(5)); // Output: 25
console.log(square(3)); // Output: 9
console.log(square(7)); // Output: 49
return a > b ? a : b;
console.log(cube(2)); // Output: 8
console.log(cube(3)); // Output: 27
console.log(cube(4)); // Output: 64
return str.includes("JavaScript");
JavaScript Objects
An object in JavaScript is a collection of key-value pairs where keys (also called
properties) are strings, and values can be any data type (number, string,
function, array, or even another object). Objects help store structured data and
model real-world entities.
Syntax:
let objectName = {
key1: value1,
key2: value2,
key3: value3
};
let person = {
age: 25,
job: "Data Analyst",
isMarried: false
};
console.log(person);
Output:
console.log(person["age"]); // Output: 25
let car = {
brand: "Tesla",
start: function() {
console.log("The car has started.");
};
Output:
let student = {
name: "John",
marks: {
math: 90,
science: 85
};
console.log(student.marks.math);
JavaScript Array
An array in JavaScript is a special type of object used to store multiple values in
a single variable. Arrays are ordered collections where each value is identified
by an index starting from 0.
Syntax
Creating an Array
console.log(fruits);
Output:
You can access elements using their index (starting from 0):
console.log(fruits);
Output:
Definition:
The push() method adds one or more elements to the end of an
array and returns the new length.
Syntax:
Example:
fruits.push("Mango", "Orange");
Definition:
The pop() method removes the last element from an array and
returns it.
Syntax:
array.pop();
Example:
let fruits = ["Apple", "Banana", "Mango"];
Definition:
Syntax:
Example:
numbers.unshift(1);
Definition:
The shift() method removes the first element from an array and
returns it.
Syntax:
array.shift();
Example:
console.log(removed); // Output: 1
Definition:
Syntax:
array.includes(element);
Example:
Definition:
Syntax:
array.slice(startIndex, endIndex);
Example:
Definition:
Syntax:
array.splice(startIndex, deleteCount, item1, item2, ...);
Example:
You can use different Date to create date object. It provides methods to get
and set day, month, year, hour, minute and seconds.
Current Date and Time: Sun Feb 02 2025 20:49:51 GMT+0530 (India Standard Time)
JavaScript Math
The JavaScript math object provides several constants and methods to
perform mathematical operation.
Math.sqrt(n)
The JavaScript math.sqrt(n) method returns the square root of the given
number.
Output:
Math.random()
The JavaScript math.random() method returns the random number between
0 to 1.
Output:
Math.floor(n)
The JavaScript math.floor(n) method returns the lowest integer for the given
number. For example 3 for 3.7, 5 for 5.9 etc.
Output:
Floor of 4.6 is: 4
Math.ceil(n)
The JavaScript math.ceil(n) method returns the largest integer for the given
number. For example 4 for 3.7, 6 for 5.9 etc.
Output:
Math.round(n)
The JavaScript math.round(n) method returns the rounded integer nearest
for the given number. If fractional part is equal or greater than 0.5, it goes to
upper value 1 otherwise lower value 0. For example 4 for 3.7, 3 for 3.3, 6 for 5.9
etc.
Output:
Math.abs(n)
The JavaScript math.abs(n) method returns the absolute value for the given
number. For example 4 for -4, 6.6 for -6.6 etc.
Output:
The default object of browser is window means you can call all the functions of
window by specifying window or directly. For example:
window.alert("hello developers");
is same as:
alert("hello developers");
Window is the object of browser, it is not the object of javascript. The javascript
objects are string, array, date etc.
Method Description
alert() displays the alert box containing
message with ok button.
<script type="text/javascript">
function msg(){
alert("Hello Alert Box");
}
</script>
<input type="button" value="click" onclick="msg()"/>
Example of confirm() in javascript
It displays the confirm dialog box. It has message with ok and cancel buttons.
<script type="text/javascript">
function msg(){
var v= confirm("Are u sure?");
if(v==true){
alert("ok");
}
else{
alert("cancel");
}
}
</script>
<input type="button" value="delete record" onclick="msg()"/>
<script type="text/javascript">
function msg(){
var v= prompt("Who are you?");
alert("I am "+v);
}
</script>
<input type="button" value="click" onclick="msg()"/>
Example of open() in javascript
It displays the content in a new window.
<script type="text/javascript">
function msg(){
open("http://www.facebook.com");
}
</script>
<input type="button" value="facebook" onclick="msg()"/>
<script type="text/javascript">
function msg(){
setTimeout(
function(){
alert("Welcome to Javascript programing after 5 seconds")
},2000);
}
</script>
<input type="button" value="click" onclick="msg()"/>
window.navigator
Or,
navigator
<script>
document.writeln("<br/>navigator.appVersion:
"+navigator.appVersion);
document.writeln("<br/>navigator.cookieEnabled:
"+navigator.cookieEnabled);
document.writeln("<br/>navigator.language: "+navigator.language);
document.writeln("<br/>navigator.userAgent: "+navigator.userAgent);
document.writeln("<br/>navigator.platform: "+navigator.platform);
document.writeln("<br/>navigator.onLine: "+navigator.onLine);
</script>
navigator.cookieEnabled: true
navigator.language: en-US
navigator.platform: Win32
navigator.onLine: true
<script>
document.writeln("<br/>screen.width: "+screen.width);
document.writeln("<br/>screen.height: "+screen.height);
</script>
screen.width: 1366
screen.height: 768
window.document
Is same as
document
Method Description
Let's see the simple example of document object that prints name with
welcome message.
<script type="text/javascript">
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name);
}
</script>
<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
</form>
In this example, we are going to get the value of input text by user. Here, we
are using document.form1.name.value to get the value of name field.
Here, document is the root element that represents the html document.
value is the property, that returns the value of the input text.
Javascript - document.getElementById()
method
<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>
Javascript -
document.getElementsByName() method
The document.getElementsByName() method returns all the element of
specified name.
The syntax of the getElementsByName() method is given below:
document.getElementsByName("name")
<script type="text/javascript">
function totalelements()
{
var allgenders=document.getElementsByName("gender");
alert("Total Genders:"+allgenders.length);
}
</script>
<form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">
<input type="button" onclick="totalelements()" value="Total
Genders">
</form>
Javascript -
document.getElementsByTagName()
method
The document.getElementsByTagName() method returns all the element of
specified tag name.
The syntax of the getElementsByTagName() method is given below:
document.getElementsByTagName("name")
<script type="text/javascript">
function countpara(){
var totalpara=document.getElementsByTagName("p");
alert("total p tags are: "+totalpara.length);
}
</script>
<p>This is a pragraph</p>
<p>Here we are going to count total number of paragraphs by
getElementByTagName() method.</p>
<p>Let's see the simple example</p>
<button onclick="countpara()">count paragraph</button>
AD
<script type="text/javascript">
function counth2(){
var totalh2=document.getElementsByTagName("h2");
alert("total h2 tags are: "+totalh2.length);
}
function counth3(){
var totalh3=document.getElementsByTagName("h3");
alert("total h3 tags are: "+totalh3.length);
}
</script>
<h2>This is h2 tag</h2>
<h2>This is h2 tag</h2>
<h3>This is h3 tag</h3>
<h3>This is h3 tag</h3>
<h3>This is h3 tag</h3>
<button onclick="counth2()">count h2</button>
<button onclick="counth3()">count h3</button>
What is an Event ?
JavaScript's interaction with HTML is handled through events that occur when
the user or the browser manipulates a page.
When the page loads, it is called an event. When the user clicks a button,
that click too is an event. Other examples include events like pressing any
key, closing a window, resizing a window, etc.
Syntax
We have written the inline JavaScript code to handle the event. In the inline
JavaScript code, the 'this' keyword represents the <button> element, and we
change the button's text color to red.
<html>
<body>
</body>
</html>
We used the 'onclick' event handler with the <button> element, which calls
the handleClick() function when the user clicks the button.
<head>
<style>
#test {
width: 600px;
height: 100px;
background-color: red;
</style>
</head>
<body>
<script>
function handleClick(event) {
div.style.backgroundColor = "blue";
</script>
</body>
</html>
Example: Multiple Functions with Event Handlers
In the code below, we have added the 'ommouseenter' event handler
with the <div> element. We call the changeFontSize() and
changeColor() functions when a user enters the mouse cursor in the
<div> element.
This way, you can invoke the multiple functions on the particular
event.
<html>
<head>
<style>
#test {
font-size: 15px;
</style>
</head>
<body>
<h2> Hover over the below text to customize the font. </h2>
<script>
function changeFontSize(event) {
document.getElementById("test").style.fontSize = "25px";
function changeColor(event) {
document.getElementById("test").style.color = "red";
</script>
</body>
</html>
Object Description
Here is the list of different types of event objects. Each event object
contains various events, methods, and properties.
Object/Type Handles
<html>
<head>
<script>
function sayHello() {
alert("Hello World")
}
</script>
</head>
<body>
<form>
</form>
</body>
</html>
<html>
<body>
<script>
function changeColor() {
document.getElementById("text").style.color = "red";
</script>
</body>
</html>
<html>
<body>
<script>
function customizeInput() {
ele.style.backgroundColor = "yellow";
ele.style.color = "red";
</script>
</body>
When the mouse pointer enters the <div> element, it calls the
changeRed() function to change the text color to red, and when the
mouse pointer leaves the <div> element, it calls the changeBlack()
function to change the text color to black again.
<html>
<body>
<script>
function changeRed() {
document.getElementById("text").style.color = "red";
function changeBlack() {
document.getElementById("text").style.color = "black";
</script>
</body>
</html>
Mouse Description
Event
Click Event
In this example we demonstrate the click event. When the button is
clicked, it prints an appropriate message to the console message i.e.
Clicked!. This event is often used while submitting forms.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
clickButton.addEventListener('click', function(event) {
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id = "output"></p>
<script>
const doubleClickButton =
document.getElementById('doubleClickButton');
doubleClickButton.addEventListener('dblclick', function(event) {
});
</script>
</body>
</html>