0% found this document useful (0 votes)
5 views40 pages

JavaScript Notes

The document provides an overview of JavaScript, including its history, creation, and evolution, as well as its core features and use cases. It covers JavaScript variables, data types, functions, and objects, explaining how to declare variables, define functions, and create objects. Additionally, it discusses the differences between client-side and server-side scripting, and highlights the importance of JavaScript in web development.

Uploaded by

belimsejan0
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)
5 views40 pages

JavaScript Notes

The document provides an overview of JavaScript, including its history, creation, and evolution, as well as its core features and use cases. It covers JavaScript variables, data types, functions, and objects, explaining how to declare variables, define functions, and create objects. Additionally, it discusses the differences between client-side and server-side scripting, and highlights the importance of JavaScript in web development.

Uploaded by

belimsejan0
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

Sem-5

Subject Name – Web Development with JavaScript


Subject Code – SC23MJDSCCS501

UNIT I: Core JavaScript and ES6+

History of JavaScript

In May 1995, Brendan Eich created JavaScript, a programming language, in just ten days.
Initially developed to enhance interactivity on websites, it was designed to add dynamic
features to static HTML pages, primarily for client-side development.

Client-Side Scripting Server-Side Scripting


Runs in the browser Runs on the web server
Code is visible to users Code is hidden from users
Faster for UI interactions Handles data processing and business logic
Cannot directly access databases Can access databases
Example: JavaScript Examples: PHP, [Link], Python

Creation of JavaScript

●​ In 1995 Netscape Communications Corporation needed a way to make web pages


more interactive and dynamic.
●​ Brendan Eich was hired by Netscape to develop a new scripting language for this
purpose.
●​ The language was initially called Mocha and later changed to LiveScript.
●​ In December 1995, LiveScript was renamed JavaScript, partly to capitalize on the
growing popularity of the programming language Java.
●​ JavaScript was designed to be lightweight, interpreted, and primarily used for
client-side scripting to manipulate web page elements in real-time.
●​
JavaScript and ECMAScript

●​ In 1996 javaScript was submitted to ECMA (European Computer Manufacturers


Association.) International, a standardization organization, for approval.
●​ This submission led to the creation of the ECMAScript standard, which outlined the
specifications for the language.
●​ The first edition of ECMAScript was published as ECMAScript 1 in 1997.
●​ The initial version of JavaScript was basic and lacked many modern features we now
use.

Nidhi Patel
●​ Although limited in functionality, the first version of JavaScript was still
revolutionary for web development at the time.

Browser Wars and JavaScript’s Evolution

●​ In the late 1990s, the Browser Wars between Netscape and Internet Explorer led to
each browser creating its own version of JavaScript, causing fragmentation and
incompatibility between them.

JavaScript Frameworks and Libraries

●​ React
●​ Angular
●​ [Link]

Use Cases of JavaScript

●​ JavaScript is mainly used to make web pages interactive and dynamic. Some
important use cases are:

1.​ Form Validation: - Form validation checks whether the data entered by a user is
correct before it is sent to the server.

JavaScript can check:


●​ Is the email in the correct format?
●​ Is the password at least 8 characters long?
●​ Are any fields empty?

​ Without JavaScript the form is submitted to the server, which then checks the data
and sends an error message back.

2.​ Creating Dynamic Web Pages: - A dynamic page changes its content without
requiring a complete reload.
Example: - On an online shopping site:
You add a product to the cart.
The cart count changes instantly.

3.​ Interactive User Interfaces (UI): - A User Interface is what users interact with on a
website.
Examples: Buttons, Menus, Dropdowns, Tabs, Search boxes

4.​ Animations and Visual Effects: - JavaScript can create animations to make websites
attractive.

Nidhi Patel
Examples: - Image sliders, Fade effects, loading animations, Scrolling effects
5.​ Single Page Applications (SPA): -A Single Page Application loads only one page and
updates content dynamically.
Examples :-Gmail ,Google Maps ,Facebook

6.​ Server-Side Development: - Originally, JavaScript worked only in browsers.


Today, JavaScript can also run on servers using [Link].

7.​ Mobile Application Development: -JavaScript can be used to create mobile apps.
Examples: -Shopping apps, Food delivery apps, educational apps

8.​ Game Development: -JavaScript can create browser-based games.


Examples: -Puzzle games, Quiz games, Snake game, Chess game

9.​ Real-Time Applications: -Applications that update instantly without refreshing.


Examples: -Chat applications, Video conferencing, Live score websites, Online
collaboration tools

10.​Desktop Application Development: -JavaScript can also create desktop software.


Examples: -Code editors, Music players, Chat applications

JavaScript Variables

Variables in JavaScript are used to store data values. They can be declared in different ways
depending on how the value should behave.
●​ Variables can be declared using var, let, or const.
●​ JavaScript is dynamically typed, so types are decided at runtime.
●​ You don’t need to specify a data type when creating a variable.

Example:-
// Old style
var a = 10
// Preferred for non-const
let b = 20;
// Preferred for const (cannot be changed)
const c = 30;
[Link](a);
[Link](b);
[Link](c);

1. 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: -

