JavaScript E Notes by Er Shubham Kumar KCS052-1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 35

Java Script E-Notes by Er.

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.

1. HTML (Hypertext Markup Language):

 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.

2. CSS (Cascading Style Sheets):

 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:

 JavaScript is a powerful, versatile scripting language that enables dynamic content on


web pages.

 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.

 It's an object-oriented language, supporting concepts such as objects, functions, and


methods.

4. Dynamic Typing:

 JavaScript is a dynamically-typed language, allowing variables to hold values of any data


type. This flexibility can simplify development but requires careful handling to avoid
unexpected behavior.

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.

6. Common Use Cases:

 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.

 Asynchronous operations: JavaScript supports asynchronous programming through


features like callbacks and Promises, enabling non-blocking operations like fetching data
from servers.

7. Frameworks and Libraries:

 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):

 Recognizing the need for standardization, Netscape submitted JavaScript to Ecma


International in 1997. The standardization process led to the creation of ECMAScript,
which is the official specification that JavaScript adheres to. ECMAScript defines the core
features of the language.

4. Browser Wars and Internet Explorer:

 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.

5. DOM and Ajax:

 The introduction of the Document Object Model (DOM) allowed JavaScript to


dynamically manipulate HTML and XML documents. This capability, coupled with the
advent of Asynchronous JavaScript and XML (Ajax), enabled the development of more
interactive and responsive web applications.
Java Script E-Notes by Er. Shubham Kumar

6. JavaScript in the 2000s:


4
 JavaScript continued to evolve, but its usage was somewhat limited due to
inconsistencies across different browsers. Libraries like jQuery emerged to address
these issues, providing a cross-browser compatibility layer.

7. JavaScript on the Server:

 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.

8. Modern JavaScript (ES6 and Beyond):

 ECMAScript 6 (ES6), introduced in 2015, brought significant enhancements to the


language, including arrow functions, classes, modules, and other features that improved
the developer experience. Subsequent versions of ECMAScript have continued to add
new capabilities and syntax.

9. Frameworks and Libraries:

 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.

Java Script Types

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:

1. Primitive Data Types:

 Undefined: Represents a variable that has been declared but not assigned any value.

 Null: Represents the intentional absence of any object value.

 Boolean: Represents a logical entity and can have two values: true or false.

 Number: Represents numeric values, including integers and floating-point numbers.


Java Script E-Notes by Er. Shubham Kumar

 String: Represents a sequence of characters, enclosed in single or double quotes.


5
2. Special Types:

 Symbol: Introduced in ECMAScript 6 (ES6), symbols are unique and immutable values,
often used as property keys in objects to avoid name clashes.

 BigInt: Also introduced in ECMAScript 6, BigInt is a numeric primitive representing


integers of arbitrary precision.

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:

typeof 42; // "number"

typeof "Hello"; // "string"

typeof true; // "boolean"

typeof undefined; // "undefined"

typeof null; // "object" (unfortunately, this is a long-standing quirk in JavaScript)

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.

Here's how you declare a variable in JavaScript:

// Using the var keyword (older, less commonly used)

var x = 10;

// Using the let keyword (introduced in ECMAScript 6)

let y = 'Hello';

// Using the const keyword (introduced in ECMAScript 6)

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.

Variables can hold various types of data:

let num = 42; // number


let name = 'John'; // string
let isTrue = true; // boolean
let myArray = [1, 2, 3]; // array
let person = { // object
firstName: 'John',
lastName: 'Doe'
};
// Variables can also hold special values
let notANumber = NaN;
let infinityValue = Infinity;
let notDefined = undefined;
let noValue = null;
Java Script E-Notes by Er. Shubham Kumar

To update the value of a variable, you simply assign a new value:


let count = 5; 7
count = count + 1;
// or using the shorthand +=
count += 1;

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
}

Logical NOT (!):


if (!condition) {
// code to execute if the condition is false
}

Increment and Decrement Operators:


Increment (++) and Decrement (--):
let counter = 3;
counter++; // Increment by 1 (result: 4)
counter--; // Decrement by 1 (result: 3)

Conditional (Ternary) Operator:


let age = 20;
let status = (age >= 18) ? 'Adult' : 'Minor';

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

if-else if-else Statement:


