Professional Documents
Culture Documents
JavaScript E Notes by Er Shubham Kumar KCS052-1
JavaScript E Notes by Er Shubham Kumar KCS052-1
JavaScript E Notes by Er Shubham Kumar KCS052-1
Shubham Kumar
Client-side scripting refers to the execution of scripts or code on the user's web browser rather than on
the web server. This allows for dynamic and interactive features on a website, enhancing the user 1
experience. The three primary technologies used for client-side scripting are HTML (Hypertext Markup
Language), CSS (Cascading Style Sheets), and JavaScript.
HTML is the standard markup language for creating the structure of web pages.
It defines the elements on a web page, such as headings, paragraphs, images, links,
forms, and more.
CSS is used for styling HTML elements, controlling the layout, and enhancing the visual
presentation of web pages.
It allows developers to define styles like colors, fonts, spacing, and positioning.
3. JavaScript:
It can be embedded directly into HTML and executed by the user's browser.
JavaScript allows for tasks such as form validation, interactivity, animations, and
updating content without requiring a page reload.
Client-side scripting is essential for creating responsive and interactive web applications. It reduces the
need for constant communication with the server, providing a faster and more seamless user
experience. However, it's important to note that client-side scripting should be used carefully to ensure
security and accessibility, as the code is visible and accessible to users.
Frameworks and libraries such as React, Angular, and Vue.js have gained popularity for building
sophisticated client-side applications, providing developers with tools to manage complex UIs and
handle data efficiently.
JavaScript is a versatile and widely-used programming language primarily known for its role in web
development. It's a crucial component of modern web browsers and allows developers to create
dynamic, interactive, and user-friendly websites. Here's an introduction to JavaScript:
1. Purpose:
JavaScript was initially created to add interactivity and dynamic behavior to static HTML
pages. It allows developers to manipulate the content, structure, and style of web pages
in real-time.
Java Script E-Notes by Er. Shubham Kumar
2. Client-Side Scripting:
2
JavaScript is primarily a client-side scripting language, meaning it runs in the user's web
browser rather than on the server. This enables developers to create responsive and
interactive user interfaces.
3. Syntax:
JavaScript syntax is similar to other programming languages like Java and C, making it
relatively easy for developers to learn if they are familiar with those languages.
4. Dynamic Typing:
5. Event-Driven Programming:
One of the key features of JavaScript is its event-driven nature. It can respond to user
actions like clicks, mouse movements, and keyboard inputs, allowing for interactive and
responsive web pages.
Form validation: JavaScript can be used to validate user inputs in forms before
submitting them to the server.
DOM manipulation: It enables the modification of the Document Object Model (DOM),
allowing developers to change the content and structure of web pages dynamically.
JavaScript has a rich ecosystem of libraries and frameworks. Popular ones include
jQuery (a library for DOM manipulation and AJAX), React, Angular, and Vue.js
(frameworks for building dynamic and single-page applications).
8. Server-Side Development:
Java Script E-Notes by Er. Shubham Kumar
With the introduction of technologies like Node.js, JavaScript can also be used for
server-side development. This allows developers to use a single language (JavaScript) for 3
both client and server-side scripting.
JavaScript is a fundamental technology for web development, and its versatility has led to its adoption in
various contexts beyond the web, including server-side development, mobile app development (via
frameworks like React Native and Ionic), and even desktop application development (with frameworks
like Electron). Understanding JavaScript is essential for anyone looking to build interactive and dynamic
web applications.
JavaScript has a rich history that spans several decades, and it has played a pivotal role in the
development of interactive and dynamic content on the World Wide Web. Here's a brief overview of the
history of JavaScript:
1. Birth at Netscape:
JavaScript was created by Brendan Eich in 1995 while he was working at Netscape
Communications Corporation. Initially, it was named Mocha, but it was later renamed to
LiveScript and eventually JavaScript to capitalize on the popularity of Java.
2. Netscape Navigator:
The first version of JavaScript was introduced in Netscape Navigator 2.0, a popular web
browser of that era. It was designed to bring interactivity to static HTML pages and
provide a way for developers to manipulate the Document Object Model (DOM).
3. Standardization (ECMAScript):
During the late 1990s and early 2000s, there was intense competition between
Netscape Navigator and Microsoft's Internet Explorer. JavaScript evolved alongside
these browser wars, and Microsoft introduced its own version of JavaScript called
JScript.
With the rise of Node.js in 2009, JavaScript extended its reach beyond the browser to
server-side development. Node.js allowed developers to use JavaScript to build scalable
and efficient server-side applications.
The popularity of JavaScript soared with the emergence of powerful frameworks and
libraries like React, Angular, and Vue.js, which facilitated the development of complex
single-page applications.
Today, JavaScript is an integral part of web development, with a vast ecosystem of tools, libraries, and
frameworks. It has expanded beyond the web browser, being used for server-side development, mobile
app development, and even desktop applications. The language continues to evolve, with ongoing
efforts to enhance its capabilities and maintain its relevance in the ever-changing landscape of
technology.
JavaScript is a dynamically-typed language, meaning that variables are not explicitly declared with a
specific data type. Instead, the type of a variable is determined at runtime based on the type of value it
holds. Here are the basic data types in JavaScript:
Undefined: Represents a variable that has been declared but not assigned any value.
Boolean: Represents a logical entity and can have two values: true or false.
Symbol: Introduced in ECMAScript 6 (ES6), symbols are unique and immutable values,
often used as property keys in objects to avoid name clashes.
3. Object:
Objects in JavaScript are complex data types that allow you to store collections of key-
value pairs. Objects can represent a wide range of entities and can contain various data
types.
4. Function:
In JavaScript, functions are also considered a type. They can be assigned to variables,
passed as arguments, and returned from other functions.
5. Array:
Arrays are a specialized type of object designed for storing ordered collections of values.
Each value in an array is associated with an index.
6. typeof Operator:
The typeof operator is a built-in JavaScript operator that can be used to determine the
data type of a variable or an expression. For example:
It's worth noting that JavaScript has a concept of "truthy" and "falsy" values, which means that certain
values are treated as either true or false in a boolean context. For example, 0, null, undefined, false,
NaN, and empty strings ("") are considered falsy, while all other values are considered truthy.
Understanding these concepts is crucial for writing effective and reliable JavaScript code.
Java Script E-Notes by Er. Shubham Kumar
JavaScript variable
In JavaScript, a variable is a symbolic name (an identifier) for a value. Variables are used to store and 6
manipulate data in a program. Unlike some statically-typed languages, JavaScript is dynamically typed,
meaning you don't need to declare the type of a variable explicitly; its type is determined at runtime.
var x = 10;
let y = 'Hello';
const PI = 3.14;
var: This was historically used to declare variables but has some quirks, such as function scope
instead of block scope. It's less commonly used in modern JavaScript.
let: Introduced in ECMAScript 6 (ES6), let allows you to declare variables with block scope. It's
preferable over var in most cases.
const: Also introduced in ES6, const is used to declare constants. Once a value is assigned to a
constant, it cannot be reassigned.
Remember, JavaScript variables are case-sensitive, so myVar and myvar would be treated as different
variables.
Understanding variables is fundamental to programming in JavaScript, as they allow you to store and
manipulate data throughout the execution of your program.
JavaScript includes a variety of operators that allow you to perform operations on variables and values.
Here are some of the most commonly used types of operators in JavaScript:
Arithmetic Operators:
Addition (+): let sum = 5 + 3; // Result: 8
Subtraction (-): let difference = 10 - 5; // Result: 5
Multiplication (*): let product = 4 * 6; // Result: 24
Division (/): let quotient = 20 / 4; // Result: 5
Modulus (%): let remainder = 15 % 7; // Result: 1 (remainder of the division)
Assignment Operators:
Assignment (=): let x = 10;
Addition Assignment (+=): let y = 5; y += 3; // Equivalent to: y = y + 3;
Subtraction Assignment (-=): let z = 8; z -= 2; // Equivalent to: z = z - 2;
Comparison Operators:
Equal (==):
let a = 5;
let b = '5';
console.log(a == b); // Result: true (loose equality)
Strict Equal (===):
console.log(a === b); // Result: false (strict equality)
Not Equal (!=):
console.log(a != b); // Result: false (loose inequality)
Strict Not Equal (!==):
console.log(a !== b); // Result: true (strict inequality)
Logical Operators:
Logical AND (&&):
if (condition1 && condition2) {
// code to execute if both conditions are true
}
Java Script E-Notes by Er. Shubham Kumar
Logical OR (||):
if (condition1 || condition2) { 8
// code to execute if at least one condition is true
}
Condition statements in JavaScript allow you to control the flow of your program based on whether
certain conditions are true or false. The primary condition statements in JavaScript are:
if Statement:
The if statement is used to execute a block of code if a specified condition is true.
let num = 10;
if (num > 5) {
console.log("The number is greater than 5.");
}
if-else Statement:
The if-else statement allows you to execute one block of code if the condition is true and another block
if the condition is false.
let num = 3;
if (num > 5) {
console.log("The number is greater than 5.");
} else {
console.log("The number is 5 or less.");
}
Java Script E-Notes by Er. Shubham Kumar
switch Statement:
The switch statement is used to perform different actions based on different conditions.
let day = "Monday";
switch (day) {
case "Monday":
console.log("It's the start of the week.");
break;
case "Friday":
console.log("TGIF!");
break;
default:
console.log("It's an ordinary day.");
}
Ternary Operator:
The ternary operator (? :) provides a concise way to write simple if-else statements.
let age = 20;
let status = (age >= 18) ? 'Adult' : 'Minor';
console.log(status);
Java Script E-Notes by Er. Shubham Kumar
JavaScript, loops are used to repeatedly execute a block of code until a certain condition is met. There
are several types of loops in JavaScript, including for, while, and do-while loops. Here's an overview of 10
each:
1. for Loop:
The for loop is often used when you know in advance how many times the loop should run.
for (initialization; condition; iteration) {
// code to be executed
}
2. while Loop:
The while loop is used when you want to execute a block of code as long as a specified condition is true.
while (condition) {
// code to be executed
}
Example: let i = 0;
while (i < 5) {
console.log(i);
i++;
}
3. do-while Loop:
The do-while loop is similar to the while loop, but it guarantees that the code inside the loop will be
executed at least once before checking the condition.
do {
// code to be executed
} while (condition);
Example: let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
Predefine Addition:
<!doctype html>
<html>
<head>
<title>Add Two Numbers</title>
<script>
var numOne = 7;
var numTwo = 7;
var sum = numOne+numTwo;
document.write("Sum = " + sum);
</script>
</head>
<body>
</body>
</html>
Java Script E-Notes by Er. Shubham Kumar
}
</script>
</head>
<body>
<form name="f1">
Height of Triangle<input type="text" name="t1"><br>
Base of Triangle<input type="text" name="t2"><br>
Final Answer <input type="text" name="t3"><br>
<input type="button" value="Submit" onClick="print()">
</form>
</body>
</html>
<script type="text/javascript">
function simple_interest()
{
var p,t,r,si,ci;
p = document.getElementById ("first").value;
t = document.getElementById ("second").value;
r = document.getElementById ("third").value;
si = parseInt((p*t*r)/100 );
amount = p*Math.pow((1 +r/100),t );
ci = amount-p;
document.getElementById ('num').innerHTML ="Simple interest : "+si;
document.getElementById ('num1').innerHTML ="Compound interest : "+ci;
}
</script>
</html>
</body>
</html>
Java Script E-Notes by Er. Shubham Kumar
</body>
</html>
JavaScript provides three types of popup boxes that you can use to interact with users: alert, confirm,
and prompt. These boxes are typically used for simple input, confirmation, or displaying information to 19
the user.
1. alert Box:
The alert box is used to display a message to the user. It only has an OK button.
Certainly! Below are a few simple JavaScript programs that use the alert box to display messages to the
user:
Greeting Message:
let userName = prompt("What is your name?");
let greeting = "Hello, " + userName + "!";
alert(greeting);
Simple Calculation:
let num1 = parseFloat(prompt("Enter the first number:"));
let num2 = parseFloat(prompt("Enter the second number:"));
let sum = num1 + num2;
alert("The sum is: " + sum);
Decision Making:
let userAge = parseInt(prompt("How old are you?"));
let message;
alert(message);
This program asks the user for their age and then uses an if statement to determine whether they are an
adult or a minor, displaying the result with the alert box.
Information Display:
let information = "This is an informational message.";
alert(information);
This is a straightforward program that displays an informational message using the alert box.
Java Script E-Notes by Er. Shubham Kumar
2. confirm Box:
The confirm box is used to get a binary choice from the user (OK or Cancel). It returns true if the user 20
clicks "OK" and false if the user clicks "Cancel."
JavaScript program that uses the confirm box to ask the user whether they want to delete something:
let userConfirmed = confirm("Do you want to delete this item?");
if (userConfirmed) {
alert("Item deleted successfully!");
} else {
alert("Deletion cancelled. Item remains.");
}
3. prompt Box:
The prompt box is used to prompt the user to enter some input. It returns the entered value as a string.
You can also provide a default value as the second parameter.
JavaScript program that uses the prompt box to get user input:
JS Event:
<!DOCTYPE html> 21
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event Handling Example</title>
</head>
<body>
<button id="myButton">Click me</button>
<script>
// Get the button element by its ID
let buttonElement = document.getElementById('myButton');
In this example:
1. The HTML file contains a button with the id myButton.
2. The JavaScript code gets the button element using getElementById.
3. An event listener is added to the button using addEventListener. This listener is triggered when
the button is clicked.
4. The event listener function displays an alert saying "Button clicked!".
This is a basic example, but events can be more complex, and there are many types of events, including
mouse events, keyboard events, form events, and more. You can attach event listeners to various HTML
elements and respond to user interactions with your web page.
Here are some common types of events:
Mouse Events:
click
dblclick
mouseover
mouseout
Keyboard Events:
keydown
keyup
keypress
Java Script E-Notes by Er. Shubham Kumar
Form Events:
submit 22
change
focus
blur
Window Events:
load
resize
scroll
You can handle these events using event listeners and responding with JavaScript code to create
dynamic and interactive web pages.
Java Script E-Notes by Er. Shubham Kumar
In JavaScript, an array is a data structure that stores a collection of elements. Arrays can hold various
types of data, including numbers, strings, objects, and even other arrays. Here's a basic overview of 23
working with arrays in JavaScript:
1. Declaring an Array:
You can create an array using the Array constructor or the literal notation []:
// Using literal notation
let myArray = [1, 2, 3, 4, 5];
Accessing Elements:
Array elements are accessed using zero-based indexing:
console.log(myArray[0]); // Output: 1
console.log(myArray[2]); // Output: 3
Modifying Elements:
You can modify array elements by assigning new values:
myArray[1] = 10;
console.log(myArray); // Output: [1, 10, 3, 4, 5]
Array Methods:
JavaScript provides various built-in methods for manipulating arrays:
push() and pop(): Add or remove elements from the end of an array.
myArray.push(6); // Add 6 to the end
myArray.pop(); // Remove the last element
unshift() and shift(): Add or remove elements from the beginning of an array.
myArray.unshift(0); // Add 0 to the beginning
myArray.shift(); // Remove the first element
Length Property:
The length property gives you the number of elements in an array:
console.log(myArray.length); // Output: 5
Multidimensional Arrays:
Arrays can contain other arrays, creating multidimensional arrays:
let multiArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
console.log(multiArray[1][2]); // Output: 6
Working with arrays in JavaScript involves various operations and methods for manipulation. Here's a
guide on common array operations in JavaScript:
Declaration:
let myArray = [1, 2, 3, 4, 5];
Accessing Elements:
console.log(myArray[0]); // Output: 1
console.log(myArray[2]); // Output: 3
Modifying Elements:
myArray[1] = 10;
console.log(myArray); // Output: [1, 10, 3, 4, 5]
// Removing elements
let removedElement = myArray.pop(); // Removes and returns the last element
let removedFirstElement = myArray.shift(); // Removes and returns the first element
Java Script E-Notes by Er. Shubham Kumar
// Splicing
myArray.splice(2, 1, 'a', 'b'); // Removes 1 element at index 2 and inserts 'a' and 'b'
Concatenation:
let newArray = myArray.concat([6, 7, 8]); // Concatenates two arrays
// Using forEach
myArray.forEach(function(element) {
console.log(element);
});
Multidimensional Arrays:
let multiArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
console.log(multiArray[1][2]); // Output: 6
Java Script E-Notes by Er. Shubham Kumar
In JavaScript, objects are a fundamental data type that allows you to store and organize data in key-
value pairs. Objects are used to represent real-world entities and their properties. Here's a basic 26
overview of working with objects in JavaScript:
Object Declaration:
// Using object literal notation
let person = {
name: 'John',
age: 30,
gender: 'male',
isStudent: false,
};
// Removing a property
delete car.year;
Java Script E-Notes by Er. Shubham Kumar
Object Methods: 27
let rectangle = {
width: 10,
height: 5,
calculateArea: function() {
return this.width * this.height;
},
};
console.log(rectangle.calculateArea()); // Output: 50
// Creating instances
let dog1 = new Dog('Buddy', 3);
let dog2 = new Dog('Max', 5);
Object Destructuring:
let { name, age } = person;
console.log(name, age); // Output: John 31
Java Script E-Notes by Er. Shubham Kumar
Object Iteration: 28
// Using for...in loop
for (let key in person) {
console.log(key + ': ' + person[key]);
}
// Using Object.keys
let keys = Object.keys(person);
console.log(keys); // Output: ['name', 'age', 'gender', 'isStudent']
In JavaScript, functions are reusable blocks of code that perform a specific task or return a value.
Functions play a fundamental role in structuring JavaScript code. Here's a basic overview of working
with functions:
Function Declaration:
// Basic function declaration
function greet(name) {
console.log('Hello, ' + name + '!');
}
// Function invocation
greet('John'); // Output: Hello, John!
Java Script E-Notes by Er. Shubham Kumar
Function Expression:
// Function expression 29
let add = function(a, b) {
return a + b;
};
Return Statement:
function square(x) {
return x * x;
}
Callback Functions:
function doSomething(callback) {
// Perform some tasks
callback();
}
doSomething(function() {
console.log('Callback function executed.');
});
Function Scope:
let globalVar = 'I am global';
function exampleFunction() {
let localVar = 'I am local';
console.log(globalVar); // Accessing global variable
console.log(localVar); // Accessing local variable
}
exampleFunction();
Closures:
function outerFunction(x) {
return function(y) {
return x + y;
};
}
Recursion:
function factorial(n) {
if (n <= 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
JavaScript in real-time applications involves creating interactive and dynamic features on websites or
web applications. JavaScript is commonly used in the frontend to enhance user experience and
responsiveness. Here are some common scenarios where JavaScript is used in real-time applications:
Event Handling:
JavaScript is used to handle various user interactions such as clicks, keypresses, form
submissions, and more.
Example: document.getElementById('myButton').addEventListener('click', function() {
alert('Button clicked!');
});
AJAX (Asynchronous JavaScript and XML) Requests:
JavaScript is used to make asynchronous requests to the server, allowing data to be fetched or
sent without reloading the entire page.
Example using the Fetch API:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Java Script E-Notes by Er. Shubham Kumar
WebSockets: 32
WebSockets enable real-time communication between the client and server, allowing for
bidirectional data exchange.
Example using the WebSocket API:
const socket = new WebSocket('wss://example.com/socket');
socket.addEventListener('message', function(event) {
console.log('Received:', event.data);
});
function validateForm() {
// Perform validation checks and return true or false
}
Form validation in JavaScript involves checking user input on the client side before submitting the form
to the server. This helps ensure that the data submitted is accurate, complete, and meets certain
criteria. Here's a basic example of how you can perform form validation using JavaScript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation</title>
<style>
.error {
color: red;
}
</style>
</head>
<body>
<br>
Java Script E-Notes by Er. Shubham Kumar
<label for="email">Email:</label> 34
<input type="email" id="email" name="email">
<span id="emailError" class="error"></span>
<br>
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<span id="passwordError" class="error"></span>
<br>
<script>
function validateForm() {
// Get form elements
var username = document.getElementById('username').value;
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
// Perform validation
if (username.trim() === '') {
document.getElementById('usernameError').innerText = 'Username is required';
return false;
}
// Simple email validation (you might want to use a regular expression for more thorough
validation)
if (email.trim() === '' || !email.includes('@')) {
document.getElementById('emailError').innerText = 'Valid email is required';
return false;
}
Java Script E-Notes by Er. Shubham Kumar
</body>
</html>
In this example:
The form has three fields: username, email, and password.
The JavaScript function validateForm is called when the form is submitted (onsubmit="return
validateForm()").
The function retrieves the values from the form fields and performs basic validation.
If any validation fails, error messages are displayed, and the form submission is prevented by
returning false.
If all validation passes, the form is submitted.
Note that this is a simple example, and you may need to customize the validation based on your specific
requirements. Additionally, server-side validation is crucial for security, as client-side validation can be
bypassed. Always validate user input on the server side as well.