Nidhi Patel
var a = "Hello Geeks";
var b = 10;
[Link](a);
[Link](b);

2. 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 = "gfg";
[Link](a);
[Link](b);

3. 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 = "gfg";
[Link](a);
[Link](b);

example:- let,const,var
<!DOCTYPE html>
<html>
<head>
<title>var let const Example</title>
</head>
<body>
<h2>Open Console (F12) to See Output</h2>

<script>
// var
var name = "John";
var name = "Mike"; // Redeclaration allowed
name = "David"; // Reassignment allowed

// let
let age = 25;
let age = 30; // Error: Redeclaration not allowed
age = 30; // Reassignment allowed

// const

Nidhi Patel
const country = "India";
country = "USA"; // Error: Reassignment not allowed

[Link]("var name =", name);


[Link]("let age =", age);
[Link]("const country =", country);

// Scope Example
{
var x = 100;
let y = 200;
const z = 300;

[Link]("Inside block:");
[Link]("x =", x);
[Link]("y =", y);
[Link]("z =", z);
}

[Link]("Outside block:");
[Link]("x =", x); // Works

[Link](y); // Error
[Link](z); // Error
</script>

</body>
</html>

Rules for Naming Variables

When naming variables in JavaScript, follow these rules

●​ Variable names must begin with a letter, underscore (_), or dollar sign ($).
●​ Subsequent characters can be letters, numbers, underscores, or dollar signs.
●​ Variable names are case-sensitive (e.g., age and Age are different variables).
●​ Reserved keywords (like function, class, return, etc.) cannot be used as variable
names.

Nidhi Patel
Example:-
let userName = "Suman”; // Valid
let $price = 100; // Valid
let _temp = 0; // Valid
let 123name = "Ajay"; // Invalid
let function = "gfg"; // Invalid

JavaScript Datatypes

Type Description
String A text of characters enclosed in quotes
Number A number representing a mathematical value
Bigint A number representing a large integer
Boolean A data type representing true or false
Object A collection of key-value pairs of data
Undefined A primitive variable with no assigned value
Null A primitive value representing object absence
Symbol A unique and primitive identifier

Example:-
// String​
let color = "Yellow";​
let lastName = "Johnson";​

// Number​
let length = 16;​
let weight = 7.5;​

// BigInt​
let x = 1234567890123456789012345n;​
let y = BigInt(1234567890123456789012345)​

// Boolean​
let x = true;​
let y = false;​

// Object​
const person = {firstName:"John", lastName:"Doe"}​
// Array object​
const cars = ["Saab", "Volvo", "BMW"];​

Nidhi Patel
// Date object​
const date = new Date("2022-03-25");​

// Undefined​
let x;​
let y;​

// Null​
let x = null;​
let y = null;​

// Symbol​
const x = Symbol();​
const y = Symbol();

JavaScript Display Possibilities

JavaScript is used to display information or output on a web page. It provides different


methods to show data to the user or to the developer.
●​ The innerHTML property is used to display or change the HTML content of an
element.
Syntax :- [Link]("elementId").innerHTML = "Your Content";
●​ The innerText property displays only the text content of an HTML element. It does
not interpret HTML tags.
​ Syntax:- [Link]("elementId").innerText = "Your Text";
●​ The [Link]() method writes content directly to the HTML document.
Syntax:- [Link]("Your Content");
●​ The [Link]() method displays a message in a pop-up alert box.
​ Syntax:- [Link]("Your Message");
●​ The [Link]() method displays output in the browser's Developer Console. It is
mainly used for testing and debugging programs.
​ Syntax:- [Link]("Your Message");

Functions in JavaScript

●​ Functions in JavaScript are reusable blocks of code designed to perform specific


tasks.
●​ They can take inputs, perform actions, and return outputs.

Nidhi Patel
JavaScript Function Return

●​ When a function reaches a return statement, the function stops executing.


●​ The value after the return keyword is sent back to the caller.

Calling Functions
●​ Functions are executed when they are called or invoked
●​ You call a function by adding parentheses to its name: name()
example
<!DOCTYPE html>
<html>
<head>
<title>Function Example</title>
</head>
<body>
<script>
// Function Definition
function greet()
{
// Print message on web page
[Link]("Welcome to JavaScript!");
}
// Function Calling
greet();
</script>
</body>
</html>

Function Parameters

●​ Parameters allow you to send values to a function


●​ Parameters are listed in parentheses in the function definition
example 1:-
<!DOCTYPE html>
<html>
<head>
<title>Function with Parameters</title>
</head>
<body>
<script>
// Function Definition
// name is a parameter
function welcome(name)
{

Nidhi Patel
// Print message on web page
[Link]("Welcome " + name);
}
// Function Calling
// Rahul is an argument
welcome("Rahul");
</script>
</body>
</html>

example 2:-
<script>
// Function Definition
// num1 and num2 are parameters
function add(num1, num2)
{
// Calculate sum
let sum = num1 + num2;
// Print result
[Link]("Sum = " + sum);
}
// Function Calling
// 10 and 20 are arguments
add(10, 20);
</script>

Parameters vs. Arguments

●​ In JavaScript, function parameters and arguments are distinct concepts