You can use the else if statement to check multiple conditions in sequence. 9
let num = 7;
if (num > 10) {
console.log("The number is greater than 10.");
} else if (num > 5) {
console.log("The number is greater than 5 but not more than 10.");
} else {
console.log("The number is 5 or less.");
}

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
}

Example: for (let i = 0; i < 5; i++) {


console.log(i);
}

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);

Loop Control Statements:


JavaScript also provides loop control statements such as break and continue.
 The break statement is used to exit the loop prematurely.
 The continue statement is used to skip the rest of the code inside the loop and move to the next
iteration.
Java Script E-Notes by Er. Shubham Kumar

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


if (i === 2) { 11
continue; // skip iteration when i is 2
}
if (i === 4) {
break; // exit the loop when i is 4
}
console.log(i);
}

#Basic Programs of Java Script

Find Your Current Age:


<!DOCTYPEhtml>
<html>
<head>
<title> JavaScript</title>
<p>current_year=2022,birth_year=2002</p>
</head>
<body>
<script language="javascript">
var current_year=2022,birth_year=2002,age
age=current_year-birth_year
document.write("Your Age is =",age)
</script>
</body>
</html>
Java Script E-Notes by Er. Shubham Kumar

Find Average Value 12


<!DOCTYPEhtml>
<html>
<head>
<title> JavaScript</title>
</head>
<body>
<script language="javascript">
var m1=39, m2=49, m3=41,avg
avg=(m1+m2+m3)/3
//Engineering Addaa
document.write("m1=39<br> m2=49<br> m3=41")
document.write("Average =", avg)
//var no1=20, no2=30, sum
//sum=no1+no2
//document.write("Your result is =",sum)
</script>
</body>
</html>

Print 122333444455555 in Vertical using loops


<html>
<head>
<script type="text/javascript">
var i,j;
for(i=1; i<=5; i++)
{
for(j=1;j<=i;j++)
{
document.write(i)
document.write("<br>")
}
}
</script>
</head>
<body>
</body>
</html>
Java Script E-Notes by Er. Shubham Kumar

Area of Circle using Function:


<html> 13
<head>
<script>
function print()
{
var height,base,Result;
height=parseInt(f1.t1.value);
base=parseInt(f1.t2.value);
Result=0.5*height*base;
f1.t3.value=Result;
}
</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>

Print your Name is 1000 time dynamic:


<html>
<head>
<title>js</title>
</head>
<body>
<script type="text/javascript">
var count;
var s1=prompt("Enter your name",0)
for(count=0; count<25; count++){
document.write(s1)
document.write("<br/>")
}
</script>
</body>
</html>
Java Script E-Notes by Er. Shubham Kumar

(a+b)2 using Function:


<html> 14
<head>
<script>
function print()
{
var a,b,Result;
a=parseInt(f1.t1.value);
b=parseInt(f1.t2.value);
Result=a*a+b*b+2*a*b;
f1.t3.value=Result;
}
</script>
</head>
<body>
<form name="f1">
Enter Value of (A)<input type="text" name="t1"><br>
Enter Value of (B)<input type="text" name="t2"><br>
Your Final Answer <input type="text" name="t3"><br>
<input type="button" value="Submit" onClick="print()">
</form>
</body>
</html>

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

Area of Triangle using function:


<html> 15
<head>
<script>
function print()
{
var height,base,Result;
height=parseInt(f1.t1.value);
base=parseInt(f1.t2.value);
Result=0.5*height*base;
f1.t3.value=Result;

}
</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>

Simple Intrest CI SI:


<html>
<head>
<title>JavaScript Program to find Simple Interest and Compound Interest</title>
</head>
<body>
<table>
<tr>
<td> <input type="text" name="a" id="first" placeholder="Enter principal"/> </td>
</tr>
<tr>
<td> <input type="text" name="b" id="second" placeholder="Enter time period "/> </td>
</tr>
<tr>
<td> <input type="text" name="c" id="third" placeholder="Enter rate of interest(%)"/> </td>
</tr>
<tr>
Java Script E-Notes by Er. Shubham Kumar

<td> <button onclick = "simple_interest()" >Submit</button> </td>


</tr> 16
</table>
<div id="num"> </div>
<div id="num1"></div>
</body>

<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>

Print your Name according user limit :


<html>
<head>
</head>
<body>
<script type="text/javascript">
var count;
var range=prompt("Enter your Range to Print Your Name",0)
var name=prompt("Enter your name",0);
for(count=0; count<range; count++)
{
document.write("<br>",name)
//document.write("<br>")
}
</script>
</body>
</html>
Java Script E-Notes by Er. Shubham Kumar

Form Action using Javascript:


<!DOCTYPE html> 17
<html>
<head>
<script type="text/javascript">
function message()
{
alert("Your form has been submitted succesfully....");
}
</script>
</head>
<body>
<form onsubmit="message()">
<table>
<tr>
<td>User ID<br><input type="text" name="id"
placeholder="Enter Your ID"></td>
</tr>
<tr>
<td> Password<br><input type="Password"
name="Password" placeholder="Enter Your Password"></td>
</tr>
<tr>
<td><input type="Submit"></td>
</tr>
</table>
</form>

</body>
</html>
Java Script E-Notes by Er. Shubham Kumar

On load event using alert box: 18


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function message()
{
alert("Click Ok to Visit this webpage....");
}
</script>
</head>
<body onload="message()">
<h1>Hellow</h1>

</body>
</html>

Radius of circle using Let and get function :


<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Radious of Circle</h2>
<p>pie = 3.14, r = 2, calculate sum = pie*r*r, and display sum:</p>
<p id="result"></p>
<script>
let pie = 3.14;
let r = 25 ;
let sum = pie*r*r;
document.getElementById("result").innerHTML = sum;
</script>
</body>
</html>
Java Script E-Notes by Er. Shubham Kumar

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.

alert("This is an alert message!");

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;

if (userAge >= 18) {


message = "You are an adult.";
} else {
message = "You are a minor.";
}

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."

let result = confirm("Do you want to proceed?");


if (result) {
console.log("User clicked OK");
} else {
console.log("User clicked 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.

let userInput = prompt("Please enter your name:", "John Doe");


if (userInput !== null) {
console.log("User entered: " + userInput);
} else {
console.log("User clicked Cancel");
}

JavaScript program that uses the prompt box to get user input:

let userInput = prompt("Please enter your favorite color:");


if (userInput !== null) {
alert("Your favorite color is: " + userInput);
} else {
alert("No input provided. Defaulting to 'Unknown'.");
}
Java Script E-Notes by Er. Shubham Kumar

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');

// Add an event listener to the button


buttonElement.addEventListener('click', function() {
alert('Button clicked!');
});
</script>
</body>
</html>

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];

// Using the Array constructor


let anotherArray = new Array(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

splice(): Add, remove, or replace elements at a specific position.


myArray.splice(2, 1, 'a', 'b'); // Remove 1 element at index 2 and insert 'a' and 'b'

concat(): Concatenate two arrays.


let newArray = myArray.concat([6, 7, 8]);

slice(): Extract a portion of an array.


let slicedArray = myArray.slice(1, 3); // Extract elements at index 1 and 2
Java Script E-Notes by Er. Shubham Kumar

forEach(): Execute a provided function once for each array element. 24


myArray.forEach(function (element) {
console.log(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]

Adding and Removing Elements:


// Adding elements
myArray.push(6); // Adds 6 to the end
myArray.unshift(0); // Adds 0 to the beginning

// 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

Slicing and Splicing:


// Slicing 25
let slicedArray = myArray.slice(1, 3); // Extract elements at index 1 and 2

// 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

Iterating over Elements:


// Using for loop
for (let i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
}

// Using forEach
myArray.forEach(function(element) {
console.log(element);
});

Filter, Map, and Reduce:


// Filter: Creates a new array with elements that pass a test
let filteredArray = myArray.filter(function(element) {
return element > 2;
});

// Map: Creates a new array by applying a function to each element


let mappedArray = myArray.map(function(element) {
return element * 2;
});

// Reduce: Reduces the array to a single value


let sum = myArray.reduce(function(acc, current) {
return acc + current;
}, 0);

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,
};

// Using the Object constructor


let car = new Object();
car.make = 'Toyota';
car.model = 'Camry';
car.year = 2022;

Accessing Object Properties:


console.log(person.name); // Output: John
console.log(car['make']); // Output: Toyota

Modifying Object Properties:


person.age = 31;
car['year'] = 2023;

Adding and Removing Properties:


// Adding a new property
person.job = 'Engineer';

// 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

Object Constructors and Prototypes:


// Object constructor function
function Dog(name, age) {
this.name = name;
this.age = age;
}

// Creating instances
let dog1 = new Dog('Buddy', 3);
let dog2 = new Dog('Max', 5);

JSON (JavaScript Object Notation):


// Converting object to JSON
let jsonPerson = JSON.stringify(person);

// Converting JSON to object


let parsedPerson = JSON.parse(jsonPerson);

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']

Object Prototypes and Inheritance:


// Creating a prototype
function Animal(name) {
this.name = name;
}

// Creating an instance with inheritance


function Dog(name, breed) {
Animal.call(this, name);
this.breed = breed;
}

let myDog = new Dog('Buddy', 'Labrador');

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;
};

// Invoking the function expression


let result = add(3, 5); // Output: 8

Arrow Functions (ES6 and later):


// Arrow function
let multiply = (a, b) => a * b;

// Invoking the arrow function


let product = multiply(4, 6); // Output: 24

Function Parameters and Arguments:


function addNumbers(num1, num2) {
return num1 + num2;
}

let sum = addNumbers(2, 3); // Output: 5

Return Statement:
function square(x) {
return x * x;
}

let squaredValue = square(4); // Output: 16

Default Parameters (ES6 and later):


function power(base, exponent = 2) {
return Math.pow(base, exponent);
}

let result1 = power(3); // Output: 9


let result2 = power(2, 4); // Output: 16
Java Script E-Notes by Er. Shubham Kumar

Rest Parameters (ES6 and later):


function sumAll(...numbers) { 30
return numbers.reduce((total, num) => total + num, 0);
}

let totalSum = sumAll(1, 2, 3, 4); // Output: 10

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;
};
}