●​ Parameters are the names listed in the function definition.
●​ Arguments are the real values passed to, and received by the function.

Arrow Functions

●​ Arrow Functions is a short syntax for function expressions


●​ You can skip the function keyword
●​ You can skip the return keyword
●​ You can skip the curly brackets

example

<!DOCTYPE html>
<html>

Nidhi Patel
<head>
<title>Arrow Function Example</title>
</head>
<body>
<script>
// Arrow Function Definition
// a and b are parameters
const multiply = (a, b) => a * b;
// Function Calling
// 4 and 5 are arguments
let result = multiply(4, 5);
// Display the result on the web page
[Link]("The Product is: " + result);
</script>
</body>
</html>

JavaScript Callbacks

A callback function is a function that is passed as an argument to another function and


executed later.
●​ A function can accept another function as a parameter.
●​ Callbacks allow one function to call another at a later time.
●​ A callback function can execute after another function has finished.

example:-
function greet(name, callback)
{
[Link]("Hello, " + name);
callback();
}
function sayBye()
{
[Link]("Goodbye!");
}
greet("Ajay", sayBye);

//out put
//Hello, Ajay
//Goodbye!

Working of Callbacks in JavaScript

Nidhi Patel
JavaScript executes code line by line (synchronously), but sometimes we need to delay
execution or wait for a task to complete before running the next function. Callbacks help
achieve this by passing a function that is executed later.

JavaScript Objects

●​ Objects are variables that can store both values and functions.
●​ Values are stored as key:value pairs called properties.
●​ Functions are stored as key:function() pairs called methods.

How to Create a JavaScript Object

1.​ Object Literal (Most common)