let innerFunction = outerFunction(5);


let result = innerFunction(3); // Output: 8
Java Script E-Notes by Er. Shubham Kumar

IIFE (Immediately Invoked Function Expression): 31


(function() {
console.log('I am an IIFE');
})();

Recursion:
function factorial(n) {
if (n <= 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}

let result = factorial(5); // Output: 120

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);
});

// Send data to the server


socket.send('Hello, server!');

Dynamic DOM Manipulation:


 JavaScript is used to dynamically update the Document Object Model (DOM) based on user
actions or server responses.
 Example: document.getElementById('myElement').innerHTML = 'New content';
Form Validation:
 JavaScript can be used to validate form inputs in real-time, providing instant feedback to users.
 Example:
document.getElementById('myForm').addEventListener('submit', function(event) {
if (!validateForm()) {
event.preventDefault();
}
});

function validateForm() {
// Perform validation checks and return true or false
}

Animations and Transitions:


 JavaScript is used to create dynamic animations and transitions to improve the visual appeal of
web pages.
 Example using CSS animations triggered by JavaScript:
document.getElementById('myElement').classList.add('animate');
Java Script E-Notes by Er. Shubham Kumar

Single Page Applications (SPAs): 33


 JavaScript frameworks/libraries like React, Angular, or Vue.js are used to build SPAs, where most
of the application logic runs on the client side, providing a smoother user experience.
 Example (React):
// React component rendering
ReactDOM.render(<MyApp />, document.getElementById('root'));

Geolocation and Maps:


 JavaScript can be used to access the user's geolocation and display maps in real-time.
 Example using the Geolocation API:
navigator.geolocation.getCurrentPosition(function(position) {
console.log('Latitude:', position.coords.latitude);
console.log('Longitude:', position.coords.longitude);
});

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>

<h2>Form Validation Example</h2>

<form id="myForm" onsubmit="return validateForm()">


<label for="username">Username:</label>
<input type="text" id="username" name="username">
<span id="usernameError" class="error"></span>

<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>

<input type="submit" value="Submit">


</form>

<script>
function validateForm() {
// Get form elements
var username = document.getElementById('username').value;
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;

// Reset error messages


document.getElementById('usernameError').innerText = '';
document.getElementById('emailError').innerText = '';
document.getElementById('passwordError').innerText = '';

// 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

// Password should be at least 8 characters 35


if (password.trim() === '' || password.length < 8) {
document.getElementById('passwordError').innerText = 'Password should be at least 8
characters';
return false;
}

// If all validation passes, the form is submitted


return true;
}
</script>

</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.

You might also like