●​ An object literal is the simplest and most common way to define a JavaScript
object.
●​ An object literal "literally" describes an object using a concise syntax with
zero or more key:value pairs inside curly braces to describe all the object
properties
●​ It means we can create an object directly using { } braces without using any
special keyword or class. This direct way is called Object Literal.​
example:-
​ <!DOCTYPE html>
<html>
<body>
<script>
// Create Object (Object Literal)
const person = { firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"};
// Print all properties in single line
[Link]( "First Name: " + [Link] + "<br>" +
"Last Name: " + [Link] + "<br>" +
"Age: " + [Link] + "<br>" +
"Eye Color: " + [Link]);
</script>
</body> </html>

2.​ Using new Object()

●​ Create a new JavaScript object using new Object()


​ example:-

Nidhi Patel
​ // Create an Object
const person = new Object({
firstName: "John",
​ lastName: "Doe",
​ ​ age: 50,
eyeColor: "blue" });

JavaScript Object Properties

●​ Properties are key:value Pairs


●​ A JavaScript object is a collection of properties
●​ Properties can be changed, added, and deleted.

Accessing JavaScript Properties

You can access object properties in these ways:


●​ Dot notation ​ [Link]
●​ Bracket notation​ objectName["propertyName"]
●​ Expression​ ​ objectName[expression]

example:-
<!DOCTYPE html>
<html>
<body>
<script>
// Create an Object
const student = { name: "Rahul",
age: 20,
city: "Ahmedabad"};
// 1. Dot Notation
[Link]("Dot Notation: " + [Link] + "<br>");
// 2. Bracket Notation
[Link]("Bracket Notation: " + student["age"] + "<br>");
// 3. Expression (using variable as key)
let key = "city";
[Link]("Expression: " + student[key]);
</script>
</body>
</html>

Properties :- Add, Change, Delete, Check

Nidhi Patel
●​ Add (Insert): Adding a new property to an object.
●​ Change (Update): Modifying an existing property value.
●​ Delete: Removing a property from an object.
●​ Check: Verifying whether a property exists in an object.

example:-
<!DOCTYPE html>
<html>
<body>
<script>
// 1. CREATE object
const student = { name: "Rahul", age: 20};
[Link]("Original Object: " + [Link] + " " + [Link] +
"<br><br>");
// 2. ADD new property
[Link] = "Ahmedabad";
[Link]("After Adding City: " + [Link] + " " + [Link] + " " +
[Link] + "<br>");
// 3. CHANGE existing property
[Link] = 21;
[Link]("After Changing Age: " + [Link] + " " + [Link] + " " +
[Link] + "<br>");
// 4. DELETE a property
delete [Link];
[Link]("After Deleting Name: " + [Link] + " " + [Link] + " " +
[Link] + "<br>");
// 5. CHECK property exists or not
[Link]("Check if 'age' exists: " + ("age" in student));
</script>
</body>
</html>

Object Methods

●​ Methods are actions that can be performed on objects.


●​ Methods are functions stored as property values.
●​ In an object method, this refers to the object.
●​ To call an object method, add parentheses (): [Link]()
●​ Without parentheses you get the function itself.
example 1
<!DOCTYPE html>
<html> <body> <p id="demo"></p>

Nidhi Patel
<script>
const person = { firstName : "John",
lastName : "Doe",
age : 50,
​ fullName : function()
{
​ ​ return [Link] + " " + [Link];
}
};
[Link]("demo").innerHTML = [Link]();
//[Link]([Link]());
</script>
</body>
</html>

Display Objects

●​ Displaying the Object Properties by name


●​ Displaying the Object Properties in a Loop
●​ Displaying the Object using [Link]()
●​ Displaying the Object using [Link]()
example
<!DOCTYPE html>
<html> <body> <p id="demo"></p>
<script>
// Create an Object
const person = { name: "John",
​ ​ age: 30,
​ ​ city: "New York" };
// Display Properties
let text = [Link] + ", " + [Link] + ", " + [Link];
[Link]("demo").innerHTML = text;
</script>
</body> </html>

Nidhi Patel
Arrays

●​ An array in JavaScript is an ordered list of values that allows you to store multiple
items under a single variable name.
●​ An Array is an object type designed for storing data collections.
●​ An array can hold many values under a single name, and you can access the values by
referring to an index number.
●​ arrays are stored in contiguous memory.

example
const fruit1 = "Apple";
const fruit2 = "Banana";
const fruit3 = "Mango";
We can store all the values in one array:
const fruits = ["Apple", "Banana", "Mango"];

Creating an Array
●​ There are three common ways to create an array in JavaScript.

1. Using an Array Literal


●​ This is the easiest and most commonly used method.
example
const cars = ["Saab", "Volvo", "BMW"];

2. Creating an Empty Array


●​ You can first create an empty array and then add values later.
example
​ const cars = [];
cars[0] = "Saab";
cars[1] = "Volvo";
cars[2] = "BMW";
[Link](cars);

3. Using the new Array() Keyword


●​ Another way to create an array is by using the new Array() constructor.
example
​ const cars = new Array("Saab", "Volvo", "BMW");
[Link](cars);

Nidhi Patel
Accessing Array Elements

Each item in an array has an index number.


●​ The first element has index 0
●​ The second element has index 1
●​ The third element has index 2
example
const cars = ["Saab", "Volvo", "BMW"];
[Link](cars[0]); // Saab
[Link](cars[1]); // Volvo
[Link](cars[2]); // BMW

Changing an Array Element


example
<script>
const cars = ["Saarb", "Volvo", "BMW"];
cars[0] = "Opel";
[Link]("demo").innerHTML = cars;
</script>

The length Property

●​ The length property of an array returns the length of an array (the number of array
elements).
example
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let size = [Link];
[Link]("demo").innerHTML = size;
</script>

JavaScript Array Methods

1. Array length
Description: Returns the number of elements in an array.
example
let fruits = ["Apple", "Banana", "Mango"];
[Link]([Link]); //3

2. toString()

Nidhi Patel
Description: Converts an array into a comma-separated string.
example
let fruits = ["Apple", "Banana", "Mango"];
[Link]([Link]()); //

3. at()
Description: Returns the element at the specified index. It also supports negative indexes.
example
let fruits = ["Apple", "Banana", "Mango"];
[Link]([Link](1));
[Link]([Link](-1)); //Banana
//Mango

4. join()
Description: Joins all array elements into a string using a separator.
example
let fruits = ["Apple", "Banana", "Mango"];
[Link]([Link](" - ")); //Apple - Banana - Mango

5. pop()
Description: Removes the last element from the array.
example
let fruits = ["Apple", "Banana", "Mango"];
[Link]();
[Link](fruits); //["Apple", "Banana"]

6. push()
Description: Adds one or more elements to the end of the array.
example
let fruits = ["Apple", "Banana"];
[Link]("Mango");
[Link](fruits); //["Apple", "Banana", "Mango"]

7. shift()
Description: Removes the first element from the array.
example
let fruits = ["Apple", "Banana", "Mango"];
[Link]();
[Link](fruits); //["Banana", "Mango"]

8. unshift()
Description: Adds one or more elements to the beginning of the array.
example

Nidhi Patel
let fruits = ["Banana", "Mango"];
[Link]("Apple");
[Link](fruits); // ["Apple", "Banana", "Mango"]

9. [Link]()
Description: Checks whether the given value is an array.
example
let fruits = ["Apple", "Banana"];
[Link]([Link](fruits)); //true
[Link]([Link]("Hello")); //false

10. delete
Description: Deletes an array element but leaves an empty slot.
example
let fruits = ["Apple", "Banana", "Mango"];
delete fruits[1];
[Link](fruits);
[Link]([Link]); //["Apple", empty, "Mango"]
//3
11. concat()
Description: Combines two or more arrays into a new array.
example
let arr1 = ["Apple", "Banana"];
let arr2 = ["Mango", "Orange"];
let result = [Link](arr2);
[Link](result); //["Apple", "Banana", "Mango", "Orange"]

12. copyWithin()
Description: Copies part of the array to another location in the same array.
example
let numbers = [1, 2, 3, 4, 5];
[Link](0, 3);// (target, start, end)
[Link](numbers); //[4, 5, 3, 4, 5]

13. flat()
Description: Flattens nested arrays into a single array.
example
let numbers = [1, 2, [3, 4], [5, 6]];
[Link]([Link]()); //[1, 2, 3, 4, 5, 6]

14. slice()

Nidhi Patel
Description: Returns a selected part of an array without changing the original array.
example
let fruits = ["Apple", "Banana", "Mango", "Orange"];
let result = [Link](1, 3);
[Link](result); //["Banana", "Mango"]
[Link](fruits); //["Apple", "Banana", "Mango", "Orange"]

15. splice()
Description: Adds, removes, or replaces elements in the original array.
example
let fruits = ["Apple", "Banana", "Mango"];
[Link](1, 1, "Orange");//(start, deleteCount, item1,....)
[Link](fruits); //["Apple", "Orange", "Mango"]

16. toSpliced()
Description: Returns a new array with changes without modifying the original array.
example
let fruits = ["Apple", "Banana", "Mango"];
let newArray = [Link](1, 1, "Orange");
[Link](newArray);
[Link](fruits); //["Apple", "Orange", "Mango"]
//["Apple", "Banana", "Mango"]

Array Iteration

1. Using for Loop


// Create an array
const fruits = ["Banana", "Orange", "Apple", "Mango"];
// Get the length of the array
let fLen = [Link];
// Loop through the array
for (let i = 0; i < fLen; i++)
{
[Link](fruits[i] + "<br>");
}
/*Output:Banana
Orange
Apple
Mango*/

2. Using for...of Loop


// Create an array
const fruits = ["Banana", "Orange", "Apple", "Mango"];

Nidhi Patel
// Loop through each element
for (let fruit of fruits)
{
[Link](fruit + "<br>");
}
/*Output: Banana
Orange
Apple
Mango*/

3. Using forEach() Method


// Create an array
const fruits = ["Banana", "Orange", "Apple", "Mango"];
// Print each element
[Link](function(fruit)
{
[Link](fruit + "<br>");
});
/*Output: Banana
Orange
Apple
Mango*/

JSON

●​ JSON stands for JavaScript Object Notation.


●​ JSON is a plain text format for storing and transporting data.
●​ JSON is similar to the syntax for creating JavaScript objects.
●​ JSON is used to send, receive and store data.
●​ JSON is make it easy to send and store data between computers
●​ JSON is text only and language independent
●​ The syntax is derived from JavaScript object syntax, but JSON is text only.
●​ JavaScript has a built in function for converting JSON strings into JavaScript objects:
[Link]()
●​ JavaScript also has a built in function for converting an object into a JSON string:
[Link]()
●​ You can receive pure text from a server and use it as a JavaScript object.

Nidhi Patel
●​ You can send a JavaScript object to a server in pure text format.
●​ You can work with data as JavaScript objects, with no complicated parsing and
translations.

example
'{"name":"John", "age":30, "car":null}'
●​ Data is in name/value pairs
●​ Data is separated by commas
●​ Curly braces hold objects
●​ Square brackets hold arrays
●​ The file type for JSON files is ".json"

Data Types

In JSON, values must be one of the following data types:


●​ a string​​ ​ {"name":"John"}
●​ a number​ ​ {"age":30}
●​ an object (JSON object){"employee":{"name":"John", "age":30, "city":"New
York"}}
●​ an array​ ​ {"employees":["John", "Anna", "Peter"]}
●​ a boolean​ ​ {"sale":true}
●​ null​ ​ ​ {"middlename":null}

[Link]() & [Link]()

●​ A common use of JSON is to exchange data to/from a web server.


●​ When receiving data from a web server, the data is always a string.
●​ Parse the data with [Link](), and the data becomes a JavaScript object.
●​ you can convert any JavaScript datatype into a string with [Link]().

example of parse

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript JSON</h1>
<h2>Creating an Object from JSON</h2>
<p id="demo"></p>
<script>
const txt = '{"name":"John", "age":30, "city":"New York"}'
const myObj = [Link](txt);

Nidhi Patel
[Link]("demo").innerHTML = [Link] + ", " +
[Link];
//example of array
const text = '[ "Ford", "BMW", "Audi", "Fiat" ]';
const myArr = [Link](text);
[Link]("demo").innerHTML = myArr[0];
</script>
</body>
</html>

example of stringify

<!DOCTYPE html>
<html>
<body>
<h2>Store and retrieve data from local storage.</h2>
<p id="demo"></p>
<script>
// Storing data:
const myObj = { name: "John", age: 31, city: "New York" };
const myJSON = [Link](myObj);
[Link]("testJSON", myJSON);

// Retrieving data:
let text = [Link]("testJSON");
let obj = [Link](text);
[Link]("demo").innerHTML = [Link];
</script>
</body>
</html>

JSON From a Server

●​ You can request JSON from the server by using an AJAX request
●​ As long as the response from the server is written in JSON format, you can parse the
string into a JavaScript object.

example :-
<!DOCTYPE html>
<html>
<body>
<h2>Fetch a JSON file with XMLHttpRequest</h2>

Nidhi Patel
<p id="demo"></p>
<script>
const xmlhttp = new XMLHttpRequest();
[Link] = function() {
const myObj = [Link]([Link]);
[Link]("demo").innerHTML = [Link];
}
[Link]("GET", "json_demo.txt");
[Link]();
</script>
</body>
</html>

ES6 Features:
●​ Destructuring
●​ Spread/Rest
●​ Template Literal

Destructuring

●​ Destructuring is an ES6 feature in JavaScript that allows us to extract values from


arrays or properties from objects and assign them to variables in a single statement. It
makes the code shorter, cleaner, and easier to read. Destructuring is an ES6
(ECMAScript 2015) feature.
●​ It works with arrays and objects.
●​ It extracts multiple values in one statement.
●​ It reduces repetitive code.
●​ It improves code readability and maintainability.

[Link] of objects

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Objects</h1>
<h2>Object Destructuring</h2>
<p id="demo"></p>
<script>
// Create an Object
const person = {
firstName: "yashana",
lastName: "patel",
age: 50

Nidhi Patel
};
// Destructuring
let {firstName, lastName, country = "US"} = person;
// Display Primitive Values
[Link]("demo").innerHTML =
firstName + " " + lastName + " " + country;
</script>
</body>
</html>

2. example of String Destructuring

<p id="demo"></p>
<script>
let name = "goodbye";
// Destructuring
let [a1, a2, a3, a4, a5] = name;
// Display Value
[Link]("demo").innerHTML = a1;
</script>

3.​ example of Array Destructuring

<p id="demo"></p>
<script>
// Create an Array
const fruits = ["Bananas", "Oranges", "Apples", "Mangos"];
// Destructuring
let [fruit1, fruit2] = fruits;
//Skipping Array Values
let [fruit1, , , fruit2] = fruits;
// Display Primitive Values
[Link]("demo").innerHTML = fruit1 + " " + fruit2;
// Bananas Mangos
</script>

The Rest Property

The Rest Property collects all the remaining properties of an object that have not been
destructured and stores them in a new object.
It is represented by three dots (...)

Nidhi Patel
example

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>Array Destructuring</h2>
<p id="demo"></p>
<script>
// Create an Array
const numbers = [10, 20, 30, 40, 50, 60, 70];
// Destructuring
const [a,b, ...rest] = numbers;
// Display the Values
[Link]("demo").innerHTML =
"<p>a is " + a +
"<p>b is " + b +
"<p>the rest is " + rest;
</script>
</body>
</html>

Swapping JavaScript Variables

example

let firstName = "nidhi";


let lastName = "patel";
// Destructuring
[firstName, lastName] = [lastName, firstName];

The Spread ... Operator

The spread operator (...) in JavaScript provides a simple and expressive way to expand
elements from arrays, strings, or objects. It helps make code cleaner by reducing the need for
manual copying or looping. This operator is widely used for cloning, merging, and passing
values.
●​ It expands elements of arrays and strings or properties of objects into individual
values.
●​ Commonly used for copying and merging arrays or objects without mutating the
original data.
●​ Improves code readability and flexibility when passing arguments or creating new
data structures.

Nidhi Patel
example

const numbers = [1, 2, 3];


const copyNumbers = [...numbers];
[Link](copyNumbers); //[1,2,3]

1. Adding Multiple Elements Using Spread Operator

// expand using spread operator


let a = [10, 20];
let b = [...a, 30, 40];
[Link](a); //[10,20]
[Link](b); //[10,20,30,40]

2. Find Min / Max using Spread Operator

// Min in an array using [Link]()


let a = [1,2,3,-1];
[Link]([Link](a)); //NaN
// Now using spread
[Link]([Link](...a)); //-1

3. Passing Array Elements as Function Parameters

function add(x, y, z)
{
return x + y + z;
}
let a = [10, 20, 30];
[Link](add(...a)); //60

4.. Concatenate Arrays using Spread Operator

// Spread operator for array concatenation


let a = [1, 2, 3];
let b = [4, 5];

a = [...a, ...b];
[Link](a); //[1,2,3,4,5]

5. Working of Objects with Spread Operator

Nidhi Patel
const usr = {
name: 'Jen',
age: 22
};
const cloneUsr = { ...usr };
[Link](cloneUsr); //{"name":"Jen","age":22}

Template literals

Template literals are a modern way to create strings in JavaScript, introduced in ES6
(ECMAScript 2015). They are enclosed by backtick (`) characters instead of single or double
quotes, allowing you to embed variables, perform operations, and build multi-line strings
effortlessly.
1. Multi-line Strings

Template literals support multi-line strings without special characters. This example displays
a simple poem.

const poem = `Roses are red,


Violets are blue,
JavaScript is awesome,
And so are you!`;
[Link](poem);

2. Dynamic Expressions /Interpolation

Embedding arithmetic expressions within template literals. This example calculates the sum
dynamically.
Template Strings allow variables in strings.

const a = 5, b = 10;
const result = `Sum of ${a} and ${b} is ${a + b}.`;
[Link](result); //Sum of 5 and 10 is 15.

3. HTML Template

Template literals build HTML strings dynamically. This example creates an h1 element.

const title = "Welcome";


const html = `<h1>${title}</h1>`;
[Link](html);

Nidhi Patel
Asynchronous JavaScript
●​ Promises
●​ async/await

JavaScript runs one task at a time.

While one task is running, no other JavaScript code can run. If a task takes a long time, the
browser cannot respond to user actions until the task finishes.

Asynchronous programming solves this problem by allowing long-running operations to


complete in the background while JavaScript continues running other code.

Async :- Instead of waiting for one task to finish before starting the next, JavaScript can
continue running other code while waiting for an operation to complete.

By default, JavaScript runs code from top to bottom and left to right.

JavaScript Promises
JavaScript Promises make handling asynchronous operations like API calls, file loading, or
time delays easier. Think of a Promise as a placeholder for a value that will be available in
the future. It can be in one of three states

●​ Pending: The task is in the initial state.


●​ Fulfilled: The task was completed successfully, and the result is available.
●​ Rejected: The task failed, and an error was provided.

Creating a Promise
Syntax :-
let myPromise = new Promise(function(resolve, reject) {
// Code that may take some time
resolve(value); // when successful
reject(value); // when error
});
resolve :- function to run if finishes successfully
reject :- function to run if finishes with an error

.then(onFulfilled, onRejected):- The then() method runs when a Promise is fulfilled.

Nidhi Patel
.catch(onRejected) :-If a Promise is rejected, catch() handles the error.
.finally(onFinally) :- The finally() method runs whether the Promise succeeds or fails.

example

<!DOCTYPE html>
<html>
<head>
​ <meta charset="utf-8">
​ <meta name="viewport" content="width=device-width, initial-scale=1">
​ <title></title>
</head>
<body>
​ <script>

​ ​ let checkEven = new Promise((resolve, reject) => {

​ ​ let number = 4;

​ ​ if (number % 2 === 0)
​ ​ resolve("The number is even.");
​ ​ else
​ ​ reject("The given number is not an even number.");
​ ​ });

​ ​ checkEven
​ ​ .then((message) => {
​ ​ [Link](message);
​ ​ [Link](message);
​ ​ })
​ ​ .catch((error) => {
​ ​ [Link](error);
​ ​ [Link](error);
​ ​ });
​ </script>
</body>
</html>

Nidhi Patel
Promises and JavaScript APIs
●​ fetch()
●​ alert()
●​ setTimeout()

example-1:- fetch()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Promise</h1>
<h2>The fetch() Method</h2>
<p id="demo"></p>
<script>
fetch("[Link]")
.then(function(response) {
return [Link]();
})
.then(function(data) {
myDisplayer(data);
})
.catch(function(error) {
myDisplayer(error);
});
// Function to display any text
function myDisplayer(text) {
[Link]("demo").innerHTML = text;
}
</script>
</body>
</html>

Nidhi Patel
example -2 :- Promises
<p id="demo"></p>
<script>
// Create a Promise
let myPromise = new Promise(function(resolve, reject)
{
// Code that might take some time goes here
let success = true;
if (success)
{
resolve("Done");
} else
{
reject("Failed");
}
});
// Using the Promise
[Link](function(value)
{
myDisplayer(value)
},
function(value)
{
myDisplayer(value)
});
// Function to display any text
function myDisplayer(text)
{
[Link]("demo").innerHTML = text;
}

Nidhi Patel
</script>
</body>
</html>
<script>

example-3 :- alert()

let welcomePromise = new Promise(function(resolve, reject)


{
alert("Welcome Student!");
resolve("Student clicked OK");
});
[Link](function(message)
{
[Link](message);
});

example-3 :-setTimeout()

[Link]("Start");
setTimeout(function()
{
[Link]("Hello Student");
},3000);
[Link]("End");

JavaScript async and await


●​ The async and await keywords make Promise-based code easier to read.
●​ They let asynchronous code look much like ordinary synchronous code.
●​ Behind the scenes, async and await still use Promises.

The async Keyword


●​ The async keyword before a function makes the function return a promise.
●​ This is true even if you return a normal value.
●​ If the function returns a value, JavaScript automatically wraps that value in a Promise.

Nidhi Patel
The await Keyword
●​ The await keyword waits for a Promise to settle.
●​ It can only be used inside an async function or at the top level of a JavaScript module.
●​ While the async function is waiting, the rest of the program can continue running.
●​ The await keyword pauses only the current async function. It does not pause
JavaScript.
[Link]

Example :- async

<script>
// Function to display any text
function myDisplayer(text)
{
​ [Link]("demo").innerHTML = text;
}
// Create an async function
async function hello()
{
​ return "Hello World!"; (return [Link]("Hello World!");)
}
// Call the async function
hello().then(function(value)
{
​ myDisplayer(value);
});
</script>

Example :- await

<p id="demo"></p>
<script>
// Function to display any text
function myDisplayer(text)
{
​ [Link]("demo").innerHTML += text + "<br>";
}
myDisplayer("Start");
// Create an async function
async function getData()
{

Nidhi Patel
await fetch("[Link]");
myDisplayer("Done");
}
// Call the async function
getData();
myDisplayer("Continue");
</script>

DOM Manipulation & Event Handling

1. Internal JavaScript
●​ Internal JavaScript is JavaScript code written inside the HTML file using the <script>
tag. It is used when the script is needed only for a single web page.
Syntax:
​ <script>
​ ​ // JavaScript code
</script>

2. External JavaScript
●​ External JavaScript is JavaScript code written in a separate file with the .js extension.
The file is linked to the HTML page using the <script src="..."></script> tag. This
method is suitable for large projects because the same JavaScript file can be reused on
multiple web pages.
Syntax:

Nidhi Patel
<script src="[Link]"></script>
3. Inline JavaScript
●​ Inline JavaScript is JavaScript code written directly inside an HTML element using
event attributes such as onclick, onmouseover, or onchange. It is mainly used for
simple and short tasks.

Practical list
P1- Write a script demonstrating variable declarations (var, let, const), data types, and
simple arithmetic operations.

P2- Create functions to calculate factorial


function factorial(n)
{
if (n < 0)
{
return "Factorial is not defined for negative numbers";
​ }
let result = 1;
for (let i = 1; i <= n; i++)
{
​ result = result * i;
}
return result;
}
[Link](factorial(5)); // 120
//OR
let ans1 = factorial(5);
[Link](ans1);

P3- Create Arrow Functions to calculate factorial


const factorialLoop = (n) =>
{
let result = 1;
for (let i = 2; i <= n; i++)
{
​ result = result * i;
}

Nidhi Patel
return result;
};
[Link](factorialLoop(5)); // Output: 120

example :- Recursive Function to Calculate Factorial

function factorial(n)
{
// Base case
if (n === 0 || n === 1)
{
return 1;
}
// Recursive case
return n * factorial(n - 1);
}
[Link](factorial(5));

P4- Write a JavaScript Program to Generate the Fibonacci Series Using a Loop.

The Fibonacci sequence is the integer sequence where the first two terms are 0
and 1. After that, the next term is defined as the sum of the previous two
terms.
​ ​ ​ function fibonacci(n)
{
let first = 0;
let second = 1;
​ ​ ​ ​ for (let i = 1; i <= n; i++)
{
[Link](first);

Nidhi Patel
let next = first + second;
​ ​ ​ ​ ​ first = second;
​ ​ ​ ​ ​ second = next;
}
}
fibonacci(10);

example -1 :- Fibonacci Using Recursion

​ ​ fib(6)=8
/ \
fib(5)=5 fib(4)=3
/ \ / \
fib(4)=3 fib(3)=2 fib(3)=2 fib(2)=1
/ \ / \ / \ / \
fib(3)=2 fib(2)=1 1 1 1 1 1 0
/ \
fib(2)=1 1
/ \
1 0

function fibonacci(n)
{
​ ​ if (n == 0)
​ ​ {
return 0;
​ ​ }

Nidhi Patel
​ ​ if (n == 1)
​ ​ {
​ ​ ​ return 1;
​ ​ }
​ return fibonacci(n - 1) + fibonacci(n - 2);
}
[Link](fibonacci(6));

P5- Create Object Literals and Implement a Student Record System to Perform Add,
Update, Delete, and Search Operations.
<!DOCTYPE html>
<html>
<head>
<title>Student Object Example</title>
</head>
<body>

<script>

// =========================================
// Step 1 : Create Object Literal
// =========================================

let student = {};

[Link]("<h3>Step 1 : Empty Student Object</h3>");


[Link]("Student Object Created.<br><br>");

// =========================================
// Step 2 : Add Student Details
// =========================================

[Link] = 101;
[Link] = "Rahul";
[Link] = 20;
[Link] = "BCA";

[Link]("<h3>Step 2 : Add Student Details</h3>");


[Link]("ID : " + [Link] + "<br>");
[Link]("Name : " + [Link] + "<br>");
[Link]("Age : " + [Link] + "<br>");
[Link]("Course : " + [Link] + "<br><br>");

Nidhi Patel
// =========================================
// Step 3 : Update Student Details
// =========================================

[Link] = 21;

[Link]("<h3>Step 3 : Update Student Age</h3>");


[Link]("Updated Age : " + [Link] + "<br><br>");

// =========================================
// Step 4 : Search Student
// =========================================

[Link]("<h3>Step 4 : Search Student</h3>");

if([Link] == "Rahul")
{
[Link]("Student Found<br>");
[Link]("Name : " + [Link] + "<br>");
}
else
{
[Link]("Student Not Found<br>");
}

[Link]("<br>");

// =========================================
// Step 5 : Delete Student Course
// =========================================

delete [Link];

[Link]("<h3>Step 5 : Delete Course</h3>");


[Link]("ID : " + [Link] + "<br>");
[Link]("Name : " + [Link] + "<br>");
[Link]("Age : " + [Link] + "<br>");
[Link]("Course : " + [Link] + "<br>");

</script>

</body>

Nidhi Patel
</html>

P6- Create Arrays and Implement a Student Record System to Perform Add, Update,
Delete, and Search Operations.

P7- Implement a Student Record System and Convert JavaScript Objects to JSON and
JSON to JavaScript Objects.

4 Destructuring & Spread/Rest

Write code snippets demonstrating array and object destructuring, and use of spread/rest
operators in functions.

5 Asynchronous JS: Promises and async/await

Build a simple app that fetches data from a public API (like JSON Placeholder) using both
Promises and async/await.

6 DOM Manipulation and Events

Create a dynamic form (e.g., registration form) that validates user input in real-time using
DOM methods and

Nidhi Patel

You might also like