[Go to site: main page, start]

0% found this document useful (0 votes)
8 views265 pages

JavaScript Notes

JavaScript is a lightweight, interpreted, and JIT-compiled programming language that supports various programming paradigms including structural, imperative, functional, and object-oriented programming. It is widely used for client-side and server-side applications, with integration techniques such as inline, embedded, and external file scripts. Despite its flexibility, JavaScript has issues such as being weakly typed and lacking strong object-oriented features, which can be mitigated by using TypeScript.

Uploaded by

bsrassignment
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views265 pages

JavaScript Notes

JavaScript is a lightweight, interpreted, and JIT-compiled programming language that supports various programming paradigms including structural, imperative, functional, and object-oriented programming. It is widely used for client-side and server-side applications, with integration techniques such as inline, embedded, and external file scripts. Despite its flexibility, JavaScript has issues such as being weakly typed and lacking strong object-oriented features, which can be mitigated by using TypeScript.

Uploaded by

bsrassignment
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JavaScript

- JavaScript is light weight interpreted and JIT compiled programming


language.

- Light weight allows to run on device or in environment with less memory.

- Interpreted allows line by line translation.

- Compiled allows translation of all lines simultaneously at the same time.

- There are 2 types of compiling techniques

a) JIT

b) AOT

- JIT is "Just-in-Time", which compiles the code only when it is requested.

- AOT is "Ahead-of-Time", which compiles the code at application level


before it is requested.

- JavaScript is a language that supports various programming techniques


and approaches like

a) Structural Programming

b) Imperative Programming

c) Functional Programming

d) Object Oriented Programming etc..

Note: JavaScript is not an OOP language. It supports only few features of


OOP.

- JavaScript have various application areas, it is used

a) Client Side HTML

b) Server Side Node JS

c) Database MongoDB

d) Animation Tools CAD, Flash 2D, 3D etc..


FAQ: What is the purpose of JavaScript client side?

Ans : A client side script is used to reduce burden on server.

It saves round trips.

FAQ: What are the activities managed by JavaScript client side?

Ans:

1. Browser Interactions [BOM]

- window

- location

- navigator

- history

- document

2. DOM Manipulations

- Adding elements

- Removing elements

- Databinding

- Style Binding

- Class Binding

- Event Binding

3. Client side Validations

- Verifying user input

- Restricting contradictory values

- Authorizing values etc..

Evolution of JavaScript:

- CERN labs introduced ECMA Script, which is known as the base for all
scripts in the world.

- Internet started with a browser called Mosaic, which uses ECMA script &
HTML.
- Netscape communications started a browser called Netscape
Communicator in 1995.

- Netscape appointed "Brendan Eich" to develop a script for their browser.

- He designed a script by name "Moca", later renamed as "Live Script".

- Netscape given the responsibility of Live Script to Sun Micro Systems.


[Java]

- Sun Micro Systems and Netscape together name the script as


"JavaScript".

- In 2000 Netscape stopped its services and given the responsibility of


JavaScript to ECMA.

- Latest version of JavaScript is ESNext [Alpha], the stable and standard


versions used in companies

ECMA 2015 ES5

ECMA 2016 ES6

ECMA 2022

Issues with JavaScript:

Class comments

Skip to main content

Google Classroom

Classroom

FullStack Web With React


7:30 PM - April 2024

JavaScript IntegrationJavaScript Integration

JavaScript Integration

Sudhakar Sharma

11 Jun

Issues with JavaScript:

- JavaScript is not strongly typed.

- No restriction for type of data to store in a reference.

x = 10; x is number

x = "A"; x changes to string

x = true; x changes to Boolean

- You need lot of validations to restrict a value type.

- JavaScript is not implicitly strictly typed.

- It allows to write without following the rules of programming.

- It leads to lot of code inconsistency.

- It is not an OOP language.

- It is not easy to extend.

- It is not good in code level security.

Solution:

- TypeScript

- It is just an alternative for JavaScript and not replacement.

- Browser can understand only JavaScript and not TypeScript.

Various Integration Techniques:

1. Inline

2. Embedded
3. External File

Inline Script:

- In this technique JavaScript functions are configured directly in the


element.

- It is faster.

- It is not good for reusing the functions across elements.

Syntax:

<button Print </button>

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

</head>

<body>

<h2>Ticket</h2>

<button >

</body>

</html>

Embedded Script:

- In this technique the JavaScript functions are configured in a <script>


container.

- You can embed script in head or body.


- Configure a function in script container

function Name()

- Access the function from any element and reuse across multiple
requests.

<button </button>

- JavaScript MIME type is "text/javascript" for interpreter.

- JavaScript MIME can be "text/babel" for external compiler like "babel".

- JavaScript MIME can be "text/module" when it is using a module system.

Syntax:

<script type="text/javascript"> // new

<script language="javascript"> // old

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script type="text/javascript">

function PrintPage(){

[Link]();
}

</script>

</head>

<body>

<h2>Ticket</h2>

<button >

</body>

</html>

3. JavaScript in External File

- You can write JavaScript functions in external script file.

- Script file have extension ".js"

- You can link the script file to HTML page by using <script> container.

- You can reuse the functions across pages.

- Using an external file will increase the number of requests for page and
also the page load time.

Ex:

1. Go to "src/scripts" folder

2. Add a new file "[Link]"

function PrintPage()

[Link]();

3. Link to HTML page

<script src="../src/scripts/[Link]" type="text/javascript"> </script>


<button Print </button>

- The production files are created by using "Minification".

<script src="../src/scripts/[Link]" type="text/javascript">


</script>

[Link]

- You can turn on Strict mode for developers by using the statement

"use strict";

Syntax:

<script>

x = 10; // valid

[Link]("x=" + x );

</script>

<script>

"use strict";

x = 10; // invalid - x is not defined

[Link]("x=" + x);

</script>

- To add rules for programming in JavaScript you can setup "ESLint" in


project.

- It is language analysis tool, used to find and fix problems of JavaScript.

- It is also used to configure JavaScript for a project.

- Configure ESLint for project


> npm init @eslint/config@latest

- JavaScript functions are not suitable for legacy browsers, if written using
new syntax. Hence we can target JavaScript for legacy browsers by
enclose JavaScript functions in HTML comments.

Syntax:

<script>

<!--

// functions

-->

</script>

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script type="text/javascript">

<!--

function PrintPage(){

[Link]();

-->

</script>

</head>
<body>

<h1>Ticket</h1>

<button >

</body>

</html>

Class comments

Skip to main content

Google Classroom

Classroom

FullStack Web With React

7:30 PM - April 2024

JavaScript Reference TechniquesJavaScript Reference Techniques

JavaScript Reference Techniques

Sudhakar Sharma

12 Jun

- Inline

- Embedded

- External File

- Strongly Typed

- Strictly Typed

- "use strict";

- MIME Type

- Minification

- Code for Legacy Browsers


<!-- -->

Various JavaScript reference techniques to access HTML elements:

1. JavaScript can refer HTML elements in page by using DOM hierarchy.

- It is the native method used by browser.

- It is faster.

- Referring to index number in DOM requires change of index in code


every time when element position changes in UI.

Syntax:

[Link][]

[Link][].elements[]

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script type="text/javascript">

function bodyload(){

[Link][0].src = "../public/images/women-
[Link]";

[Link][0].elements[2].value = "Login";

[Link][1].elements[2].value = "Register";

</script>
</head>

<body >

<div><img width="200" height="200" border="1"></div>

<div>

<form>

<h2>User Login</h2>

<dl>

<dt>User Name</dt>

<dd><input type="text"></dd>

<dt>Password</dt>

<dd><input type="password"></dd>

</dl>

<input type="button">

</form>

</div>

<div>

<form>

<h2>Register User</h2>

<dl>

<dt>Email</dt>

<dd><input type="email"></dd>

<dt>Mobile</dt>

<dd><input type="text"></dd>

</dl>

<input type="button">

</form>

</div>

</body>

</html>
2. JavaScript can refer elements by using "name"

- Every HTML element can have a reference name in UI.

- JavaScript can use the reference name to access element.

- You can't refer a child element directly with name. It is always required
to access child through the parent.

Syntax:

<div> <img name="poster"> </div>

[Link] = "path";

<form name="frm">

<input type="button" name="btn">

</form>

[Link] = "Login"; // invalid

[Link]="Login"; // valid

- "name" attribute can have same value for multiple elements. JavaScript
fails in this scenario.

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>
<script type="text/javascript">

function bodyload(){

[Link] = "../public/images/[Link]";

[Link] = "Login";

[Link] = "Register";

</script>

</head>

<body >

<div><img width="200" name="poster" height="200"


border="1"></div>

<div>

<form name="frmLogin">

<h2>User Login</h2>

<dl>

<dt>User Name</dt>

<dd><input type="text"></dd>

<dt>Password</dt>

<dd><input type="password"></dd>

</dl>

<input name="btnLogin" type="button">

</form>

</div>

<div>

<form name="frmRegister">

<h2>Register User</h2>

<dl>

<dt>Email</dt>

<dd><input type="email"></dd>
<dt>Mobile</dt>

<dd><input type="text"></dd>

</dl>

<input type="button" name="btnRegister">

</form>

</div>

</body>

</html>

3. JavaScript can refer HTML elements by using ID reference

- Every HTML element can have a reference "id".

- "id" is used to define a unique reference for elements in page.

- You can access elements directly from any level of hierarchy.

- It used the document method "getElementById()"

Syntax:

<img id="poster">

[Link]("poster").src = "path";

- "id" is a reference used by CSS in page, where same "id" can be used for
multiple elements, JavaScript fails again in this scenario.

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">
<title>Document</title>

<script type="text/javascript">

function bodyload(){

[Link]("poster").src= "../public/images/kids-
[Link]";

[Link]("btnLogin").value = "Login";

[Link]("btnRegister").value = "Register";

</script>

</head>

<body >

<div><img width="200" id="poster" height="200"


border="1"></div>

<div>

<form name="frmLogin">

<h2>User Login</h2>

<dl>

<dt>User Name</dt>

<dd><input type="text"></dd>

<dt>Password</dt>

<dd><input type="password"></dd>

</dl>

<input id="btnLogin" type="button">

</form>

</div>

<div>

<form name="frmRegister">

<h2>Register User</h2>

<dl>

<dt>Email</dt>
<dd><input type="email"></dd>

<dt>Mobile</dt>

<dd><input type="text"></dd>

</dl>

<input type="button" id="btnRegister">

</form>

</div>

</body>

</html>

4. JavaScript can use CSS selectors to refer elements

- CSS provides various selectors like type, id, class, rational, etc..

- JavaScript document object can use "querySelector()" method to access


elements using CSS references.

Syntax:

<img>

<input type="button" id="btnLogin">

<input type="button" class="btn-primary">

[Link]("img").src = "path"; => type selector

[Link]("#btnLogin").value = " "; => id selector

[Link](".btn-primary").value = " "; => class


selector

[Link]("nav span");

[Link]("div>p");

Ex:
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script type="text/javascript">

function bodyload(){

[Link]("img").src = "../public/images/[Link]";

[Link]("#btnLogin").value = "Login";

[Link](".btn-primary").value = "Register";

</script>

</head>

<body >

<div><img width="200" height="200" border="1"></div>

<div>

<form name="frmLogin">

<h2>User Login</h2>

<dl>

<dt>User Name</dt>

<dd><input type="text"></dd>

<dt>Password</dt>

<dd><input type="password"></dd>

</dl>

<input id="btnLogin" type="button">

</form>

</div>
<div>

<form name="frmRegister">

<h2>Register User</h2>

<dl>

<dt>Email</dt>

<dd><input type="email"></dd>

<dt>Mobile</dt>

<dd><input type="text"></dd>

</dl>

<input type="button" class="btn-primary">

</form>

</div>

</body>

</html>

Note: JavaScript provides various other methods to access multiple


elements simultaneously at the same time.

[Link]()

[Link]()

[Link]()

etc...

JavaScript Output Techniques

- In computer programming "output" is the concept of rendering result to


console or GUI.

- JavaScript provides various output properties and methods

1. alert()
2. confirm()

3. [Link]()

4. innerText

5. innerHTML

6. outerHTML

7. console methods

log()

warn()

error()

debug()

info() etc..

alert():

- It is popup message box provided by browser.

- It renders the output in browser window as a dialog.

- It is an RC type dialog.

- It will not allow backdrop.

- You have to confirm only with OK.

- There is no cancel.

Syntax:

alert("message / expression");

alert("Welcome");

alert(20+30);

alert("Addition" + (20+30));

alert("line-1 \n line-2"); \n for line break.

Ex:

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script type="text/javascript">

function DeleteClick(){

alert("Delete Record\nRecord Deleted Successfully");

</script>

</head>

<body>

<button >

</body>

</html>

confirm():

- It is similar to alert but allows to cancel.

- It is a Boolean type method.

- It returns

true => on OK click

false => on Cancel click

EX:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">

<title>Document</title>

<script type="text/javascript">

function DeleteClick(){

result = confirm("Delete Record\nAre you sure?");

if(result==true)

alert("Deleted..");

else

alert("You canceled..");

</script>

</head>

<body>

<button >

</body>

</html>

Class comments
Skip to main content

Google Classroom

Classroom

FullStack Web With React

7:30 PM - April 2024

Output and Input TechniquesOutput and Input Techniques

Output and Input Techniques

Sudhakar Sharma

13 Jun

Output

- alert()

- confirm()

3. [Link]()

- It prints output on a new screen of same page.

- It supports complex string formats & markup.

Syntax:

[Link]("value / expression / markup");

Ex:

<!DOCTYPE html>

<html lang="en">

<head>
<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script type="text/javascript">

function DeleteClick(){

result = confirm("Delete Record\nAre you sure?");

if(result==true)

[Link]("<h2><font color='red'>Record Deleted


Successfully..</font></h2><a href='[Link]'>Back</a>");

else

alert("You canceled..");

</script>

</head>

<body>

<button >

</body>

</html>

4. innerText

- It can display output in any HTML container.

- You can use a semantic or non-semantic container that support text


display.

- You can't display complex formats for text.

- It can display plain text content [alpha numeric and special chars].
Syntax:

<div id="msg"> </div>

[Link]("msg").innerText = "msg";

5. innerHTML

- It is similar to innerText but supports complex text formats using markup.

Syntax:

[Link]("msg").innerHTML = "<b> Msg </b>";

- It can add new elements into the specified parent container.

6. outerHTML

- It can replace the parent container with new elements.

Syntax:

[Link]("p").outerHTML = "<h2> Msg </h2>";

7. console methods [contextual]

log()

error()

info()

debug()

warn()
- Developer use console as command line terminal for testing functions
and tracking performance of actions.

- Developer can log various results into console by using contextual


methods.

- It is recommended only for design and testing, not for production.

- All console methods are RC type.

Syntax:

[Link]("string | expression");

[Link]()

[Link]()

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script type="text/javascript">

function DeleteClick(){

[Link]("Delete button clicked");

result = confirm("Delete Record\nAre you sure?");

if(result==true)

[Link](".msg").outerHTML =
"<h3>Deleted..</h3>";

[Link]("OK clicked");
}

else

alert("You canceled..");

[Link]("Cancel Clicked");

</script>

</head>

<body>

<button >

<p class="msg"></p>

</body>

</html>

JavaScript Input Techniques

1. QueryString

- User can input from address bar of browser.

- The values from address bar are allowed as Query String.

- Query String comprises of Key and value.

- Query String is appended to page in address bar using "?"

Syntax:

[Link]

- You can access query string using "[Link]", which is browser


object property.

[Link]; => ?key=value


- You need various string handling methods to extract only value from
query string.

indexOf() It returns the index number of character in a string.

slice() It extracts the chars between specified index.

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script>

function bodyload(){

querystring = [Link];

equalPosition = [Link]("=");

val = [Link](equalPosition+1);

[Link]("p").innerHTML = "Searching For :" +


val;

</script>

</head>

<body >

<p></p>

</body>

</html>
Input from URL:

[Link]

Syntax:

[Link]("p").innerHTML = "Searching For :" +


[Link]([Link]("=")+1);

2. prompt()

- It is an input box provided by browser window object.

- It allows user to input a value dynamically.

Syntax:

prompt("Message", "Default_Value_optional");

- Prompt returns values results

null : on cancel click

"" : on ok without value

"value" : on ok with value

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>
<link rel="stylesheet"
href="../node_modules/bootstrap-icons/font/[Link]">

<script>

function SearchClick(){

result = prompt("Enter Search String");

if(result=="")

alert("Search string can't be empty");

else if(result==null)

alert("Search Canceled");

else {

[Link]("p").innerHTML = "Searching For: " +


result;

</script>

</head>

<body>

<button class="bi bi-search" >

<p></p>

</body>

</html>

Class comments
Skip to main content

Google Classroom

Classroom

FullStack Web With React

7:30 PM - April 2024

JavaScript Form InputJavaScript Form Input

JavaScript Form Input

Sudhakar Sharma

14 Jun

JavaScript Input

Query String

prompt()

3. Form Input Elements

- You can use form elements to input a value.

- The input elements include textbox, checkbox , radio, dropdown,


number, range etc.

- Form elements accept a "value" as input, which you can access and use
in application.

Syntax:

<input type="text" id="UserName">

<input type="password" id="Password">

<select id="Cities">

<input type="checkbox" id="Stock"> <label> Available </label>


<button> Insert </button>

[Link]("UserName").value => textbox value

[Link]("Cities").value => select - option


value

[Link]("Stock").value => ON

[Link]("Stock").checked => true / false

[Link]("button").innerHTML => Insert

Ex: Inox

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Inox</title>

<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/[Link]">

<link rel="stylesheet"
href="../node_modules/bootstrap-icons/font/[Link]">

<script
src="../node_modules/bootstrap/dist/js/[Link]"></script>

<script type="text/javascript">

function BookClick(){

[Link]("btnContainer").[Link] = "none";

[Link]("summaryContainer").[Link] =
"block";
[Link]("lblMovie").innerHTML =
[Link]("lstMovies").value;

[Link]("lblCinema").innerHTML =
[Link]("lstCinema").value;

[Link]("lblDate").innerHTML =
[Link]("lstDate").value;

[Link]("lblTime").innerHTML =
[Link]("lstTiming").value;

poster = [Link]("imgPoster");

movie = [Link]("lstMovies").value;

if(movie=="CHANDU CHAMPION")

[Link] = "../public/images/[Link]";

else

[Link] = "../public/images/[Link]";

function ModifyClick(){

[Link]("title").innerHTML = "Modify Booking";

[Link]("btnBook").innerHTML = "Update";

[Link]("btnBook").className = "btn btn-


success";

</script>

</head>
<body class="container-fluid">

<div id="btnContainer">

<button data-bs-target="#booking" data-bs-toggle="modal"


class="btn btn-primary mt-3">Quick Booking</button>

</div>

<div id="summaryContainer" class="w-50 mt-3" style="display:


none;">

<div class="bg-dark text-white p-2 d-flex justify-content-between">

<span class="fs-6">Booking Summary</span>

<span class="bi bi-ticket-fill"></span>

</div>

<div class="row my-3">

<div class="col-3">

<img height="200" width="100%" border="1" id="imgPoster">

</div>

<div class="col-9">

<dl class="row">

<dt class="col-3">Movie</dt>

<dd class="col-9" id="lblMovie"></dd>

<dt class="col-3">Date</dt>

<dd class="col-9" id="lblDate"></dd>

<dt class="col-3">Cinema</dt>

<dd class="col-9" id="lblCinema"></dd>

<dt class="col-3">Show Time</dt>

<dd class="col-9" id="lblTime"></dd>

</dl>

</div>

</div>
<button data-bs-target="#booking" data-bs-
toggle="modal" class="btn btn-warning bi bi-pen-fill">Modify
Booking</button>

<a href="./[Link]" class="btn btn-danger">Cancel


Booking</a>

</div>

<div class="modal fade" id="booking">

<div class="modal-dialog modal-fullscreen">

<div class="modal-content">

<div class="modal-header">

<h2 id="title">Quick Booking</h2>

<button class="btn btn-close"


data-bs-dismiss="modal"></button>

</div>

<div class="modal-body">

<div class="d-flex justify-content-between bg-dark text-white


p-2">

<div>

<select class="form-select" id="lstMovies">

<option>Select Movie</option>

<option>CHANDU CHAMPION</option>

<option>INSIDE OUT 2</option>

</select>

</div>

<div>

<select class="form-select" id="lstDate">

<option>Select Date</option>

<option>Today, 14 Jun</option>

<option>Tomorrow, 15 Jun</option>

</select>
</div>

<div>

<select class="form-select" id="lstCinema">

<option>Select Cinema</option>

<option>PVR Next Galleria </option>

<option>PVR Panjagutta Hyderabad</option>

</select>

</div>

<div>

<select class="form-select" id="lstTiming">

<option>Select Timing</option>

<option>07:50 PM</option>

<option>10:20 PM</option>

</select>

</div>

<div>

<button id="btnBook" class="btn


btn-danger" data-bs-dismiss="modal">Book</button>

</div>

</div>

</div>

</div>

</div>

</div>

</body>

</html>

Class comments
Skip to main content

Google Classroom

Classroom

FullStack Web With React

7:30 PM - April 2024

JavaScript LanguageJavaScript Language

JavaScript Language

Sudhakar Sharma

15 Jun

Form Input Elements

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">
<title>Document</title>

<link rel="stylesheet"
href="../node_modules/bootstrap-icons/font/[Link]">

<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/[Link]">

<script
src="../node_modules/bootstrap/dist/js/[Link]"></script>

<script type="text/javascript">

function SubmitClick(){

[Link]("lblId").innerHTML =
[Link]("txtId").value;

[Link]("lblName").innerHTML =
[Link]("txtName").value;

[Link]("lblPrice").innerHTML =
[Link]("txtPrice").value;

[Link]("lblCity").innerHTML =
[Link]("lstCities").value;

stock = "";

stockCheckBox = [Link]("optStock");

if([Link])

stock = "Available";

else

stock = "Out of Stock";

[Link]("lblStock").innerHTML = stock;
}

</script>

</head>

<body class="container-fluid">

<div id="registerContainer">

<h2>Register Product</h2>

<dl class="w-25">

<dt>Product Id</dt>

<dd><input type="number" id="txtId"


class="form-control"></dd>

<dt>Name</dt>

<dd><input type="text" id="txtName"


class="form-control"></dd>

<dt>Price</dt>

<dd><input type="number" id="txtPrice" class="form-


control"></dd>

<dt>Shipped To</dt>

<dd>

<select id="lstCities" class="form-select">

<option>Select City</option>

<option>Delhi</option>

<option>Hyd</option>

</select>

</dd>

<dt>Stock</dt>

<dd class="form-switch">

<input type="checkbox" id="optStock" class="form-check-


input"> <label> Available </label>

</dd>

<button data-bs-toggle="modal" data-bs-


target="#details" class="btn btn-primary w-100">Submit</button>
</dl>

</div>

<div class="modal fade" id="details">

<div class="modal-dialog">

<div class="modal-content">

<div class="modal-header">

<h2>Product Details</h2>

</div>

<div class="modal-body">

<dl>

<dt>Product Id</dt>

<dd id="lblId"></dd>

<dt>Name</dt>

<dd id="lblName"></dd>

<dt>Price</dt>

<dd id="lblPrice"></dd>

<dt>Shipping City</dt>

<dd id="lblCity"></dd>

<dt>Stock</dt>

<dd id="lblStock"></dd>

</dl>

</div>

<div class="modal-footer">

<button class="btn btn-primary" data-bs-dismiss="modal">


OK </button>

</div>

</div>

</div>

</div>
</body>

</html>

JavaScript Language

1. Variables

2. Data Types

3. Operators

4. Statements

5. Functions

6. OOP

Variables

- Variables are storage locations in memory where you can store a value
and use it as a part of any expression.

- Variable uses a temporary memory, which can vary its value according
to state and situation.

- Variable have same reference name but varying values.

- Variable configuration have 3 phases

a) Declaration

b) Assignment

c) Initialization

- Declaration comprises of specification about behaviour, scope and


reference name.

- If JavaScript is not in strict mode, then declaration is not mandatory.

- If JavaScript is in strict mode, then you have to declare a variable by


using the keywords:

a) var
b) let

c) const

Syntax:

var x; // declaring

let price; // declaring

- Assignment is the process of storing a value into variable reference after


declaring.

var x; // declaring

x = 10; // assigning

x = 20; // assigning

- Initialization is the process of storing a value into variable reference


while declaring a variable.

var x = 10; // initialization

x = 20; // assignment

FAQ: What is difference between var, let & const?

var

- It configures a function scope variable.

- A function scope variable can be declared in any block of a function and


can be accessed from any another block inside function.

- It allows declaring, initialization and assignment.

Ex:

<script>
function f1()

var x; // declaring

x = 10; // assignment

if(x==10)

var y = 20; // initialization

[Link]("x=" + x + "<br>" + "y=" + y);

f1();

</script>

- It allows shadowing.

- Shadowing is the process of re-declaring or re-initializing same name


identifier within the scope.

var x = 10; // initialization

x = 20; // assignment

var x = 30; // shadowing

- It allows hoisting.

- It is a mechanism of configuring the declaration of variable at any


location in function, there is no order dependency in declaring and using a
variable.

- It allows to use and later declare or initialize.

Ex:

<script>

"use strict";
function f1()

x = 10;

[Link]("x=" + x);

var x; //hoisting

f1();

</script>

let:

- It configures a block scope variable.

- It is accessible only in the block where it is declared and its inner blocks.

- It supports declaring, assignment and initialization.

- It will not support shadowing & hoisting.

Class comments

Skip to main content

Google Classroom

Classroom
FullStack Web With React

7:30 PM - April 2024

JavaScript VariablesJavaScript Variables

JavaScript Variables

Sudhakar Sharma

17 Jun

Variables

- Configuration

- Keywords

a) var

b) let

c) const

const:

- It is a block scope constant.

- It allows only initialization.

- It will not allow declaring and assigning.

const x; // invalid

x = 10; // invalid

const x = 10; // valid

x =20; // invalid

- It will not support shadowing and hoisting.

Global Scope:
- A global scope allows access from any function in a module.

- You can declare or initialize values in global scope. So that you can
access from various function or components.

- You can declare or initialize global variables using var, let or const.

Ex:

<script>

// module scope

let x = 10;

var y = 20;

const z = 30;

function f1() {

[Link]("F1 x=" + x + "y=" + y + "z=" + z + "<br>");

function f2(){

[Link]("F2 x=" + x + "y=" + y + "z=" + z + "<br>");

f1();

f2();

</script>

- You can configure a variable inside function and make it global by using
"window" reference. But it is possible for JavaScript only when it is used in
browser.

[window is a browser object]

Ex:

<script>

"use strict";

// module scope
let x = 10;

var y = 20;

function f1() {

window.z = 40;

[Link]("F1 x=" + x + "y=" + y + "z=" + z + "<br>");

function f2(){

[Link]("F2 x=" + x + "y=" + y + "z=" + z + "<br>");

f1();

f2();

</script>

Naming Rules:

- Variable name must start with an alphabet.

- It can start with underscore "_" but not recommended.

- It can be alpha numeric but can't start with number.

- Don't use special chars in variable name.

- It can max 255 chars long.

- It can't be a keyword.

var class; // invalid

var class2; // valid

var Class; // valid

- It must speak what it is.

FAQ's:
1. var x, y, z; is it a valid syntax?

A. Yes.

2. var x = 10, y, z; what is the value of y & z?

A. undefined

3. const x, y, z=20; is it valid?

A. No. x & y are not initialized.

4. var x = y = z = 20; is it valid?

A. Yes if it is not in strict mode.

5. What is difference between

A.

var x, y, z; // declaring 3 individual variables

var [x,y,z]; // declaring one collection with 3 references

6. What is result of given

var [x, y, z] = 20; // invalid 20 is not an iterator.

7. What is result of given

var [x,y,z] = [20]; // x = 20, y=undefined, z=undefined

8. What is the result of given

var [x, y] = [20, 30, 50]; // valid in JavaScript x=20, y=30


JavaScript Data Types

- In computer programming data type defines the data structure.

- Data type refers to the structure of data in memory.

- Data structure comprises of variable details about data, which include

a) type

b) range

c) behaviour etc..

- JavaScript is a not a strongly typed language.

- JavaScript is implicitly typed or dynamic typed.

- The data type will be determined according to the value assigned.

var x = 10; x is number

x= "A"; x is string

x= true; x is Boolean

- JavaScript types are classified into 2 groups

1. Primitive Data Types

2. Non Primitive Data Types

Class comments
Skip to main content

Google Classroom

Classroom

FullStack Web With React

7:30 PM - April 2024

Primitive Data TypesPrimitive Data Types

Primitive Data Types

Sudhakar Sharma

18 Jun

Primitive Types

- Primitive types are immutable types.

- They have a fixed data structure, which can't change dynamically.

- They also have a fixed range for values.

- They are stored in memory stack.

- Stack uses LIFO [Last-in First-out].

- JavaScript primitive types are

1. number

2. string

3. boolean

4. null

5. undefined

6. symbol

7. bigint
Number

- Number in JavaScript represents a numeric value, which can be any one


of the following.

Signed Integer -30

Unsigned Integer 30

Floating Point 30.45

Double 240.45

Decimal 35000.44 [29 places]

Exponent 2e3 [2000] 2 x 10^3

Hexadecimal 0x7682

Binary 0b1010 [10]

Octa 0o745

Bigint 98388118484n

- JavaScript allows numeric strings in various calculations.

- But a numeric string must be converted into number by using the


methods

a) parseInt()

b) parseFloat()

- A numeric string must start with number and enclosed in quotes.

- It can have number with chars, but it reads only up to the numeric
occurrence in a string.

var x = "10AB";

var y = 20;
parseInt(x) + y => 30

var x = "10AB20";

var y = 30;

parseInt(x) + y => 40

var x = "20";

var y = 20;

x + y; = 2020

parseInt(x) + y = 40

EX:

<script>

var age = parseInt(prompt("Enter Age"));

[Link]("You will be " + (age+1) + " next year");

</script>

- You have to use "parseFloat()" for values like double, decimal and float.

Ex:

<script>

var rate = parseFloat(prompt("Enter Interest Rate"));

[Link]("Next year interest rate " + (rate+1) + " increased by


1");

</script>

- JavaScript provides methods to convert a number into string.

a) toString() : It converts into a numeric string.


b) toLocaleString() : It converts into a local string, which can use
the

regional formats. [Globalization, Localization]

Syntax:

var price = 45000;

[Link](); 45,000;

[Link]('en-us');

[Link]('en-in', {style:"currency", currency:"INR"});

Ex:

<script>

var price = 545000.55;

[Link]("Price=" + [Link]('en-in',
{style:"currency", currency:"INR"}));

</script>

- You can check number input using "isNaN()" method. It returns true if
input value is not a number.

Syntax:

var age = "A";

if(isNaN(age)) => it returns Boolean true

alert("Age must be number");

}
Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script>

function SubmitClick(){

var age = [Link]("txtAge").value;

if(isNaN(age))

alert("Age must be a number");

} else {

[Link]("Your Age : " + age);

</script>

</head>

<body>

Your Age : <input type="text" id="txtAge"> <button


>

</body>

</html>

- JavaScript supports various manipulations on numeric values with


operators and built-in functions.

- JavaScript operators to handle numeric values


+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus

** Exponent [Power] 2**3 = 8

++ Increment x++; x=x+1

-- Decrement x--; x=x-1

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script>

function SubmitClick(){

var n = parseInt([Link]("txtNumber").value);

if(n % 2 == 0)

[Link]("Verified..");

else {

alert("Not an even number");

}
</script>

</head>

<body>

Enter an Even number : <input type="text" id="txtNumber"> <button


>

</body>

</html>

- Increment : It increases the current value by one and assigns to the


current reference.

a) Post Increment : It will assign then later increments.

var x = 10;

var y = x++; x=11, y=10

b) Pre Increment : It will increment and later assign

var x = 10;

var y = ++x; x = 11, y=11

- Decrement : It decrease the current value by one and assigns to the


current reference

a) Post Decrement

var x = 10;

var y = x--; x=9, y=10

b) Pre Decrement
var x = 10;

var y = --x; x=9, y=9

- JavaScript provides a "Math" library to handle various math operations.

[Link]()

[Link]()

[Link]

[Link]()

[Link]()

[Link]()

[Link]()

[Link]()

[Link]() etc...

Class comments

Skip to main content

Google Classroom

Classroom

FullStack Web With React

7:30 PM - April 2024

EMI Calculator, Math FunctionsEMI Calculator, Math Functions

EMI Calculator, Math Functions

Sudhakar Sharma


19 Jun

Number Types

- Various Numeric Types

- Conversion of Number to String

- Conversion of String to Number

- isNaN()

- Operators

- Math Functions

[Link]

[Link]() [Link](2)

[Link]() [Link](2,3)

[Link]()

[Link]()

[Link]()

etc...

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script>

function GenerateCode(){

var a = [Link]([Link]() * 10);

var b = [Link]([Link]() * 10);

var c = [Link]([Link]() * 10);


var d = [Link]([Link]() * 10);

var e = [Link]([Link]() * 10);

var f = [Link]([Link]() * 10);

[Link]("lblCode").innerHTML = a + "&nbsp;" +
b + "&nbsp;" + c + "&nbsp;" + d + "&nbsp;" + e + "&nbsp;" + f;

</script>

</head>

<body >

<dl>

<dt>User Id</dt>

<dd><input type="text"></dd>

<dt>Password</dt>

<dd><input type="password"></dd>

<dt>Verify Code</dt>

<dd id="lblCode"></dd>

</dl>

<button>Login</button>

</body>

</html>

Ex: EMI Calculator

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">
<title>EMI Calculator</title>

<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/[Link]">

<style>

input[type="range"]{

width:90%;

</style>

<script type="text/javascript">

function AmountChange(){

[Link]("txtAmount").value =
[Link]("rangeAmount").value;

function YearChange(){

[Link]("txtYears").value =
[Link]("rangeYears").value;

function RateChange(){

[Link]("txtRate").value =
[Link]("rangeRate").value;

function CalculateClick(){

var P = parseInt([Link]("txtAmount").value);

var r =
parseFloat([Link]("txtRate").value)/12/100;

var n = parseInt([Link]("txtYears").value) *
12;

var EMI = P * r * ([Link](1+r,n)) / [Link](1+r,n) - 1;

[Link]("result").innerHTML = "Your
installement amount every month is <b>" +
[Link](EMI).toLocaleString('en-in',{style:'currency', currency:'INR'}) +
"</b> for " + n + " months";
}

</script>

</head>

<body class="container-fluid bg-secondary" >

<div class="bg-light text-dark p-4 m-4">

<div class="fs-4 text-center">Personal Loan EMI Calculator</div>

<div class="row my-3">

<div class="col">

Amount you need &#8377; <input type="text" size="16"


id="txtAmount">

</div>

<div class="col">

for <input type="text" size="2" id="txtYears"> years

</div>

<div class="col">

Interest rate <input type="text" size="2" id="txtRate"> %

</div>

</div>

<div class="row my-3">

<div class="col">

<input type="range" >
id="rangeAmount" min="100000" max="1000000" value="100000">

<div class="d-flex justify-content-between">

<span>&#8377; 1,00,000</span>

<span>&#8377; 10,00,000</span>

</div>

</div>

<div class="col">

<input type="range" min="1"


id="rangeYears" max="5" value="1">
<div class="d-flex justify-content-between">

<span>1</span>

<span>5</span>

</div>

</div>

<div class="col">

<input type="range" id="rangeRate"


min="10.45" max="18.45" value="10.45"
step="0.01">

<div class="d-flex justify-content-between">

<span>10.45%</span>

<span>18.45%</span>

</div>

</div>

</div>

<div class="row my-4">

<div class="col text-end">

<button class="btn btn-


primary">Calculate</button>

</div>

</div>

<div class="row my-4">

<div id="result" class="text-center fs-4"></div>

</div>

</div>

</body>

</html>

Task : BMI Calculator


<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<link rel="stylesheet"
href="../node_modules/bootstrap-icons/font/[Link]">

<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/[Link]">

<script>

function CalculateClick(){

var n = parseInt(prompt("Enter Weight"));

var status = [Link]("status");

if(n<40){

[Link] = "100px";

} else if (n>40 && n<60) {

[Link] = "250px";

</script>

</head>

<body class="container-fluid">

<button class="btn btn-primary mt-


4">Calculate</button>

<div class="mt-4 progress">

<div class="progress-bar bg-dark me-1" style="width:25%">Under


Weight</div>

<div class="progress-bar bg-success me-1"


style="width:25%">Normal Weight</div>
<div class="progress-bar bg-warning me-1"
style="width:25%">Over Weight</div>

<div class="progress-bar bg-danger me-1"


style="width:25%">Obese</div>

</div>

<div class="bi bi-triangle-fill" id="status">You</div>

</body>

</html>

String Type

Class comments

Skip to main content

Google Classroom

Classroom

FullStack Web With React

7:30 PM - April 2024

String in JavaScriptString in JavaScript

String in JavaScript
Sudhakar Sharma

20 Jun

- Number in JavaScript provides methods for precision and fixed values.

a) toPrecision() : It sets the length for number.

b) toFixed() : It sets the fractions limit.

Syntax:

var x = 300;

[Link](2); // 300.00

var x = 300.4478;

[Link](2); // 300.45

var x = 300.4478;

[Link](6); // 300.447

String Type

- String is a literal with group of characters enclosed with in

a) Double Quotes

b) Single Quotes

b) Backticks

- String chars include alphabet, number and special chars.

- Double and Single quotes are used for defining outer and inner string.

Syntax:

var link = "<a href=' [Link] '> Home </a>";


var link = '<a href=" [Link] "> Home </a> ';

- Single and double quote requires lot of concatenation with dynamic data
in string.

Syntax:

"string" + refName + "string" + (expression) + "string."

- JavaScript ES5+ version provides backtick for string, which allows


embedded data binding expression.

- JavaScript data binding expression is defined using "${ }", which is


allowed only with in backtick string representation.

Syntax:

` string ${refName} string ${expression} string `;

Ex:

<script>

var uname = prompt("Enter Name");

var age = parseInt(prompt("Enter Age"));

var msg1 = "Hello !&nbsp;" + uname + "&nbsp;your age is&nbsp;" +


age + "&nbsp;and you will be&nbsp;" + (age+1) + "&nbsp;next
year.<br>";

var msg2 = `Hello ! ${uname} your are is ${age} and you will be $
{age+1} next year.`;
[Link](msg1);

[Link](msg2);

</script>

EX:

<script>

var label_title = prompt("Enter Label");

var input_type = prompt("Enter Input Type");

var button_text = prompt("Enter Button Text");

var component = `

<label>${label_title}</label>

<div>

<input type=${input_type}>

<button>${button_text}</button>

</div>

`;

[Link](component);

</script>

- Several chars in a string representation can't print.

- Translator ignores few chars in a string representation as they are


internally used by the translation system.

- You have to explicitly print the non-printable chars by using "\".

Syntax:

var path = "D:\Images"; => D:Images

var path = "D:\\Images"; => D:\Images


Ex:

<script>

var path = "\"D:\\project\\images\\[Link]\"";

[Link](path);

</script>

- JavaScript provides various functions to format and to manipulate a


string.

String Formatting:

- It is the process of applying formats to string dynamically.

- The formats include text styles, font styles, font effects etc.

bold()

italics()

sup()

sub()

fontsize()

fontcolor()

strike()

toUpperCase()

toLowerCase()

etc..

Ex:

<script>

var msg = "Welcome to JavaScript";

[Link]([Link]().italics().fontcolor('green').toUpperCase());
</script>

onblur : defines action when element lost focus.

onkeyup : defines action when user key-in and release a char.

EX:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script>

function ChangeCase(){

var username = [Link]("txtName").value;

[Link]("txtName").value =
[Link]();

</script>

</head>

<body>

<fieldset>

<legend>Your Name</legend>

<input type="text" id="txtName"


placeholder="Name in Block Letters">

</fieldset>

</body>

</html>
Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<style>

dt {

font-weight: bold;

dd {

margin-bottom: 10px;

</style>

<script>

function ApplyClick(){

var size = [Link]("fontSize").value;

var color = [Link]("fontColor").value;

[Link]("msg").innerHTML = "Sample
Text".fontsize(size).fontcolor(color);

</script>

</head>

<body>

<fieldset>

<legend>Format Text</legend>

<dl>
<dt>Font Size</dt>

<dd><input type="range" id="fontSize"


min="1" max="7" value="1"></dd>

<dt>Font Color</dt>

<dd><input type="color" id="fontColor"></dd>

<dd>

<button >

</dd>

</dl>

<p id="msg" align="center"></p>

</fieldset>

</body>

</html>

Class comments

Skip to main content

Google Classroom

Classroom

FullStack Web With React

7:30 PM - April 2024

String ManipulationsString Manipulations

String Manipulations

Sudhakar Sharma

21 Jun

String Type

- Single Quote

- Double Quote

- Backtick

- Data Binding Expression ${ }

- Escape Character

- String Formatting functions

String Manipulation

1. length : It is a property that returns the total count of chars in a


string.

Syntax:

var msg = "Welcome";

[Link]; // 7

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script>

function SubmitClick(){

var userName = [Link]("UserName").value;


var userError = [Link]("UserError");

if([Link]==0)

[Link] = "User Name Required".fontcolor('red');

else {

if([Link]<4)

[Link] = "Name too short - Min 4


chars".fontcolor('goldenrod');

} else {

[Link]("Registered..");

function VerifyChars(){

var message = [Link]("Message").value;

var length = [Link];

var maxLength = 100;

[Link]("MsgStatus").innerHTML = `$
{maxLength-length} Chars Left`;

</script>

</head>

<body>

<dl>

<dt>User Name</dt>

<dd><input type="text" id="UserName"></dd>

<dd id="UserError"></dd>

<dt>Your Message</dt>
<dd>

<textarea id="Message" rows="4" >
cols="40" maxlength="100"></textarea>

</dd>

<dd id="MsgStatus"></dd>

</dl>

<button >

</body>

</html>

2. charAt() : It returns the character at specified index.

Syntax:

var msg = "Welcome";

[Link](1); // e

[Link](0); // W

3. charCodeAt() : It returns the ASCII code of character at specified


index.

Syntax:

var name = "Ajay";

[Link](0); // 65

Chars Code

A=65, Z=90

a=97, z=122

Ex:

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script>

function SubmitClick(){

var opt = [Link]("OTP").value;

var error = [Link]("Error");

if([Link](0)=="6") {

[Link]("Verified Successfully..");

} else {

[Link] = "Invalid OTP".fontcolor('red');

function VerifyName(){

var username = [Link]("UserName").value;

var nameError = [Link]("nameError");

if([Link](0)>=65 &&
[Link](0)<=90)

[Link] = "";

} else {

[Link] = "Name must start with uppercase


letter".fontcolor('red');

</script>

</head>
<body>

<dl>

<dt>Name</dt>

<dd><input type="text" placeholder="Name must start with


Uppercase letter" id="UserName"></dd>

<dd id="nameError"></dd>

<dt>OTP</dt>

<dd><input type="text" id="OTP"></dd>

<dd id="Error"></dd>

</dl>

<button >

</body>

</html>

4. startsWith() : It returns true if the string starts with specified


char(s)

5. endsWith() : It returns true if the string ends with specified char(s)

Syntax:

var msg = "Welcome";

[Link]("W"); // true

[Link]("w"); // false

[Link]("me"); // true

[Link]("e"); // true

Ex:

<!DOCTYPE html>

<html lang="en">

<head>
<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/[Link]">

<script>

function VerifyCard(){

var card = [Link]("Card").value;

var pic = [Link]("img");

if([Link]("44")){

[Link] = "../public/images/[Link]";

} else {

[Link] = "../public/images/[Link]";

function VerifySkype(){

var skype = [Link]("Skype").value;

var skypeError= [Link]("skypeError");

if([Link]("[Link]")) {

[Link] = "Your account


verified".fontcolor('green');

} else {

[Link] = "Invalid Skype ID".fontcolor('red');

</script>

</head>

<body class="container-fluid">

<div class="mt-4 w-25">


<dl>

<dt>Your Card Number</dt>

<dd class="input-group">

<input type="text" maxlength="16"


id="Card" class="form-control"><img class="input-group-text"
width="80">

</dd>

<dt>Your Skype Id</dt>

<dd>

<input type="text" id="Skype"


class="form-control">

</dd>

<dd id="skypeError"></dd>

</dl>

</div>

</body>

</html>

6. indexOf() : It returns the index number of specified character in a


string.

It verifies the first occurrence of char in a string.

It returns -1 if character not found.

7. lastIndexOf() : It returns the last occurrence index number of char in a


string.

Syntax:

var msg = "Welcome";

[Link]("e"); // 1

[Link]("e"); // 6

[Link]("a"); // -1
Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script>

function VerifyEmail(){

var email = [Link]("Email").value;

var EmailError = [Link]("EmailError");

if([Link]("@")<3)

[Link] = "Invalid Email Please include @ min


after 2 chars".fontcolor('red');

} else {

[Link] = "Email Verfified".fontcolor('green');

</script>

</head>

<body>

<dl>

<dt>Your email</dt>

<dd>

<input type="text" id="Email">

</dd>
<dd id="EmailError"></dd>

</dl>

</body>

</html>

8. slice() : It returns the chars between specified index. [uni-


directional]

9. substr() : It returns the specified number of chars from given index.

10. substring() : It returns the chars between specified index bi-


directional.

Syntax:

slice(startIndex, endIndex) // endIndex must be greater than


start

substr(startIndex, numberOfChars)

substring(startIndex, endIndex) // endIndex can be any direction

Class comments

Skip to main content

Google Classroom

Classroom

FullStack Web With React

7:30 PM - April 2024

String MethodsString Methods


String Methods

Sudhakar Sharma

24 Jun

What is difference between

a) slice()

b) substr()

c) substring()

Ex:

<script>

var email = prompt("Enter Email"); // john_nit@[Link] ,


sam@[Link]

var id = [Link](0, [Link]("@"));

var domain = [Link]([Link]("@")+1);

[Link](`Id=${id}<br>Domain=${domain}`);

</script>

Ex:

<script>

var videoUrl = "[Link]

var videoCode = [Link]([Link]("=")+1);

[Link](`Video Code: ${videoCode}`);

</script>
Ex:

<script>

var message = prompt("Enter your message"); //welcoME TO


JavaScriPT;

var firstChar = [Link](0).toUpperCase();

var restChars = [Link](1).toLowerCase();

var sentence = firstChar + restChars;

[Link](sentence);

</script>

11. trim() : It removes the leading spaces in a string. It trims both


start and

end.

12. trimEnd() : It removes leading spaces towards end.

13. trimStart() : It removes leading space towards start.

Syntax:

var otp = " 5678";

[Link](); "5678"

Ex:

<script>

var OTP = prompt("Enter OTP");

if([Link]()=="5678")

[Link]("Success..");

}
else

[Link]("Invalid OTP");

</script>

14. split() : It splits the string into multiple strings using a delimiter.
[separator]

Syntax:

var msg = "Welcome to JavaScript";

var result = [Link](' ');

result[0] // Welcome

result[1] // to

result[2] // JavaScript

15. replace() : It replaces specified char or word with a new char and
word.

It can replace only the first occurrence value.

Syntax:

var msg = "Hello ! JavaScript";

[Link]("JavaScript", "HTML");

16. repeat() : It creates a copy of string. It uses a number that


specified the

total count of copies to create.


Syntax:

var msg = "Welcome";

[Link](2);

17. match() : It uses a regular expression to verify the pattern of


value.

It returns Boolean true if string is matching specified pattern.

Note: Patterns or Regular Expression in JavaScript is defined using "/ /".

Syntax:

var regExp = /\+91\d{10}/;

var mobile = "919876543210";

if([Link](regExp)) => true or false

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script>

function VerifyPassword(){

var password = [Link]("Password").value;

var regExp = /(?=.*[A-Z])\w{4,15}/;


var error = [Link]("error");

var Grade = [Link]("Grade");

if([Link](regExp))

[Link] = "Strong Password".fontcolor('green');

[Link]=100;

else {

if([Link]<4)

[Link] = "Poor Password min 4 chars


required".fontcolor('red');

[Link] = 20;

} else {

[Link] = "Weak Password at least 1 must be


uppercase letter".fontcolor('goldenrod');

[Link] = 60;

</script>

</head>

<body>

<fieldset>

<legend>Verify Password</legend>

<input type="password" id="Password"


>

<div><meter id="Grade" style="width:170px" min="1"


max="100"></meter></div>
<div id="error"></div>

</fieldset>

</body>

</html>

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/[Link]">

<script>

function VerifyPassword(){

var password = [Link]("Password").value;

var regExp = /(?=.*[A-Z])\w{4,15}/;

var error = [Link]("error");

var Progress = [Link]("Progress");

if([Link](regExp))

[Link] = "Strong Password".fontcolor('green');

[Link] = "progress-bar progress-bar-animated


progress-bar-striped bg-success";

[Link] = "100%";

}
else {

if([Link]<4)

[Link] = "Poor Password min 4 chars


required".fontcolor('red');

[Link] = "progress-bar progress-bar-


animated progress-bar-striped bg-danger";

[Link] = "30%";

} else {

[Link] = "Weak Password at least 1 must be


uppercase letter".fontcolor('goldenrod');

[Link] = "progress-bar progress-bar-


animated progress-bar-striped bg-warning";

[Link] = "70%";

</script>

</head>

<body class="container-fluid">

<fieldset class="w-25">

<legend>Verify Password</legend>

<input type="password" class="form-control" id="Password"


>

<div class="progress w-100 mt-2">

<div id="Progress" class="progress-bar progress-bar-striped


progress-bar-animated"></div>

</div>

<div id="error"></div>

</fieldset>

</body>
</html>

Class comments

Skip to main content

Google Classroom

Classroom

FullStack Web With React

7:30 PM - April 2024

BooleanBoolean

Boolean

Sudhakar Sharma

25 Jun

Boolean Type

- Boolean is used in decision making.

- Boolean can handle the keywords "true & false".

- JavaScript Boolean values can use "1 & 0 " to compare.

true = 1

false = 0

Syntax:
var stock = true;

if(stock==1) // valid - but bad code

if(stock==true) // good code

- HTML attributes provides Boolean value directly to reference, hence


conversion is not required.

- HTML Boolean attributes are:

readonly

disabled

checked

selected

autofocus

required

novalidate

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>
<script>

function StockChange(){

var optStock = [Link]("optStock");

var lblStock = [Link]("lblStock");

if([Link])

[Link] = "Available";

else

[Link] = "Out of Stock";

</script>

</head>

<body>

<dl>

<dt>Stock</dt>

<dd>

<input type="checkbox" >
id="optStock"> <label id="lblStock"> Out of Stock </label>

</dd>

</dl>

</body>

</html>

FAQ: How to convert a string Boolean word into Boolean native?

Ans : Explicitly by using various decision making statements and


operators
Syntax: Ternary Operator

(condition) ? true : false

(ref=="true") ? true : false

Ex:

<script>

var choice = (prompt("Enter true or false")=="true"?true:false);

if(choice==true)

[Link]("You selected true");

else {

[Link]("You selected false");

</script>

- Boolean type depends on comparison and logical operators, which are


used to build Boolean expression.

- The comparison operators

> greater than

>= greater than or equal

< less than

<= less than or equal

== equal

=== identical equal


!= not-equal

!== not-identical

FAQ: What is difference between "==" & "===" ?

Ans: "==" can compare values of different types.

"===" can compare values only of same data type.

Syntax:

"10" == 10 => true

"10" === 10 => false

"10" === "10" => true

10 === 10 => true

- The Logical operators

&& AND

|| OR

! NOT

- Logical "&&" combines multiple expressions and returns true if all


evaluates to true.

(10==10) && (10==20) => false

(10 > 5) && (10 > 8) => true

- Logical "||" combines multiple expressions and returns true if any one
expression evaluates to true.

(10 > 5) || (10 < 5) => true


(10<5) || (10 < 8) => false

- Logical "!" NOT can transform or switch from true to false & vice versa.

!true => false

!disabled => disabled = false

!readonly => readonly= false

- Boolean requires selection statements to handle decision making.

- Selection statements are configure using

"if, else, switch, case, default"

The "IF" selector:

- It is a decision making statement used to execute a block of statements


based on the given Boolean expression.

- It have various forms

a) Forward Jump

b) Simple Decision

c) Multiple Decisions

d) Multi Level Decisions

Forward Jump:

- It is a programming approach where there is no alternative provided.

- It flows to next only when the given condition evaluates to true.

Syntax:

if (condition)
{

statements on true;

Class comments

Skip to main content

Google Classroom

Classroom

FullStack Web With React

7:30 PM - April 2024

IF StatementsIF Statements

IF Statements

Sudhakar Sharma

26 Jun

The IF Selector

1. Forward Jump

if (condition)

statements on true;

Ex:

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script>

function VerifyCard(){

var card = [Link]("Card").value;

if(card==="4444555566667890")

[Link]("Cvv").disabled = false;

function VerifyCvv(){

var cvv = [Link]("Cvv").value;

if(cvv==="345")

[Link]("Expiry").disabled = false;

function VerifyExpiry(){

var expiry = [Link]("Expiry").value;

if(expiry==="2025")

[Link]("btnPay").disabled = false;

</script>
</head>

<body>

<fieldset>

<legend>Payment</legend>

<dl>

<dt>Card Number</dt>

<dd><input type="text" id="Card" maxlength="16"


>

<dt>CVV</dt>

<dd><input type="text" size="4" id="Cvv" >
disabled></dd>

<dt>Expiry</dt>

<dd>

<select id="Expiry" disabled >

<option>Select Expiry</option>

<option>2024</option>

<option>2025</option>

<option>2026</option>

</select>

</dd>

</dl>

<button id="btnPay" disabled>Pay</button>

</fieldset>

</body>

</html>

Ex:

<!DOCTYPE html>

<html lang="en">
<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script>

function VerifyCard(){

var card = [Link]("Card").value;

if(card==="4444555566667890")

[Link]("Cvv").disabled = false;

[Link]("cvvContainer").[Link] =
"block";

function VerifyCvv(){

var cvv = [Link]("Cvv").value;

if(cvv==="345")

[Link]("Expiry").disabled = false;

[Link]("expiryContainer").[Link] =
"block";

function VerifyExpiry(){

var expiry = [Link]("Expiry").value;

if(expiry==="2025")

[Link]("btnPay").disabled = false;

[Link]("btnPay").[Link] = "block";
}

</script>

</head>

<body>

<fieldset>

<legend>Payment</legend>

<dl>

<dt>Card Number</dt>

<dd><input type="text" id="Card" maxlength="16"


>

<div id="cvvContainer" style="display: none;">

<dt>CVV</dt>

<dd><input type="text" size="4" id="Cvv"


disabled></dd>

</div>

<div id="expiryContainer" style="display: none;">

<dt>Expiry</dt>

<dd>

<select id="Expiry" disabled >

<option>Select Expiry</option>

<option>2024</option>

<option>2025</option>

<option>2026</option>

</select>

</dd>

</div>

</dl>

<button style="display: none;" id="btnPay" disabled>Pay</button>

</fieldset>
</body>

</html>

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script>

function SubmitClick(){

var optMale = [Link]("optMale");

var optFemale = [Link]("optFemale");

var para = [Link]("p");

if([Link])

[Link] = `Gender : ${[Link]}`;

if([Link])

[Link] = `Gender : ${[Link]}`;

}
</script>

</head>

<body>

<fieldset>

<legend>Gender</legend>

<input type="radio" name="gender" value="Male" id="optMale">


<label> Male </label>

<input type="radio" name="gender" value="Female"


id="optFemale"> <label> Female</label>

<br><br>

<button >

<p></p>

</fieldset>

</body>

</html>

2. Simple Decision

- In this approach we provide one alternative.

- It executes one set of statements when condition is true and another set
when it is false.

Syntax:

if (condition)

statements on true;

else

statements on false;

}
- "else" is a clause used as alternative for condition defined in "IF".

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script>

function VerifyCard(){

var card = [Link]("Card").value;

if(card==="4444555566667890")

[Link]("Cvv").disabled = false;

[Link]("cvvContainer").[Link] =
"block";

} else {

[Link]("cvvContainer").[Link] =
"none";

function VerifyCvv(){

var cvv = [Link]("Cvv").value;

if(cvv==="345")

[Link]("Expiry").disabled = false;
[Link]("expiryContainer").[Link] =
"block";

function VerifyExpiry(){

var expiry = [Link]("Expiry").value;

if(expiry==="2025")

[Link]("btnPay").disabled = false;

[Link]("btnPay").[Link] = "block";

</script>

</head>

<body>

<fieldset>

<legend>Payment</legend>

<dl>

<dt>Card Number</dt>

<dd><input type="text" id="Card" maxlength="16"


>

<div id="cvvContainer" style="display: none;">

<dt>CVV</dt>

<dd><input type="text" size="4" id="Cvv"


disabled></dd>

</div>

<div id="expiryContainer" style="display: none;">

<dt>Expiry</dt>

<dd>

<select id="Expiry" disabled >
<option>Select Expiry</option>

<option>2024</option>

<option>2025</option>

<option>2026</option>

</select>

</dd>

</div>

</dl>

<button style="display: none;" id="btnPay" disabled>Pay</button>

</fieldset>

</body>

</html>

3. Multi Level Decisions

- It is a programming approach where a condition is defined with in the


context of another condition block or clause block.

- It enables forward jump as it moves to next level condition only when the
previous level evaluates to true.

Syntax:

if (condition-1 )

if(condition-2)

statements on both conditions true;

} else {

statements on 2nd condition false;

else {
statements on 1st condition false;

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script>

function LoginClick(){

var UserId = [Link]("UserId").value;

var Password = [Link]("Password").value;

var p = [Link]("p");

if(UserId=="")

[Link] = "User Id Required".fontcolor('red');

else {

if(UserId==="john_nit")

if(Password==="")

[Link] = "Password Required".fontcolor('red');

} else {

if(Password==="john@123")
{

[Link]("Login Success");

else

[Link] = "Invalid Password".fontcolor('red');

else

[Link] = "Invalid UserId".fontcolor('red');

</script>

</head>

<body>

<dl>

<dt>User Id</dt>

<dd><input type="text" id="UserId"></dd>

<dt>Password</dt>

<dd><input type="password" id="Password"></dd>

</dl>

<button >

<p></p>

</body>

</html>
Ex: Payment

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script>

function PayClick(){

var p = [Link]("p");

var Card = [Link]("Card").value;

var Cvv = [Link]("Cvv").value;

var Expiry = [Link]("Expiry").value;

if(Card==="")

[Link] = "Card Number Required".fontcolor('red');

} else {

if(Card==="4444555566667890")

if(Cvv==="")

[Link] ="CVV Required".fontcolor('red');

} else {

if(Cvv==="345")
{

if(Expiry=="-1"){

[Link] = "Please Select Expiry


Year".fontcolor('red');

} else {

if(Expiry==="2025"){

[Link]("<h2>Payment Success..</h2>");

} else {

[Link] = "Invalid Expiry".fontcolor('red');

} else {

[Link] = "Invalid CVV".fontcolor('red');

} else {

[Link] = "Invalid Card Number".fontcolor('red');

</script>

</head>

<body>

<fieldset>

<legend>Payment</legend>

<dl>
<dt>Card</dt>

<dd><input type="text" id="Card"></dd>

<dt>Cvv</dt>

<dd><input type="text" id="Cvv" size="4"></dd>

<dt>Expiry</dt>

<dd>

<select id="Expiry">

<option value="-1">Select Expiry</option>

<option>2024</option>

<option>2025</option>

<option>2026</option>

</select>

</dd>

</dl>

<button >

<p align="center"></p>

</fieldset>

</body>

</html>

4. Multiple Choices

Class comments

Skip to main content

Google Classroom
Classroom

FullStack Web With React

7:30 PM - April 2024

IF and Switch SelectorIF and Switch Selector

IF and Switch Selector

Sudhakar Sharma

27 Jun

- Forward Jump

- Simple Decision

- Multi Level Decisions

Multiple Choices

- You can configure different logics for one action.

- Program can choose any one according to the state and situation.

- It is just providing multiple alternatives for one action.

- Alternative condition is defined using "else if"

Syntax:

if (condition-1 )

statements on condition-1 true;

else if (condition-2)

statements on condition-2 true;

else

{
statements on all conditions false;

Ex: Amazon-Login

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Amazon</title>

<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/[Link]">

<script>

var flag = "";

function ContinueClick()

var UserId = [Link]("txtUserId").value;

function ToggleContainers(){

[Link]("Id_Container").[Link] =
"none";

[Link]("Pwd_Container").[Link] =
"block";

if(UserId==="david123@[Link]")

{
flag = `Your email verified successfully - Activation link sent to $
{UserId}`;

ToggleContainers();

else if(UserId==="+919876543211")

flag = `Your mobile verified successfully - OTP sent to your $


{UserId}`;

ToggleContainers();

else {

[Link]("UserId_Error").innerHTML = `$
{UserId} doesn't exist`;

function LoginClick(){

var Password = [Link]("txtPassword").value;

if(Password==="david@123")

[Link](`<h2>${flag}</h2>`);

} else {

[Link]("Password_Error").innerHTML =
"Invalid Password";

</script>

</head>

<body class="d-flex justify-content-center align-items-center"


style="height: 100vh;">

<div>

<div class="h2">Sign In</div>


<div id="Id_Container">

<label class="form-label fw-bold">Email or mobile phone


number</label>

<div>

<input type="text" id="txtUserId" class="form-control">

<div id="UserId_Error" class="text-danger"></div>

</div>

<div class="my-2">

<button class="btn btn-warning w-100"


>

</div>

</div>

<div id="Pwd_Container" style="display: none;">

<label class="form-label fw-bold">Password</label>

<div>

<input type="password" id="txtPassword" class="form-


control">

<div id="Password_Error"></div>

</div>

<div class="my-2">

<button class="btn btn-warning w-


100">Login</button>

</div>

</div>

</div>

</body>

</html>

Switch Selector
- Switch is used to interrupt the flow of electrons in a circuit.

- There are various types of switches

a) Push Button Switch

b) Toggle Switch

c) Selector Switch

d) Joy Stick Switch

etc..

- Switch selector is a decision making approach used in programming,


which selects exactly the required set of statements.

- It saves the compile time.

Syntax:

switch(value / expression)

case value/expression:

statements;

jump;

default:

statements;

jump;

Ex:

<script>

var n = parseInt(prompt("Enter Number"));

switch(n)

case 1:
[Link]("One");

break;

case 2:

[Link]("Two");

break;

case 3:

[Link]("Three");

break;

case 4:

[Link]("Four");

break;

default:

[Link]("Please enter value from 1 to 4 only");

break;

</script>

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Amazon</title>

<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/[Link]">

<script>

var flag = "";


function ContinueClick()

var UserId = [Link]("txtUserId").value;

function ToggleContainers(){

[Link]("Id_Container").[Link] =
"none";

[Link]("Pwd_Container").[Link] =
"block";

switch(UserId)

case "david123@[Link]":

flag = `Your email verified successfully - Activation link sent to


${UserId}`;

ToggleContainers();

break;

case "+919876543211":

flag = `Your mobile verified successfully - OTP sent to your $


{UserId}`;

ToggleContainers();

break;

default:

[Link]("UserId_Error").innerHTML = `$
{UserId} doesn't exist`;

break;

/*
if(UserId==="david123@[Link]")

flag = `Your email verified successfully - Activation link sent to $


{UserId}`;

ToggleContainers();

else if(UserId==="+919876543211")

flag = `Your mobile verified successfully - OTP sent to your $


{UserId}`;

ToggleContainers();

else {

[Link]("UserId_Error").innerHTML = `$
{UserId} doesn't exist`;

*/

function LoginClick(){

var Password = [Link]("txtPassword").value;

if(Password==="david@123")

[Link](`<h2>${flag}</h2>`);

} else {

[Link]("Password_Error").innerHTML =
"Invalid Password";

</script>

</head>
<body class="d-flex justify-content-center align-items-center"
style="height: 100vh;">

<div>

<div class="h2">Sign In</div>

<div id="Id_Container">

<label class="form-label fw-bold">Email or mobile phone


number</label>

<div>

<input type="text" id="txtUserId" class="form-control">

<div id="UserId_Error" class="text-danger"></div>

</div>

<div class="my-2">

<button class="btn btn-warning w-100"


>

</div>

</div>

<div id="Pwd_Container" style="display: none;">

<label class="form-label fw-bold">Password</label>

<div>

<input type="password" id="txtPassword" class="form-


control">

<div id="Password_Error"></div>

</div>

<div class="my-2">

<button class="btn btn-warning w-


100">Login</button>

</div>

</div>

</div>

</body>
</html>

FAQ's:

1. Can we define a switch without "default" block?

A. Yes

2. Can we define default block before or between cases?

A. Yes

3. Can we use "return" as jump for case or default?

A. Yes.

4. What is difference between break & return?

A. break terminates the block but keeps the compiler alive.

return terminates the block and compiling process.

Note: Any code defined after "return" is not reachable to compiler.

Class comments

Skip to main content


Google Classroom

Classroom

FullStack Web With React

7:30 PM - April 2024

Switch DemoSwitch Demo

Switch Demo

Sudhakar Sharma

28 Jun

Switch Selector

FAQ's:

5. How to define one set of statements for multiple cases?

A. By defining the cases line-by-line

case 1:

case 2:

case 3:

statements;

break;

Ex:

<script>

function f1(){

var product = prompt("Enter Product Name");

switch(product)

case "TV":

case "Mobile":
case "Watch":

[Link](`${product} belongs to Electronics category`);

break;

case "Casuals":

case "Boots":

[Link](`${product} belongs to Footwear category`);

break;

default:

[Link](`Avail Products : TV, Mobile, Watch, Casuals, Boots


only..`);

break;

f1();

</script>

Ex:

<script>

function f1(){

var choice = prompt("Enter Choice Y or N");

switch(choice)

case "y":

case "Y":

[Link]("You selected yes to continue");

break;

case "n":

case "N":

[Link]("You selected No to stop");


break;

default:

[Link]("Please enter your choice Y or N");

break;

f1();

</script>

Ex:

<script>

function f1(){

var choice = prompt("Enter Choice Yes or No");

switch([Link]())

case "yes":

[Link]("You selected yes to continue");

break;

case "no":

[Link]("You selected No to stop");

break;

default:

[Link]("Please enter your choice Y or N");

break;

f1();

</script>
6. How you write case for range of values?

A. By using Boolean expression that verifies the range of values.

IF case is using a Boolean expression then the switch must always use
true as value.

Syntax:

switch(true)

case booleanExpression:

statements;

break;

Ex:

<script>

function f1(){

var n = parseInt(prompt("Enter Number"));

switch(true)

case (n>=1 && n<=10):

[Link](`Your number ${n} is between 1 to 10`);

break;

case (n>=11 && n<=20):

[Link](`Your number ${n} is between 11 to 20`);

break;

default:

[Link]("Pleae enter a number between 1 to 20 only");

break;

}
}

f1();

</script>

7. Can we define case without jump statement?

A. Yes. Switch will continue to execute next case until break occurs.

If there is no break in next level cases then it executes up to end,


which include the

default.

Ex:

<script>

function f1(){

var n = parseInt(prompt("Enter Number"));

switch(n)

case 1:

[Link]("You will get one<br>");

break;

case 2:

[Link]("You selected Two third one is free<br>");

case 3:

[Link]("Collect your three<br>");

break;

default:

[Link]("Pleae enter a number between 1 to 3 only");

break;

}
}

f1();

</script>

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/[Link]">

<script>

var regExp = / /;

var tip = "";

function SetValidation(pattern, tooltip, image){

regExp = pattern;

tip = tooltip;

[Link]("imgFlag").src = image;

[Link]("txtMobile").placeholder = tip;

function CountryChange()

var countryName =
[Link]("lstCountries").value;
switch(countryName)

case "India":

SetValidation(/\+91\d{10}/, "+91 and 10 digits",


"../public/images/[Link]");

break;

case "US":

SetValidation(/\+\(1\)\(\d{3}\)\s\d{4}-\d{4}/, "+(1)(000) 0000-


0000", "../public/images/[Link]");

break;

case "UK":

SetValidation(/\+\(44\)\(\d{3}\)\s\d{4} \d{4}/, "+(44)(000)


0000 0000", "../public/images/[Link]");

break;

default:

SetValidation(/ /, "Please select country", "");

break;

function VerifyClick(){

var mobile = [Link]("txtMobile").value;

var lblError = [Link]("lblError");

if([Link](regExp))

[Link](`<h2>Your Mobile ${mobile} Verified


Successfully..</h2>`)

} else {
[Link] = `Invalid Mobile : ${tip}`;

</script>

</head>

<body class="container-fluid">

<h1>Verify Your Mobile</h1>

<dl class="w-25">

<dt>Select Your Country</dt>

<dd class="input-group">

<select class="form-select" id="lstCountries"


>

<option>Choose Country</option>

<option>India</option>

<option>US</option>

<option>UK</option>

</select>

<img class="input-group-text" id="imgFlag" width="50">

</dd>

<dt>Mobile Number</dt>

<dd><input type="text" class="form-control" id="txtMobile"></dd>

<dd id="lblError" class="text-danger"></dd>

<button class="btn btn-primary w-100 mt-


3">Verify</button>

</dl>

</body>

</html>

Class comments
Skip to main content

Google Classroom

Classroom

FullStack Web With React

7:30 PM - April 2024

Undefined, Null, ArrayUndefined, Null, Array

Undefined, Null, Array

Sudhakar Sharma

1 Jul

Number

String

Boolean Types

- Boolean Operators

- Conditional Statements

if, else, switch, case, default

Undefined Type

- Undefined is a value assigned to any reference if value is not defined.

Syntax:

var x;
[Link]("x=" + x); x = undefined

- You can use "undefined" keyword to verify value.

if(x===undefined) => returns true if x is undefined, but not


good.

if(x) => returns true if x is defined, good code.

if(x!=undefined) => returns true if x is defined, not good


code.

Ex:

<script>

var price;

if(price)

[Link](`Price=${price}`);

} else {

[Link]("Please provide a value for price");

</script>

Null

- It is a type defined for reference when value is not provided at runtime.

- You can verify by using "null" keyword.

Syntax:
var price = prompt("Enter Price");

if(price==null)

Summary

- Number

- String

- Boolean

- Null

- Undefined

- Symbol

Non Primitive Data Types

- They are mutable types.

- They don't have fixed range for values.

- Value range varies according to memory available.

- They are stored in memory heap.

- Heap is memory which allows random access.

- JavaScript non-primitive includes

a) Array

b) Object

c) Map

d) Set (obsolete)

Array

- Arrays are used to reduce overhead and complexity.


- Arrays can reduce overhead by storing values in sequential order.

- Arrays can reduce complexity by storing multiple values under the


reference of one name.

- Array can handle various types of values in sequential order.

- Array size can change dynamically.

Note: Several computing technologies can't handle different types of


memory in

sequential order and can't change the memory size dynamically.


Hence they

restrict array to similar data type and will not allow to change the size
dynamically.

[C, C++, Java, C#, … ]

- JavaScript array size can change dynamically and can handle various
types of values in sequential order.

- Array is a collection arranged in sequential order and allows access in


random.

Configuring Array:

- Array declaration comprises of keyword and reference name.

- You can use var, let or const.

Syntax:

var products;

let categories;

- To allocate multiple memory you can initialize or assign memory using 2


techniques
a) Array meta character "[ ]"

b) Array Constructor "Array()"

Syntax:

var products = [ ]; => Initializing memory

var products = new Array();

(or)

var products;

products = [ ]; => Assigning memory

var products;

products = new Array();

- Array meta character "[ ]" is used to allocate static memory, which
defined memory for first request and continue the same across any
number of requests.

- Array constructor is used to allocate a dynamic memory, which is a


discreet memory.

Memory is newly allocated for every request.

Static => Continuous Memory

Dynamic => Discreet Memory

Class comments
Skip to main content

Google Classroom

Classroom

FullStack Web With React

7:30 PM - April 2024

Array ManipulationArray Manipulation

Array Manipulation

Sudhakar Sharma

2 Jul

Non Primitive

- Array

-[]

- Array()

Storing values in Array:

- You can initialize values into array memory.

Syntax:

var values = [10, "A", true];

var values = new Array(10, "A", true);

- You can assign values with reference of property.


- Property is a string type that maps to memory index, which is number
type.

Syntax:

var values = [ ];

values[0] = 10; // 0 is property

values["1"] = 20; // 1 is property

values[0] = 30; // valid you can re-assign, as var & let allows

assignment.

- Array memory can handle any type of value

a) Primitive type

b) Non Primitive type

c) Function

Syntax:

var values = [ 10, "A", true, ["Delhi", "Hyd"], function(){ } ];

values[0] = 10;

values[1] = "A";

values[2] = true;

values[3] = ["Delhi", "Hyd"];

values[4] = function(){ }

- Array can handle function in memory, but it must be anonymous.

- Anonymous function will not have a name.

- Anonymous functions are accessed by using IIFE pattern.

[Immediately Invoked Function Expression]


Syntax:

values[4]();

values[3][0] // Delhi

Syntax: IIFE

<script>

(function()

[Link]("Hello !");

})();

</script>

Ex:

<script>

var values = [[10, 20, 30], ["Delhi", "Hyd", ["TV", "Watch"]]];

values[1][2][1] = "Fastrack Watch";

[Link](values[1][2][1]);

</script>

Ex:

<script>

var values = [[10, 20, 30], ["Delhi", "Hyd", ["TV", "Watch"]], function()
{[Link]("Function inside array")}];

values[1][2][1] = "Fastrack Watch";

[Link](values[1][2][1] + "<br>");

values[2]();

</script>
Array Manipulations

1. Reading Array Elements

toString() : It returns all array elements with "," delimiter.

join() : It returns all array elements with custom delimiter.

map() : It is an iterator that reads elements in sequential


order.

forEach() : It is an iterator that reads elements and index in


sequential order.

Ex:

<script>

var categories = ["Electronics", "Fashion", "Footwear"];

[Link]([Link]() + "<br>");

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

</script>

Syntax: Map Iterator

[Link](function(value){

// use value

})

Syntax: forEach Iterator

[Link](function(value, index){

// use index & value

})
Ex:

<script>

var categories = ["Electronics", "Fashion", "Footwear"];

[Link](function(value, index){

[Link](`<p>[${index}]${value}</p>`);

});

</script>

<script>

var categories = ["Electronics", "Fashion", "Footwear"];

[Link](function(value){

[Link](`<p>${value}</p>`);

});

</script>

- You can use explicit iterators for reading array properties and elements.

for..in It can read all properties of array.

for..of It can read all elements of array.

Syntax:

for(var property in collection)

for(var value of collection)

{
}

Ex:

<script>

var categories = ["Electronics", "Fashion", "Footwear"];

for(var property in categories)

[Link](`<p>[${property}]${categories[property]} </p>`);

</script>

2. Filtering Elements

find() : It is an iterator that finds and returns only first occurrence


value

that matches the given condition.

filter() : It is an iterator that returns all values that match given


condition

slice() : It can returns the values between specified index.

Syntax:

[Link](function(value){

return value_condition; => returns on value

});

[Link](function(value){ => returns an array [ ]


return value_condition;

});

Ex:

<script>

var values = [40000, 31000, 57000, 67000, 45100];

[Link](function(value){

return value>=30000 && value<=50000;

}).map(function(value){

[Link](`<p>${value}</p>`);

})

</script>

Class comments

Skip to main content

Google Classroom

Classroom

FullStack Web With React

7:30 PM - April 2024

Array PresentationArray Presentation

Array Presentation

Sudhakar Sharma

3 Jul

Configure Array

Store Elements
Read Array Elements

Creating and Adding elements into page dynamically:

1. You can create any HTML element by using

[Link]()

Syntax:

[Link]("img")

[Link]("p")

[Link]("div")

2. Assign created element to a memory reference

Syntax:

var pic = [Link]("img"); [HTMLElement type]

3. Every dynamic element requires "Properties"

Syntax:

[Link] = "200";

[Link]= "100";

[Link]= "./images/[Link]";

4. Add element into page by using "appendChild()"

Syntax:

<body> </body>
<div id="container"> </div>

[Link]("body").appendChild(pic);

[Link]("container").appendChild(pic);

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script>

function LoadClick(){

var pic = [Link]("img");

[Link]="100";

[Link]="100";

[Link]="../public/images/[Link]";

[Link]("container").appendChild(pic);

</script>

</head>

<body>

<button Image</button>


<br><br>

<div id="container">

</div>

</body>

</html>

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script>

function LoadClick(){

var ol = [Link]("ol");

[Link] = "a";

var item1 = [Link]("li");

var item2 = [Link]("li");

[Link] = "Home";

[Link] = "About";

[Link](item1);

[Link](item2);
[Link]("container").appendChild(ol);

</script>

</head>

<body>

<button List</button>

<br><br>

<div id="container">

</div>

</body>

</html>

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script>

function LoadClick(){

var table = [Link]("table");

[Link]="25%";
[Link]="1";

var thead = [Link]("thead");

var tr_head = [Link]("tr");

var th = [Link]("th");

[Link] = "Product Name";

tr_head.appendChild(th);

[Link](tr_head);

[Link](thead);

[Link]("container").appendChild(table);

</script>

</head>

<body>

<button Table</button>

<br><br>

<div id="container">

</div>

</body>

</html>

Ex:

<!DOCTYPE html>

<html lang="en">
<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script>

var menu = ["Home", "Shop", "Blog", "Pages", "Docs", "Contact"];

function bodyload(){

[Link](function(item){

var li = [Link]("li");

[Link] = item;

[Link]("ol").appendChild(li);

var button = [Link]("button");

[Link] = "button";

[Link] = item;

[Link]("nav").appendChild(button);

var option = [Link]("option");

[Link] = item;

[Link] = item;

[Link]("select").appendChild(option);

var ul_li = [Link]("li");

var input = [Link]("input");

[Link] = "checkbox";

[Link] = item;
var label = [Link]("label");

[Link] = item;

ul_li.appendChild(input);

ul_li.appendChild(label);

[Link]("ul").appendChild(ul_li);

})

</script>

</head>

<body >

<nav style="display: flex;justify-content: space-between; width:


50%;">

</nav>

<ol>

</ol>

<select>

</select>

<ul>

</ul>

</body>

</html>
Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script>

var menu = ["Home", "Shop", "Blog", "Pages", "Docs"];

function bodyload(){

[Link](function(item){

var li = [Link]("li");

[Link] = item;

[Link]("ol").appendChild(li);

var button = [Link]("button");

[Link] = "button";

[Link] = item;

[Link]("nav").appendChild(button);

var option = [Link]("option");

[Link] = item;

[Link] = item;

[Link]("select").appendChild(option);
var ul_li = [Link]("li");

ul_li.innerHTML = `<input type="checkbox"> <label>$


{item}</label>`;

[Link]("ul").appendChild(ul_li);

})

</script>

</head>

<body >

<nav style="display: flex;justify-content: space-between; width:


50%;">

</nav>

<ol>

</ol>

<select>

</select>

<ul>

</ul>

</body>

</html>
Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/[Link]">

<script
src="../node_modules/bootstrap/dist/js/[Link]"></script>

<script>

var menu = ["Amazon","Home", "Shop", "Blog", "Pages", "Docs"];

function bodyload(){

[Link](function(item){

var div = [Link]("div");

[Link] = "alert alert-dismissible alert-warning";

[Link] = `

<button class="btn btn-close"


data-bs-dismiss="alert"></button>

<h3>${item}</h3>

`;

[Link]("section").appendChild(div);

})

</script>

</head>

<body class="container-fluid">

<section class="m-4 p-4 w-25">


</section>

</body>

</html>

Class comments

Skip to main content

Google Classroom

Classroom

FullStack Web With React

7:30 PM - April 2024

Array ManipulationArray Manipulation

Array Manipulation

Sudhakar Sharma

4 Jul

Adding Elements into Array:

push() : It adds new element(s) as last item.


unshift() : It adds new element(s) as first item.

splice() : It adds new element(s) at specific position.

Syntax:

[Link](e1, e2, … )

[Link](e1, e2, …)

[Link](indexNumber, deleteCount, ...Items)

Note: Set delete count to "0" to add element without deleting existing.

Ex:

[Link](1, 0, "About");

[Link]("About", "Contact");

Removing Elements from Array:

pop() : It removes and returns last element.

shift() : It removes and returns first element.

splice() : It removes and returns specific element(s).

Syntax:

[Link]()

[Link]()

[Link](1,2); // from 1 index remove 2 items

Sorting Elements:

sort() : It sorts the elements and returns in ascending order.

reverse() : It arranges elements in reverse order.


Syntax:

[Link]()

[Link]()

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<link rel="stylesheet"
href="../node_modules/bootstrap-icons/font/[Link]">

<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/[Link]">

<script
src="../node_modules/bootstrap/dist/js/[Link]"></script>

<script type="text/javascript">

var menuItems = ["Home", "Shop"];

function LoadMenuItems(){

[Link]("lstMenuItems").innerHTML = "";

[Link](function(item){

var option = [Link]("option");

[Link] = item;

[Link] = item;

[Link]("lstMenuItems").appendChild(option);
})

[Link]("lblCount").innerHTML =
[Link];

function AddClick(){

var item_name = [Link]("txtName").value;

if([Link](item_name)==-1)

[Link](item_name);

alert(`${item_name} Added Successfully..`);

LoadMenuItems();

[Link]("txtName").value = "";

} else {

alert(`${item_name} Exists`);

function RemoveClick(){

var selectedItem =
[Link]("lstMenuItems").value;

var selectedItemIndex = [Link](selectedItem);

var flag = confirm(`Are you sure?\nWant to delete $


{selectedItem}`);

if(flag==true){

[Link](selectedItemIndex,1);

LoadMenuItems();

}
function RemoveAllClick(){

[Link] = 0;

LoadMenuItems();

function EditClick(){

var selectedItem =
[Link]("lstMenuItems").value;

[Link]("txtEdit").value = selectedItem;

function SaveClick(){

var newValue = [Link]("txtEdit").value;

var selectedItem =
[Link]("lstMenuItems").value;

var selectedIndex = [Link](selectedItem);

menuItems[selectedIndex] = newValue;

LoadMenuItems();

function SortAsc(){

[Link]();

LoadMenuItems();

function SortDesc(){

[Link]();

[Link]();

LoadMenuItems();

</script>

</head>

<body class="container-fluid" >

<div class="mt-3 w-50">


<h2>Design Your Menu</h2>

<div>

<label class="form-label fw-bold">Add Menu Item</label>

<div class="input-group">

<input type="text" placeholder="New Menu Item Name"


class="form-control" id="txtName"> <button >class="btn btn-primary">Add</button>

</div>

</div>

<div class="my-2">

<label class="form-label fw-bold">Menu Items <span


id="lblCount" class="badge bg-danger"></span> </label>

<button class="bi bi-sort-alpha-down btn btn-


success"></button>

<button class="bi bi-sort-alpha-up btn btn-


warning"></button>

<div class="my-3">

<select class="form-select" size="3" id="lstMenuItems">

</select>

<div class="mt-2 row">

<div class="col">

<button data-bs-toggle="modal" >
data-bs-target="#edit" class="btn w-100 btn-warning bi bi-pen-
fill">Edit</button>

<div class="modal fade" id="edit">

<div class="modal-dialog">

<div class="modal-content">

<div class="modal-header">

<h3>Edit Item</h3>

</div>
<div class="modal-body">

<input type="text" class="form-control"


id="txtEdit">

</div>

<div class="modal-footer">

<button class="btn btn-success" data-bs-


dismiss="modal" >

<button class="btn btn-danger" data-bs-


dismiss="modal">Cancel</button>

</div>

</div>

</div>

</div>

</div>

<div class="col">

<button class="btn w-100 btn-


danger bi bi-trash-fill">Remove</button>

</div>

<div class="col">

<button class="btn w-100 btn-


outline-danger bi bi-trash">Remove All</button>

</div>

</div>

</div>

</div>

</div>

</body>

</html>

Class comments
Skip to main content

Google Classroom

Classroom

FullStack Web With React

7:30 PM - April 2024

Object Object

Object

Sudhakar Sharma

5 Jul

Array with Spread Operator:

- You can use "..." which is a spread operator to copy the elements of an
array into another.

- It allows to spread the values of a collection into individual references.

Syntax:

var "B"];

var two = [one]; // two have 1 element

var two = [one, "C", "D"]; // two have 3 elements

var two = [...one, "C", "D"]; // two have 4 elements

Syntax:

var "B"];

var two = ["C", "D"];

var three = [...one, two]; // 3 elements

var three = [...one, ...two]; // 4 elements


var three = [one, two]; // 2 elements

- Array functions for finding elements

indexOf()

lastIndexOf()

find()

filter()

Object Type

- Object is used to keep all related data and logic together.

- "Alan kay" introduced the concept of object into computer programming


in early 1960's.

- Technically object is a key-value pair.

- Key is always string type and value can be any type.

Syntax:

var obj = {

"Key": value,

"Key": value

- Value can be

a) Primitive

b) Non Primitive

c) Function

Syntax:
var obj = {

"Key": number,

"Key": string,

"Key": new Array(),

"Key": { object },

"Key": function(){ }

- If object comprises of only data without any action (function) defined,


then it is referred as "JSON".

- JSON is JavaScript Object Notation, It is a format for data.

* JSON is light weight

* JSON is faster in transporting and rendering

* JSON doesn't require COM to Marshal [Converting object to binary &


vice versa]

* JSON can flow through firewalls.

* JSON is not infected by VIRUS.

Syntax:

"Name": "TV",

"Price": 34000.44,

"Stock": true,

"ShippedTo": ["Delhi", "Hyd"],

"Rating": { "Rate": 4.6, "Count": 4500}

- Object values are accessed with reference of "Key".

Syntax:
var product = { "Name": "TV", "Price":56000 };

[Link]; // returns TV

[Link]; // returns 56000

- You can assign new values if declared with "var or let".

[Link] = newname;

[Link] = newprice;

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<link rel="stylesheet"
href="../node_modules/bootstrap-icons/font/[Link]">

<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/[Link]">

<script>

var mobile = {

"title": "Apple iPhone 15 (Green, 128 GB)",

"price": 64999,

"rating": {"rate":4.6, "ratings":39755, "reviews":2187},

"offers": [
"Bank OfferGet ₹50 Instant Discount on first Flipkart UPI
transaction on order of ₹200 and aboveT&C",

"Bank Offer5% Cashback on Flipkart Axis Bank CardT&C",

"Bank Offer₹1000 off on Selected Bank Net Banking


TransactionT&C",

"Special PriceGet extra ₹12901 off (price inclusive of


cashback/coupon)T&C"

],

"image": "../public/images/[Link]"

function bodyload(){

[Link]("imgProduct").src = [Link];

[Link]("lblTitle").innerHTML = [Link];

[Link]("lblRating").innerHTML =
[Link];

[Link]("lblReviews").innerHTML = `<b>$
{[Link]()} ratings $
{[Link]()} reviews </b>`;

[Link]("lblPrice").innerHTML =
[Link]('en-in', {style:'currency', currency:'INR'});

[Link](function(offer){

var li = [Link]("li");

[Link] = "text-success bi bi-tag-fill my-2";

[Link] = `<span class="text-secondary">


${offer}</span>`;

[Link]("ul").appendChild(li);

})

</script>

</head>

<body class="container-fluid" >
<div class="mt-4 row">

<div class="col-3">

<img id="imgProduct" width="100%">

</div>

<div class="col-9">

<div class="h5" id="lblTitle"></div>

<div class="my-3">

<span class="bg-success p-1 rounded text-white"> <span


id="lblRating"></span> <span class="bi bi-star-fill"></span> </span>
<span id="lblReviews" class="text-secondary ms-3"></span>

</div>

<div class="my-4">

<div class="h3" id="lblPrice"></div>

</div>

<div class="my-3">

<ul class="list-unstyled">

</ul>

</div>

</div>

</div>

</body>

</html>

Class comments
Skip to main content

Google Classroom

Classroom

FullStack Web With React

7:30 PM - April 2024

JavaScript AJAXJavaScript AJAX

JavaScript AJAX

Sudhakar Sharma

8 Jul

Object Data Type

JSON - JavaScript Object Notation

Note:

- You can store data offline in a JSON file. So that you can access from any
page.

- JSON file must have the extension ".json"

- To access data from JSON file you need "Ajax Requests".

JavaScript Ajax

- Ajax is Asynchronous JavaScript And XML.

- Asynchronous allows to handle a task without blocking other tasks in


process.

- Ajax enables "Partial Postback". It can post specific portion of page


without submitting entire page.

- Ajax allows to add new content into page without reloading the complete
page.
- JavaScript is used as browser language to hand Async request.

- XML is used as medium to transport data in async request.

- In a browser the Ajax calls are managed by "XMLHttpRequest" object.

Step-1: Create a new XMLHttpRequest object

var http = new XMLHttpRequest();

Step-2: Configure the request by using "open()" method

[Link]("requestMethod", "url", async:boolean)

requestMethod => GET, POST, PUT, PATCH, DELETE

Async => It is default false.

Step-3: Send the request for processing

[Link]();

Setp-4: You have to check the readyState "onreadystatechange" function.

[Link] = function() {

if([Link] == 4)

}
readyState==1 => Initial

readyState==2 => Success

readyState==3 => Complete

readyState==4 => Response Ready

Step-5: Collect the response details using http object

[Link]

[Link]

Ex:

1. Create a new folder "data"

2. Add a new file "[Link]" with some content inside

3. Add HTML page

[Link]

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script>

function bodyload(){

var now = new Date();

[Link](`Page Loaded on : ${[Link]()}`);


}

function LoadClick(){

var now = new Date();

[Link](`Load Button Clicked at $


{[Link]()}`);

var http = new XMLHttpRequest();

[Link]("get", "../data/[Link]", true);

[Link]();

[Link] = function(){

if([Link]==4)

[Link]("container").innerHTML =
[Link];

</script>

</head>

<body >

<button Help</button>

<br><br>

<pre id="container">

</pre>

</body>

</html>
Note: You have to convert text into JSON by using "[Link]()"

Ex:

1. Data/[Link]

"title": "Apple iPhone 15 (Black, 128 GB)",

"price": 74999,

"rating": {"rate":4.6, "ratings":39755, "reviews":2187},

"offers": [

"Bank OfferGet ₹50 Instant Discount on first Flipkart UPI


transaction on order of ₹200 and aboveT&C",

"Bank Offer5% Cashback on Flipkart Axis Bank CardT&C",

"Bank Offer₹1000 off on Selected Bank Net Banking


TransactionT&C",

"Special PriceGet extra ₹12901 off (price inclusive of


cashback/coupon)T&C"

],

"image": "../public/images/[Link]"

2. [Link]

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>
<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/[Link]">

<link rel="stylesheet"
href="../node_modules/bootstrap-icons/font/[Link]">

<script>

function bodyload(){

var product = {};

var http = new XMLHttpRequest();

[Link]("get", "../data/[Link]", true);

[Link]();

[Link] = function(){

if([Link]==4){

product = [Link]([Link]);

[Link]("imgProduct").src =
[Link];

[Link]("lblTitle").innerHTML =
[Link];

[Link]("lblRating").innerHTML =
[Link];

[Link]("lblReviews").innerHTML = `$
{[Link]()} ratings $
{[Link]()} reviews`;

[Link]("lblPrice").innerHTML =
"&#8377;" + [Link]();

[Link](function(offer){

var li = [Link]("li");

[Link] = "bi bi-tag-fill text-success my-2";

[Link] = `<span class="text-secondary"> ${offer}


</span>`;
[Link]("lstOffers").appendChild(li);

})

</script>

</head>

<body class="container-fluid" >

<div class="row mt-3">

<div class="col-3">

<img width="100%" id="imgProduct">

</div>

<div class="col-9">

<div class="h4" id="lblTitle"></div>

<div class="my-3">

<span class="bg-success badge rounded p-2"> <span


id="lblRating"></span> <span class="bi bi-star-fill text-white"></span>
</span>

<span class="fw-bold text-secondary" id="lblReviews"></span>

</div>

<div class="my-3">

<div class="h3" id="lblPrice"></div>

</div>

<div class="my-3">

<ul class="list-unstyled" id="lstOffers">


</ul>

</div>

</div>

</div>

</body>

</html>

Class comments

Skip to main content

Google Classroom

Classroom

FullStack Web With React

7:30 PM - April 2024

API and FetchAPI and Fetch

API and Fetch

Sudhakar Sharma

9 Jul

XMLHttpRequest Issues

- It is not async by default.

- You have to explicitly configure async.

- It requires various parsing techniques to convert response data.

- It is not good in handling errors.


JavaScript "fetch()" Promise

- Promise is by default async.

- It provides good error handling methods.

- It returns every response in binary format.

- However it requires conversion of data.

Syntax:

fetch("url")

.then(function(){ on success })

.catch(function(){ on failure })

.finally(function(){ always })

- then() function returns a response from URL, which is in "binary format".

- You need another then() function that converts binary to required format.

Syntax:

.then(function(response){

return [Link]();

})

.then(function(data){

// use data

})

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">

<title>Document</title>

<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/[Link]">

<link rel="stylesheet"
href="../node_modules/bootstrap-icons/font/[Link]">

<script>

function bodyload(){

fetch("../data/[Link]")

.then(function(response){

return [Link]();

})

.then(function(product){

[Link]("imgProduct").src =
[Link];

[Link]("lblTitle").innerHTML =
[Link];

[Link]("lblRating").innerHTML =
[Link];

[Link]("lblReviews").innerHTML = `$
{[Link]()} ratings $
{[Link]()} reviews`;

[Link]("lblPrice").innerHTML =
"&#8377;" + [Link]();

[Link](function(offer){

var li = [Link]("li");

[Link] = "bi bi-tag-fill text-success my-2";

[Link] = `<span class="text-secondary"> ${offer}


</span>`;
[Link]("lstOffers").appendChild(li);

})

})

.catch(function(err){

[Link](err);

})

.finally(function(){

[Link](`Ajax Request Completed`);

})

</script>

</head>

<body class="container-fluid" >

<div class="row mt-3">

<div class="col-3">

<img width="100%" id="imgProduct">

</div>

<div class="col-9">

<div class="h4" id="lblTitle"></div>

<div class="my-3">

<span class="bg-success badge rounded p-2"> <span


id="lblRating"></span> <span class="bi bi-star-fill text-white"></span>
</span>

<span class="fw-bold text-secondary" id="lblReviews"></span>

</div>

<div class="my-3">

<div class="h3" id="lblPrice"></div>

</div>
<div class="my-3">

<ul class="list-unstyled" id="lstOffers">

</ul>

</div>

</div>

</div>

</body>

</html>

Object with functions

- Object comprises of data and functionality.

- Data is defined as property and action is defined as function.

- The members of object are accessed outside object using object


reference name and a key name.

- The members of object are accessed within object using "this" keyword.

Syntax:

Key : value,

Key : function(){ }

Ex:

<script>

var product = {

Name: "",

Price: 0,

Qty: 0,
Total : function(){

return [Link] * [Link];

},

Print: function(){

[Link](`Name=${[Link]}<br>Price=$
{[Link]}<br>Qty=${[Link]}<br>Total=${[Link]()}`)

[Link] = "Samsung TV";

[Link] = parseInt(prompt("Enter Price"));

[Link] = parseInt(prompt("Enter Quantity"));

[Link]();

</script>

Ex: Array of Objects

data/[Link]

"title": "Apple iPhone 15 (Black, 128 GB)",

"price": 74999,

"rating": {"rate":4.6, "ratings":39755, "reviews":2187},

"offers": [

"Bank OfferGet ₹50 Instant Discount on first Flipkart UPI


transaction on order of ₹200 and aboveT&C",

"Bank Offer5% Cashback on Flipkart Axis Bank CardT&C",

"Bank Offer₹1000 off on Selected Bank Net Banking


TransactionT&C",
"Special PriceGet extra ₹12901 off (price inclusive of
cashback/coupon)T&C"

],

"image": "../public/images/[Link]"

},

"title": "Apple iPhone 15 (Green, 256 GB)",

"price": 84999,

"rating": {"rate":4.8, "ratings":39755, "reviews":2187},

"offers": [

"Bank OfferGet ₹50 Instant Discount on first Flipkart UPI transaction


on order of ₹200 and aboveT&C",

"Bank Offer5% Cashback on Flipkart Axis Bank CardT&C",

"Bank Offer₹1000 off on Selected Bank Net Banking TransactionT&C",

"Special PriceGet extra ₹12901 off (price inclusive of


cashback/coupon)T&C"

],

"image": "../public/images/[Link]"

},

"title": "Apple iPhone 15 (Pink, 128 GB)",

"price": 74999,

"rating": {"rate":4.3, "ratings":29755, "reviews":1187},

"offers": [

"Bank OfferGet ₹50 Instant Discount on first Flipkart UPI transaction


on order of ₹200 and aboveT&C",

"Bank Offer5% Cashback on Flipkart Axis Bank CardT&C",

"Bank Offer₹1000 off on Selected Bank Net Banking TransactionT&C",

"Special PriceGet extra ₹12901 off (price inclusive of


cashback/coupon)T&C"

],
"image": "../public/images/[Link]"

[Link]

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<link rel="stylesheet"
href="../node_modules/bootstrap-icons/font/[Link]">

<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/[Link]">

<script>

function bodyload(){

fetch("../data/[Link]")

.then(function(response){

return [Link]();

})

.then(function(products){

[Link](function(product){

var div = [Link]("div");

[Link] = "row my-4 border border-1 m-4 p-2";


[Link] = `

<div class="col-2">

<img src=${[Link]} width="100%">

</div>

<div class="col-8">

<div class="h4">${[Link]}</div>

<div class="my-2">

<span class="badge bg-success p-1 rounded"> $


{[Link]} <span class="bi bi-star-fill"></span> </span>
<span class="ms-3 text-secondary fw-bold"> ${[Link]}
ratings & ${[Link]} reviews </span>

</div>

</div>

<div class="col-2">

<div class="h2"> &#8377; $


{[Link]()}</div>

</div>

`;

[Link]("section").appendChild(div);

})

})

</script>

</head>

<body class="container-fluid" >

<section>
</section>

</body>

</html>

[Link] - NASA API's

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>NASA</title>

<link rel="stylesheet"
href="../node_modules/bootstrap-icons/font/[Link]">

<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/[Link]">

<script>

function bodyload(){

fetch("[Link]
sol=1000&api_key=DEMO_KEY&quot;)

.then(function(response){

return [Link]();

})

.then(function(marsObject){

[Link](function(item){

var div = [Link]("div");


[Link] = "card m-2 p-2";

[Link] = "250px";

[Link] = `

<a href=${item.img_src} target="_blank"><img


class="card-img-top" src=${item.img_src} height="200"></a>

<div class="card-header">

<div class="fw-bold">${[Link]}</div>

</div>

<div class="card-body">

<dl>

<dt class="bi bi-camera"> Camera </dt>

<dd> ${[Link].full_name} </dd>

<dt class="bi bi-globe"> Rover </dt>

<dd> ${[Link]} </dd>

</dl>

</div>

`;

[Link]("section").appendChild(div);

})

})

</script>

</head>

<body class="container-fluid" >

<section class="d-flex flex-wrap">

</section>
</body>

</html>

Class comments

Skip to main content

Google Classroom

Classroom

FullStack Web With React

7:30 PM - April 2024

Object ManipulationObject Manipulation

Object Manipulation

Sudhakar Sharma

10 Jul

Object Manipulations:

1. How to access all keys from object?

A.

a) for..in

b) [Link]()
Syntax:

for (var key in object)

[Link](objectName).map()

Ex:

<script>

var product = {

id: 1,

title: "Samsung TV",

price: 45000.44,

stock : true

for(var key in product)

[Link](key + "<br>");

[Link](product).map(function(key){

[Link](`<li>${key}</li>`);

})

</script>

Ex:

<script>

var product = {

id: 1,

title: "Samsung TV",


price: 45000.44,

stock : true

for(var key in product)

[Link](`${key} - ${product[key]}<br>`);

[Link](product).map(function(key){

[Link](`<li>${key} : ${product[key]}</li>`);

})

</script>

2. How to get the count of keys in object?

A.

[Link](product).length

Ex:

[Link](`Total Count of Keys : $


{[Link](product).length}`);

3. How to delete a key?

A. By using JS "delete" operator

Syntax:

delete [Link];

delete [Link];

4. How to find a key?

A. By using "in" operator


Syntax:

"key" in objectName; // true if object have the given key

Ex:

<script>

var product = {

id: 1,

title: "Samsung TV",

price: 45000.44,

stock : true,

if("rating" in product){

[Link](`Rating : ${[Link]}`);

} else {

[Link](`Rating not available`);

</script>

5. How to hide a key in iterations?

A. By using JS "Symbol" data type.

Syntax:

var id = Symbol();

var product = {

[id] : 1,

title: "TV"

}
[Link](product[id]);

[Link](product).map(); // id is ignored

EX:

<script>

var id = Symbol();

var product = {

[id]: 1,

title: "Samsung TV",

price: 45000.44,

stock : true,

[Link](product).map(function(key){

[Link](`<li>${key}</li>`);

});

[Link](`Product Id : ${product[id]}`);

</script>

Note: In HTML form you can handle hidden fields by using input type
"hidden".

Syntax:

<input type="hidden" name="UserId" value="john_nit">

Ex:

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

</head>

<body>

<form>

<dl>

<dd><input type="hidden" name="UserId"


value="john_nit"></dd>

<dt>User Name</dt>

<dd><input type="text" name="UserName"


value="John"></dd>

<dt>Age</dt>

<dd><input type="number" name="Age" value="22"></dd>

</dl>

<button>Save</button>

</form>

</body>

</html>

6. How to know the data type of a value stored in key?

A. By using "typeof" operator.

Syntax:

typeof [Link] // returns data type

typeof object[key]

typeof product[price]
Ex: Nested Map()

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script>

var menu = [

{Category:"Electronics", Products: ["TV", "Mobile", "Watch"]},

{Category:"Fashion", Products: ["Kids", "Men", "Women"]}

];

function bodyload(){

[Link](function(item){

var ol_li = [Link]("li");

ol_li.innerHTML = [Link];

[Link](function(product){

var ul = [Link]("ul");

var ul_li = [Link]("li");

ul_li.innerHTML = product;

[Link](ul_li);

ol_li.appendChild(ul);

[Link]("ol").appendChild(ol_li);

})

})

}
</script>

</head>

<body >

<ol>

</ol>

</body>

</html>

Ex: Dropdown with optgroup

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script>

var menu = [

{Category:"Electronics", Products: ["TV", "Mobile", "Watch"]},

{Category:"Fashion", Products: ["Kids", "Men", "Women"]}

];

function bodyload(){

[Link](function(item){

var optgroup = [Link]("optgroup");

[Link] = [Link];

[Link](function(product){

var option = [Link]("option");


[Link] = product;

[Link] = product;

[Link](option);

[Link]("select").appendChild(optgroup);

})

})

</script>

</head>

<body >

<select>

</select>

</body>

</html>

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script>

var topics = [
{title: "HTML", description: "It is a markup language"},

{title: "CSS", description: "It defines tyles for HTML"}

function bodyload(){

[Link](function(topic){

var dt = [Link]("dt");

[Link] = [Link];

var dd = [Link]("dd");

[Link] = [Link];

[Link]("dl").appendChild(dt);

[Link]("dl").appendChild(dd);

})

</script>

</head>

<body >

<dl>

</dl>

</body>

</html>

Ex:

<script>
var products = [

{Name: "Nike Causals", Category:"Footwear"},

{Name: "Samsung TV", Category:"Electronics"},

{Name: "Woodland Boots", Category:"Footwear"},

{Name: "Jeans", Category: "Fashion"},

[Link](function(product){

return [Link]=="Footwear" ||
[Link]=="Fashion";

}).map(function(product){

[Link]([Link] + "<br>");

})

</script>

Ex:

<script>

var products = [

{Name: "Nike Causals", Category:"Footwear", Price: 5000.44},

{Name: "Samsung TV", Category:"Electronics", Price: 45000.44},

{Name: "Woodland Boots", Category:"Footwear", Price: 3400.33},

{Name: "Jeans", Category: "Fashion", Price: 2000.44},

{Name: "Lee Sneakers", Category:"Footwear", Price: 2400.33},

var total = 0;

[Link](function(product){

return [Link]=="Footwear";

}).map(function(product){
total= total + [Link];

[Link](`${[Link]} - ${[Link]}<br>`);

})

[Link]("Total Amount: " + total);

</script>

Class comments

Skip to main content

Google Classroom

Classroom

FullStack Web With React

7:30 PM - April 2024

FakestoreFakestore

Fakestore

Sudhakar Sharma

11 Jul

Fakestore API

[ [Link] ]

Routes:

Method Path Description

--------------------------------------------------------------------------------------------------------
------------
GET /products It returns all products [ { }, { } ]

GET /products/1 It returns specific id product { }

GET /products/category/jewellery It returns products of


specific category

[ { }, { } ]

GET /products/categories It returns all categories [ " " ]

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Fakestore</title>

<link rel="stylesheet"
href="../node_modules/bootstrap-icons/font/[Link]">

<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/[Link]">

<script
src="../node_modules/bootstrap/dist/js/[Link]"></script>

<script type="text/javascript">

function LoadCategories(){

fetch("[Link]

.then(function(response){
return [Link]();

})

.then(function(categories){

[Link]("all");

[Link](function(category){

var option = [Link]("option");

[Link] = [Link]();

[Link] = category;

[Link]("lstCategories").appendChild(option);

})

})

function LoadProducts(url){

[Link]("main").innerHTML="";

fetch(url)

.then(function(response){

return [Link]();

})

.then(function(products){

[Link](function(product){

var div = [Link]("div");

[Link] = "card p-2 m-2";

[Link] = "200px";

[Link] = `

<img src=${[Link]} class="card-img-top"


height="120">

<div class="card-header" style="height:130px">

${[Link]}
</div>

<div class="card-body">

<dl>

<dt>Price</dt>

<dd>${[Link]}</dd>

<dt>Rating</dt>

<dd>

<span class="badge bg-success p-1 rounded"> $


{[Link]} <span class="bi bi-star-fill"> </span> </span> $
{[Link]} ratings

</dd>

</dl>

</div>

<div class="card-footer">

<button >class="btn btn-warning w-100 bi bi-cart4"> Add to Cart </button>

</div>

`;

[Link]("main").appendChild(div);

})

})

function bodyload(){

LoadCategories();

LoadProducts("[Link]

GetCartCount();

function CategoryChanged(){
var categoryName =
[Link]("lstCategories").value;

if(categoryName==="all") {

LoadProducts("[Link]

} else {

LoadProducts(`[Link]
{categoryName}`);

function GetCartCount(){

[Link]("lblCount").innerHTML =
[Link];

var cartItems = [];

function AddClick(id)

fetch(`[Link]

.then(function(response){

return [Link]();

})

.then(function(product){

[Link](product);

alert(`${[Link]}\nAdded to Cart`);

GetCartCount();

})

}
function LoadCart(){

[Link]("tbody").innerHTML = "";

[Link](function(item){

var tr = [Link]("tr");

var tdTitle = [Link]("td");

var tdPhoto = [Link]("td");

var tdPrice = [Link]("td");

[Link] = [Link];

[Link] = `<img src=${[Link]} width="50"


height="50">`;

[Link] = [Link];

[Link](tdTitle);

[Link](tdPhoto);

[Link](tdPrice);

[Link]("tbody").appendChild(tr);

})

</script>

</head>

<body class="container-fluid" >

<header class="d-flex bg-light border border-1 justify-content-between


p-2 mt-2">

<div>

<button class="bi bi-justify btn btn-light" data-bs-


toggle="offcanvas" data-bs-target="#menu"> <span class="fs-5 fw-
bold">Fakestore.</span> </button>
</div>

<div class="fs-5">

<span class="mx-3"><a class="text-decoration-none link-dark"


href="javascript:LoadProducts('[Link]
e</a></span&gt;

<span class="mx-3"><a class="text-decoration-none link-dark"


href="javascript:LoadProducts('[Link]
/electronics')">Electronics</a></span&gt;

<span class="mx-3"><a class="text-decoration-none link-dark"


href="javascript:LoadProducts('[Link]
/jewelery')">Jewelery</a></span&gt;

<span class="mx-3"><a>Men's Clothing</a></span>

<span class="mx-3"><a>Women's Clothing</a></span>

</div>

<div>

<button data-bs-target="#cart" data-bs-


toggle="offcanvas" class="btn me-4 btn-warning bi bi-cart4 position-
relative"> <span id="lblCount" class="badge position-absolute bg-danger
rounded rounded-circle"></span> </button>

<div class="offcanvas offcanvas-end" id="cart">

<div class="offcanvas-header">

<h2>Your Cart Items</h2>

<button class="btn btn-close" data-bs-


dismiss="offcanvas"></button>

</div>

<div class="offcanvas-body">

<table class="table table-hover">

<thead>

<tr>

<th>Title</th>

<th>Photo</th>

<th>Price</th>
</tr>

</thead>

<tbody>

</tbody>

</table>

</div>

</div>

</div>

</header>

<section class="mt-4">

<nav class="offcanvas offcanvas-start" id="menu">

<div class="offcanvas-header">

<h2>Fakestore</h2>

<button class="btn btn-close" data-bs-


dismiss="offcanvas"></button>

</div>

<div class="offcanvas-body">

<label class="form-label fw-bold"> Select Category </label>

<div>

<select class="form-select"


id="lstCategories"></select>

</div>

</div>

</nav>

<main class="d-flex flex-wrap overflow-auto" style="height:


500px;">

</main>

</section>
</body>

</html>

Class comments

Skip to main content

Google Classroom

Classroom

FullStack Web With React

7:30 PM - April 2024

Date and Time Date and Time

Date and Time

Sudhakar Sharma

12 Jul

FAQ: What are the issues with object?

- It can have keys only of "string" type.

- It uses all explicit methods and operators for manipulation.

- It is slow in interactions.

Note: Object provides a schema for data. [structured data]

Map Type

- It is a key / value collection same as object.

- It provides schema less data.


- Key can be any type and value can be any type.

- It provides implicit methods for manipulation.

- It is faster when compared to object.

Syntax:

var ref = new Map();

.size : It returns the length of keys

.set() : It adds a new key and value

.get() : It can access the value with reference of key

.delete() : It removes a keys

.clear() : It removes all keys

.has() : It finds a key

.keys() : It returns all keys

.values() : It returns all values

.entries() : It returns both keys and values

Ex:

<script>

var topics = new Map();

[Link](1, "HTML is a markup language");

[Link]("CSS", "It configures styles");

[Link](true, "Stock Available");

[Link]("Cities", ["Delhi", "Hyd"]);

[Link](1001, {Name:"TV", Rating:4.3});

[Link]("CSS");

if([Link]("CSS")){
[Link]([Link]("CSS"));

} else {

[Link]("Can't find CSS<br>");

for(var item of [Link]()){

[Link](item + "<br>");

</script>

JavaScript Date & Time

- JavaScript provides Date() constructor to configure date and time values.

Syntax:

var dept = new Date(); // loads the current date and time into
memory

var dept = new Date("yy-mm-dd hrs:min:[Link]"); // stores


specific date

Ex:

var dept = new Date("2024-07-14 18:40:43.77");

- JavaScript provides various methods to access the date and time values

getHours() 0 to 23

getMinutes() 0 to 59

getSeconds() 0 to 59
getMilliSeconds() 0 to 99

getDate() 1 to 28, 29, 30, 31

getDay() weekday number 0=sunday, 1=Monday...

getMonth() month number 0=Jan, … 11=Dec

getFullYear() year number 4 digits 2024

getYear() [obsolete]

toDateString()

toTimeString()

toLocaleDateString()

toLocaleTimeString()

Ex:

<script>

var Departure = new Date("2024-07-15 14:50:31.64");

var weekdays = ["Sunday", "Monday", "Tue", "Wed", "Thur", "Friday",


"Saturday"];

var months = ["Jan", "Feb", "March", "April", "May", "June", "July",


"August", "Sep", "October", "Nov", "Dec"];

[Link](`${weekdays[[Link]()]} $
{[Link]()} ${months[[Link]()]}, $
{[Link]()}`)

</script>

Note: JavaScript supports various 3rd party Date Adapters to handle and
manipulate

Date and Time values.


a) moment

b) dayjs

c) luxon

etc...

- JavaScript provides various methods to set date and time.

setHours()

setMinutes()

setSeconds()

setMilliSeconds()

setDate()

setMonth()

setYear()

<script>

var Departure = new Date("2024-07-15 14:50:31.64");

var weekdays = ["Sunday", "Monday", "Tue", "Wed", "Thur", "Friday",


"Saturday"];

var months = ["Jan", "Feb", "March", "April", "May", "June", "July",


"August", "Sep", "October", "Nov", "Dec"];

[Link](12);

[Link](`${weekdays[[Link]()]} $
{[Link]()} ${months[[Link]()]}, $
{[Link]()}`)

</script>
Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script>

function bodyload(){

var now = new Date();

var pic = [Link]("pic");

[Link](10);

var hrs = [Link]();

var h1 = [Link]("h1");

if(hrs>=0 && hrs<=12){

[Link] = "Good Morning !";

[Link]="../public/images/[Link]";

} else if(hrs>12 && hrs<=16){

[Link] = "Good Afternoon";

[Link]="../public/images/[Link]";

} else{
[Link] = "Good Evening !";

</script>

</head>

<body >

<div align="center">

<img id="pic" width="100" height="100"/>

</div>

<h1 align="center"></h1>

</body>

</html>

JavaScript Timer Events

setTimeout()

clearTimeout()

setInterval()

clearInterval()

Syntax:

setInterval(function(){}, interval); // interval 1000ms = 1sec

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">
<title>Document</title>

<script>

function bodyload(){

setInterval(function(){

var now = new Date();

[Link]("h2").innerHTML =
[Link]();

}, 1000)

</script>

</head>

<body >

<font face="monospace"><h2></h2></font>

</body>

</html>

Class comments

Skip to main content

Google Classroom

Classroom

FullStack Web With React

7:30 PM - April 2024


Timer EventsTimer Events

Timer Events

Sudhakar Sharma

15 Jul

Timer Events

1. setTimeout()

- It is used to control "debounce".

- Bounce is a mechanism where the tasks are sent into process


immediately one after another.

- Debounce is a mechanism where you can keep the tasks wating in


memory and release after specific duration of time interval.

Syntax:

setTimeout(function(){ }, interval)

2. clearTimeout()

- It removes the task from memory before it is released into process.

Syntax:

clearTimeout(refName);

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">
<title>Document</title>

<script>

function msg1(){

[Link]("p").innerHTML = "Hello !";

function msg2(){

[Link]("p").innerHTML = "How are you?";

function msg3(){

[Link]("p").innerHTML = "Welcome to
JavaScript";

var m1, m2, m3;

function DisplayClick(){

m1 = setTimeout(msg1, 3000);

m2 = setTimeout(msg2, 6000);

m3 = setTimeout(msg3,10000);

function CancelClick(){

clearTimeout(m2);

</script>

</head>

<body>

<div align="center">

<button Messages</button>

<button Msg2</button>

<p></p>

</div>
</body>

</html>

3. setInterval()

- It loads the task into memory and releases a copy of task into process at
regular time intervals.

- It performs the given task repeatedly, until removed from memory.

Syntax:

setInterval(function(){ }, interval)

4. clearInterval()

- It removes the task from memory, which is set to execute at regular


intervals.

Syntax:

clearInterval(refName)

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script>

function bodyload(){

setInterval(function(){
var now = new Date();

[Link]("p").innerHTML =
[Link]();

}, 1000);

</script>

</head>

<body >

<p></p>

</body>

</html>

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<link rel="stylesheet"
href="../node_modules/bootstrap-icons/font/[Link]">

<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/[Link]">

<style>

progress {

width: 300px;

height: 30px;

}
@keyframes ZoomEffect

from {

width:50px;

height: 50px;

transform: rotate(0deg);

to {

width: 200px;

height: 300px;

transform: rotate(360deg);

</style>

<script>

var count = 1;

function StartProgress(){

count++;

[Link]("progress").value = count;

[Link]("lblStatus").innerHTML = `${count} %
Completed`;

if(count===100) {

[Link]("progressContainer").[Link] =
"none";

[Link]("imageContainer").[Link] =
"block";

[Link]("pic").[Link] =
"ZoomEffect";

[Link]("pic").[Link] =
"5000ms";
}

var thread;

function LoadClick(){

[Link]("btnContainer").[Link] = "none";

[Link]("progressContainer").[Link] =
"block"

thread = setInterval(StartProgress,50);

function PauseClick(){

clearInterval(thread);

[Link]("lblStatus").innerHTML = `${count} %
Completed [paused]`;

function PlayClick(){

thread = setInterval(StartProgress,100);

</script>

</head>

<body class="container-fluid d-flex justify-content-center align-items-


center" style="height:100vh">

<div class="text-center">

<div id="btnContainer">

<button class="btn btn-primary" >
Image</button>

</div>

<div id="progressContainer" style="display: none;" >

<progress id="progress" min="1" max="100"></progress>

<div>
<button class="btn btn-danger bi bi-
pause"></button>

<button class="btn btn-success bi bi-


play"></button>

</div>

<p id="lblStatus"></p>

</div>

<div id="imageContainer" style="display: none;">

<img id="pic" src="../public/images/[Link]"


width="200" height="300">

</div>

</div>

</body>

</html>

Ex: Slide Show

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<link rel="stylesheet"
href="../node_modules/bootstrap-icons/font/[Link]">

<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/[Link]">

<script>

function LoadProduct(id){

fetch(`[Link]
.then(function(response){

return [Link]();

})

.then(function(product){

[Link]("lblTitle").innerHTML =
[Link];

[Link]("imgPoster").src = [Link];

})

var count = 1;

function NextClick(){

count++;

LoadProduct(count);

function PrevClick(){

count--;

LoadProduct(count);

function LoadProductAuto(){

count++;

[Link]("rangePicker").value = count;

fetch(`[Link]

.then(function(response){

return [Link]();

})

.then(function(product){

[Link]("lblTitle").innerHTML =
[Link];

[Link]("imgPoster").src = [Link];
})

var thread;

function PlayClick(){

thread = setInterval(LoadProductAuto, 5000);

[Link]("lblStatus").innerHTML = "[Auto
Playing]";

function PauseClick(){

clearInterval(thread);

[Link]("lblStatus").innerHTML = "[Paused]";

function PickerChange(){

LoadProduct([Link]("rangePicker").value);

</script>

</head>

<body class="container-fluid d-flex justify-content-center"


>

<div class="card mt-3 p-2 w-50">

<div class="card-header text-center">

<div id="lblTitle"></div>

<div id="lblStatus"></div>

</div>

<div class="card-body row">

<div class="col-1 d-flex flex-column justify-content-center align-


items-center">

<button class="btn bi bi-chevron-


left"></button>

</div>
<div class="col-10">

<img width="100%" id="imgPoster" height="300">

<input type="range" >
id="rangePicker" min="1" max="20" class="form-range" value="1">

</div>

<div class="col-1 d-flex flex-column justify-content-center align-


items-center">

<button class="btn bi bi-chevron-


right"></button>

</div>

</div>

<div class="card-footer text-center">

<button class="btn btn-primary bi bi-


play"></button>

<button class="btn btn-danger bi bi-


pause"></button>

</div>

</div>

</body>

</html>

Class comments

Skip to main content

Google Classroom

Classroom

FullStack Web With React

7:30 PM - April 2024

JavaScript OperatorsJavaScript Operators


JavaScript Operators

Sudhakar Sharma

16 Jul

JavaScript Variables

JavaScript Data Types

a) Primitive

b) Non Primitive

Handling Date and Time

Timer Events

JavaScript Operators

- Operator is an object that evaluates a value.

- Data is kept in "operands".

- Logic is defined with "literal".

a + b; => a, b are operands

- Operators are classified into various categories based on the number of


operands they can handle.

a) Unary Operator

b) Binary Operator

c) Ternary Operator

Unary Operator:

- It can use only one operand.


x++ x=x+1

x-- x=x-1

Binary Operator:

- It can use only two operands.

- Left and right operands.

x+y+z

Ternary Operator:

- It can use 3 operands.

(condition)?true:false

- Operators are again classified into different categories based on the type
of value they return.

1. Arthematic operators

- It returns a number as result.

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus

** Exponent [[Link]()]

++ Increment

-- Decrement
2. Comparison Operators

== Equal

=== Identical Equal

!= Not Equal

!== Not Identical

> Greater than

>= Greater than or equal

< Less than

<= Less than or equal

3. Logical Operators

&& AND

|| OR

! NOT

var x = !true; // x = false

if(x!==undefined) // x is defined

4. Assignment Operators

+= Add and Assign

-= Subtract and Assign

*= Multiply and Assign

/= Divide and Assign

%= Modulus and Assign


Syntax:

var x = 10;

var y = 20;

x += y; // x = x + y x=30

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>KFC Online</title>

<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/[Link]">

<link rel="stylesheet"
href="../node_modules/bootstrap-icons/font/[Link]">

<script
src="../node_modules/bootstrap/dist/js/[Link]"></script>

<script type="text/javascript">

function SummaryClick(){

[Link]("lblName").innerHTML =
[Link]("txtName").value;

[Link]("lblMobile").innerHTML =
[Link]("txtMobile").value;

var mealName = "";

var adonName = "";

var mealCost = 0;

var adonCost = 0;
var total = 0;

var optBurger = [Link]("optBurger");

var optRoller = [Link]("optRoller");

var imgMeal = [Link]("imgMeal");

if([Link]) {

mealName = [Link];

mealCost = 120;

[Link] = "../public/images/[Link]";

if([Link]) {

mealName = [Link];

mealCost = 100;

[Link] = "../public/images/[Link]";

var optKrusher = [Link]("optKrusher");

var optWings = [Link]("optWings");

if([Link]) {

adonName += [Link] + "<br>";

adonCost = 40;

mealCost += adonCost;

if([Link]) {
adonName += [Link] + "<br>";

adonCost = 60;

mealCost += adonCost;

total = mealCost;

[Link]("lblMeal").innerHTML = mealName;

[Link]("lblAdon").innerHTML = adonName;

[Link]("lblTotal").innerHTML = `$
{[Link]('en-in', {style:'currency', currency:'INR'})}`;

</script>

</head>

<body class="container-fluid">

<header>

<img src="../public/images/[Link]" width="100%"


height="200">

</header>

<section>

<div class="accordion" id="kfc">

<div class="accordion-item">

<div class="accordion-header">

<button data-bs-target="#customer" data-bs-


toggle="collapse" class="btn btn-danger w-100">Customer
Details</button>

</div>

<div class="accordion-collapse collapse" id="customer" data-


bs-parent="#kfc">

<div class="accordion-body bg-danger text-white mt-2">


<dl>

<dt>Customer Name</dt>

<dd><input type="text" id="txtName" class="form-


control"></dd>

<dt>Mobile</dt>

<dd><input type="text" id="txtMobile" class="form-


control"></dd>

</dl>

</div>

</div>

</div>

<div class="accordion-item">

<div class="accordion-header">

<button data-bs-target="#meal" data-bs-toggle="collapse"


class="btn btn-danger w-100">Select Your Meal</button>

</div>

<div class="accordion-collapse collapse" id="meal" data-bs-


parent="#kfc">

<div class="accordion-body">

<div class="row">

<div class="col text-center">

<img src="../public/images/[Link]"
width="50%">

<div class="fs-5">

<input type="radio" id="optBurger"


value="OMG Burger" name="meal" class="form-check-input"> <label>
OMG Burger &#8377; 120/- </label>

</div>

</div>

<div class="col text-center">

<img src="../public/images/[Link]"
width="50%">
<div class="fs-5">

<input type="radio" name="meal"


id="optRoller" value="OMG Roller" class="form-check-input"> <label>
OMG Roller &#8377; 100/- </label>

</div>

</div>

</div>

</div>

</div>

</div>

<div class="accordion-item">

<div class="accordion-header">

<button data-bs-target="#adon" data-bs-toggle="collapse"


class="btn btn-danger w-100">Select AD-ON's</button>

</div>

<div class="accordion-collapse collapse" id="adon" data-bs-


parent="#kfc">

<div class="accordion-body">

<div class="row">

<div class="col fs-5 text-center">

<img src="../public/images/[Link]"
width="50%">

<div>

<input type="checkbox" id="optKrusher"


value="Krusher Brownie" class="form-check-input"> <label> Krusher
Brownie &#8377; 40/- </label>

</div>

</div>

<div class="col fs-5 text-center">

<img src="../public/images/[Link]"
width="50%">
<div>

<input type="checkbox" id="optWings"


value="HOT Wings 6pcs" class="form-check-input"> <label> Hot Wings
&#8377; 60/- </label>

</div>

</div>

</div>

</div>

</div>

</div>

<button data-bs-target="#summary" data-bs-toggle="modal"


class="btn btn-danger w-100" Order
Summary</button>

<div class="modal fade" id="summary">

<div class="modal-dialog">

<div class="modal-content">

<div class="modal-header">

<h3>Your Bill Summary</h3>

</div>

<div class="modal-body">

<div class="row">

<div class="col">

<dl>

<dt>Customer Name</dt>

<dd id="lblName"></dd>

<dt>Mobile</dt>

<dd id="lblMobile"></dd>

<dt>Meal Name</dt>

<dd id="lblMeal"></dd>

<dt>Ad ON's</dt>
<dd id="lblAdon"></dd>

<dt>Total Amount</dt>

<dd id="lblTotal"></dd>

</dl>

</div>

<div class="col">

<img id="imgMeal" width="100%">

</div>

</div>

</div>

<div class="modal-footer">

<button class="btn btn-warning" data-bs-


dismiss="modal">OK</button>

</div>

</div>

</div>

</div>

</div>

</section>

</body>

</html>

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>
<style>

ul {

list-style: none;

</style>

<script>

function SubmitClick(){

var courseName = "";

var courses = [Link]("Course");

for(var course of courses) {

if([Link]){

courseName += [Link] + "<br>";

[Link]("p").innerHTML = `Selected Courses :


<br> ${courseName}`;

</script>

</head>

<body>

<ul>

<li> <input type="checkbox" >
name="Course" value="UI Full Stack"> <label>UI Full Stack</label>
</li>

<li> <input type="checkbox" >
name="Course" value="Java"> <label>Java</label> </li>

<li> <input type="checkbox" >
name="Course" value=".NET"> <label>.NET</label> </li>

<li> <input type="checkbox" >
name="Course" value="Oracle"> <label>Oracle</label> </li>
</ul>

<button >

<p></p>

</body>

</html>

Class comments

Skip to main content

Google Classroom

Classroom

FullStack Web With React

7:30 PM - April 2024

Statements and Special OperatorsStatements and Special Operators

Statements and Special Operators

Sudhakar Sharma

17 Jul

Operators

- Arithematic

- Comparison

- Logical

- Assignment

- Bitwise operators
Special Operators

1. Ternary Operator ?:

2. new operator : Dynamic memory allocation operator.

3. typeof : It returns the data type of value stored in a reference.

4. in operator : It can search for a key in object and return Boolean


true/false.

"Price" in product; // true - false

5. delete : It can remove a key from object.

delete [Link];

6. of operator : It can read value of a property in an iterator.

for(var item of collection)

7. instanceof : It returns true if object is instance of specified class.

8. void : It discards the return of a function.


Syntax:

<a href="javascript:void()"> Home </a>

9. yield : It yields a value for function generator.

JavaScript Statements

- A statement is used to control the execution flow in a program.

- JavaScript statements are classified into

1. Selection Statements

if, else, switch, case, default

2. Looping Statements

for, while, do while

3. Iteration Statements

for..in, for..of

4. Jump Statements

break, continue, return

5. Exception Handling Statements

try, catch, throw, finally

Looping Control Statements:


- Looping is the process of executing a set of statements repeatedly until
the given condition is satisfied.

- You can create loops with

a) for

b) while

c) do while

The "for" loop:

- It is a looping control statement used by developer when it is sure about


number of iterations and iteration counter will not change dynamically.

- It requires an initialization, condition and counter.

Syntax:

for(initialization; condition; counter)

initialization : It specifies the starting point

condition : It decides the ending

counter : It defines how to proceed. [increment, decrement or


step]

Ex:

for(var i=1; i<=10; i++)

}
i++ => increments by 1

i=i+2 => increments by 2 [executes for every 2 step values]

Ex:

<script>

var msg = "Welcome to JavaScript";

var count = 0;

for(var i=0; i<[Link]; i++)

if([Link](i)=="e"){

count++;

[Link](`e occurred ${count} times`);

</script>

Ex:

<script>

// write a loop to count the number of ovels used in statement. [a, e, i ,


o , u]

var msg = "Welcome to JavaScript";

var count = 0;

for(var i=0; i<[Link]; i++)

if([Link](i)=="e" || [Link](i)=="a" || [Link](i)=="i" ||


[Link](i)=="o" || [Link](i)=="u"){

count++;

}
}

[Link](`Total Count of ovels ${count}`);

</script>

Tasks:

1. Write a program to count the occurrence of a string in message.

2. Write a program to find the word is palindrome or not.

3. Write a program to print all values greater than 40000 from an array of
numbers.

[2000, 57000, 53100, 34000]

4. Write a program to print array element in ordered list

["All", "Electronics", "Fashion"]

1. All

2. Electronics

3. Fashion

Class comments

Skip to main content

Google Classroom
Classroom

FullStack Web With React

7:30 PM - April 2024

Loops ContinueLoops Continue

Loops Continue

Sudhakar Sharma

18 Jul

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>

<script>

var categories = ["All", "Electronics", "Fashion"];

function bodyload(){

for(var i=0; i<[Link]; i++)

var li = [Link]("li");

[Link] = categories[i];

[Link]("ol").appendChild(li);

</script>

</head>

<body > <ol>

</ol>

</body>

</html>

Nested Loops:

- A loop can have outer iterations and inner iterations.

for(var i=0; i<=10; i++)

for(var j=0; j<4; j++)

Task:

values = [ [10, 20, 30] , [40, 50, 60] ];

Output:

10 20 30

40 50 60

Ex:

<script>

var values = [[10, 20, 30], [40, 50, 60]];


for(var i=0; i<[Link]; i++){

for(var j=0; j<values[i].length; j++)

[Link](values[i][j] + "&nbsp;&nbsp;&nbsp;");

[Link]("<br><br>");

</script>

Task: Write program to print pattern

var n = parseInt(prompt("Enter Number")); 5;

* *

* * *

* * * *

* * * * *

<script>

var n = parseInt(prompt("Enter Number"));

for(var i=1; i<=n; i++)

for(var j=1; j<=i; j++) {

[Link]("* &nbsp;&nbsp;&nbsp; ");

[Link]("<br>");

</script>
Ex: Reverse

<script>

var n = parseInt(prompt("Enter Number"));

for(var i=n; i>=1; i--)

for(var j=1; j<=i; j++) {

[Link]("* &nbsp;&nbsp;&nbsp; ");

[Link]("<br>");

</script>

Task : Write program to print pyramid of "*"

Write program to print diamond of "*"

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Document</title>
<script>

var data = [

{Category:"Electronics", Products:["Televisions", "Mobiles",


"Watches"]},

{Category:"Footwear", Products:["Casuals", "Sneakers", "Boots"]}

];

function bodyload(){

for(var i=0; i<[Link]; i++)

var ol_li = [Link]("li");

ol_li.innerHTML = data[i].Category;

for(var j=0; j<data[i].[Link]; j++)

var ul = [Link]("ul");

var ul_li = [Link]("li");

ul_li.innerHTML = data[i].Products[j];

[Link](ul_li);

ol_li.appendChild(ul);

[Link]("ol").appendChild(ol_li);

/*

[Link](function(item){

var ol_li = [Link]("li");

ol_li.innerHTML = [Link];

[Link](function(product){

var ul = [Link]("ul");

var ul_li = [Link]("li");


ul_li.innerHTML = product;

[Link](ul_li);

ol_li.appendChild(ul);

[Link]("ol").appendChild(ol_li);

})

})

*/

</script>

</head>

<body >

<ol>

</ol>

</body>

</html>

Task: Write a program to find factorial of given number?

var n = parseInt(prompt("Enter number")); 5

5 * 4 * 3 * 2 * 1;

Ex:

<script>

var n = parseInt(prompt("Enter Number"));

var fact = 1;

for(var i=1; i<=n; i++)

{
fact *= i;

[Link](`Factorial of ${n} is ${fact}`);

</script>

The While Loop:

- It is used when it is not sure about the number of iterations and iteration
counter may change dynamically.

- It executes the statements only when the given condition evaluates to


true.

Syntax:

while(condition)

statements;

counter;

The Do While loop:

- It similar to while but ensures that statements will execute at least once
even when the condition is false.

Syntax:

do {

statements;

counter;

} while(condition);

Ex:
<script>

var i = 11;

do {

[Link](i + "<br>");

i++;

}while(i<=10);

</script>

Class comments

Skip to main content

Google Classroom

Classroom

FullStack Web With React

7:30 PM - April 2024

Exception and JumpException and Jump

Exception and Jump

Sudhakar Sharma

19 Jul

Jump Statements

a) break

b) return

c) continue

- break : It terminates the block but continue the compiling process.


- return : It terminates the compiling, any thing after return is not
reachable to compiler.

- continue: It skips the counter and continue to next.

Ex:

1. data/[Link]

"UserId": "john"

},

"UserId": "john12"

},

"UserId": "john_nit"

},

"UserId": "david"

2. html page

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">
<title>Document</title>

<script>

function VerifyUser(){

var userid = [Link]("UserId").value;

var lblError = [Link]("lblError");

fetch("../data/[Link]")

.then(function(response){

return [Link]();

})

.then(function(users){

for(var user of users) {

if([Link]===userid){

[Link] = "User Id Taken - Try


another".fontcolor('red');

break;

} else {

[Link] = "User Id Available".fontcolor('green');

})

</script>

</head>

<body>

<h3>Register User</h3>

<dl>

<dt>User Id</dt>

<dd><input type="text" id="UserId"


> <dd id="lblError"></dd>

</dl>

</body>

</html>

Ex: Continue

<script>

fetch('[Link]

.then(function(response){

return [Link]();

})

.then(function(products){

for(var product of products)

if([Link]==="electronics" ||
[Link]==="men's clothing"){

continue;

[Link](`<li> ${[Link](0,15)}... [<b>$


{[Link]}</b>] </li>`)

})

</script>

Exception Handling Statements

- A computer program can have 2 types of errors.

a) Compile Time Errors

b) Runtime Errors
- Compile Time Errors are syntactical errors. A program fails to execute
due to compile time errors.

- Runtime errors occurs when compiler is not sure about the actions
performed.

A program compiles and executes successfully but fails to understand


certain actions.

- Runtime errors lead to "Abnormal Termination" of application.

- To avoid abnormal termination you need "Exception handling".

- JavaScript exception handling statements

a) try : monitoring block

b) catch : handler block

c) throw : explicitly throws exception

d) finally : executes every time.

Syntax:

try

statements to execute;

catch(error)

report error;

finally
{

statements to execute always

EX:

<script>

try

var a = parseInt(prompt("Enter number-1"));

var b = parseInt(prompt("Enter number-2"));

if(b==0){

throw "Can't Divide By Zero";

if(b>a){

throw "Can't divide by greater number";

var c = a / b;

[Link](`Division=${c}<br>`);

catch(error){

[Link](`${error}<br>`);

finally {

[Link](`End of Program`);

</script>

Summary:

1. Selection Statements
2. Looping Statements

3. Iteration Statements

4. Jump Statements

5. Exception Handling Statements

Task : Design a program that converts number to words.

Enter Number : 450

Output: Four Hundred Fifty

Summary

- Variables

- Data Types

- Operators

- Statements

Functions

Class comments

Skip to main content

Google Classroom

Classroom

FullStack Web With React

7:30 PM - April 2024

Functions in JavaScriptFunctions in JavaScript


Functions in JavaScript

Sudhakar Sharma

20 Jul

Functions in JavaScript

- Function is used to "refactor" code.

- Refactoring is the process of extracting a set of statements and


encapsulating into a code block.

- You can refactor into function, loop, condition etc.

- You can easily reuse and extend the functionality.

Function Configuration:

- You can configure function with 2 techniques

a) Function Declaration

b) Function Expression

- Function Declaration configures memory where specific functionality is


defined.

It perform the same every time.

Syntax:

function Name()

- Function Expression allows to configure a memory to handle function,


the function can change according to state and situation.

- An expression can assign new functionality into the memory.


Syntax:

var name = function() {

- Expression uses "Anonymous" function, which is access using IIFE


pattern.

[Immediately Invoked Function Expression]

Ex:

<script>

var password = prompt("Enter Password");

var result;

if(password==="admin") {

result = function(){

[Link]("Login Success..");

} else {

result = function(){

[Link]("Invalid Password<br><a
href='[Link]'>Try Again</a>")

result();

</script>

Function Structure:

- Every function configuration comprises of

a) Declaration

b) Signature
c) Definition

- Declaration defines function keyword and name with parameters.

function Name(params) => declaration

- Signature defines the name and parameters

Name(params) => signature

- Definition specifies the functionality to perform

=> definition

Parameterized Functions

- A function can be parameter less or parameterized.

- Parameter allows to modify the function definition.

- A parameterized function can change the definition according to


situation.

Syntax:

function Name(param) => param is formal parameter

Name(value); => value is actual parameter


- The parameter defined in function declaration is known as "Formal
Parameter".

- Formal Parameter is just a memory reference name.

- The parameter defined while calling function is known as "Actual


Parameter".

- It is the actual value stored in formal reference.

param = value;

Ex:

<script>

function PrintNumbers(howMany)

for(var i=1; i<=howMany; i++)

[Link](i + "<br>");

PrintNumbers(5);

PrintNumbers(10);

</script>

- Parameter can handle any type of data

a) Primitive

b) Non Primitive

c) Function Type

Ex:

<script>

function PrintList(collection)
{

for(var item of collection){

[Link](item + "<br>");

PrintList(["All", "Fashion", "Footwear"]);

PrintList([10, 20, 30]);

function GetObjectData(obj)

for(var property in obj)

[Link](`${property}:${obj[property]}<br>`);

let product = {Name:"TV", Price:45000.55, Stock:true};

GetObjectData(product);

GetObjectData({Id:1, Name:'John', Salary: 140000.44,


Designation:'Manager'});

</script>

Ex:

<script>

function PrintList(collection)

for(var item of collection){

[Link](item + "<br>");

}
PrintList(["All", "Fashion", "Footwear"]);

PrintList([10, 20, 30]);

function GetObjectData(obj)

for(var property in obj)

[Link](`${property}:${obj[property]}<br>`);

let product = {Name:"TV", Price:45000.55, Stock:true};

GetObjectData(product);

GetObjectData({Id:1, Name:'John', Salary: 140000.44,


Designation:'Manager'});

function Fetch(fetchData){

fetchData();

Fetch(function(){ [Link]("Data Fetched from Server...") });

</script>

- A function can have multiple parameters.

- Every parameter is required and have order dependency.

Syntax:

function Product(id, name, price)

}
Product(1, "TV", 45000);

Product(1, "Mobile"); id=1, name=Mobile, price=undefined

Product(1, 45000); id=1, name=45000, price=undefined

Product("Mobile", 45000); id=Mobile, Name=45000

Ex:

<script>

function Product(id, name, price, rating)

if(rating)

[Link](`Id=${id}<br>Name=${name}<br>Price=$
{price}<br>Rating=${rating}`);

} else {

[Link](`Id=${id}<br>Name=${name}<br>Price=$
{price}`);

Product(1, "", 45000.44);

</script>

Task: Write a function that takes start and end parameters so that it can
print the number between start and end range.

function PrintNumbers(start, end)

for(var i=start; i<=end; i++) {

}
PrintNumbers(5, 10); => 5, 6, 7, 8, 9, 10

PrintNumbers(10, 40);

Ex:

<script>

function PrintNumber(start, end) {

for(var i=start; i<=end; i++)

[Link](i +"<br>");

PrintNumber(15,40);

</script>

- ECMA standards allow 1024 parameters for a function.

- JavaScript allows "rest" parameters.

- A single rest parameter can handle multiple arguments.

- A rest parameter is defined using "...paramName"

Syntax:

function Name(...paramName)

Name(1, "TV", 45000.44, 4.3);

- Rest parameter is Array type


...paramName[0] = 1,

...paramName[1] = "TV"

Ex:

<script>

function Product(...details)

var [id, name, price, rating] = details;

[Link](`Id=${id}<br>Name=${name}<br>Price=$
{price}<br>Rating=${rating}`);

Product(1, "Mobile", 56000.44, 4.2);

</script>

- Every function can have only one rest parameter.

- It must be the last parameter in formal list.

Ex:

<script>

function Product(title, ...details)

var [id, name, price, rating] = details;

[Link](`<h2>${title}</h2>Id=${id}<br>Name=$
{name}<br>Price=${price}<br>Rating=${rating}`);

Product("Product Details", 1, "Mobile", 56000.44, 4.2);

</script>

Class comments
Skip to main content

Google Classroom

Classroom

FullStack Web With React

7:30 PM - April 2024

JavaScript Functions ContinueJavaScript Functions Continue

JavaScript Functions Continue

Sudhakar Sharma

22nd july

Function Parameters

Rest Parameters

Spread Operator

- It can spread on value into multiple parameters.

Syntax:

function Name(p1, p2, p3)

Name(...[v1, v2, v3]); p1=v1, p2=v3, p3=v3

Name([v1, v2, v3]); p1= [v1,v2,v3], p2=undefined,


p3=undefined

FAQ: What is difference between rest and spread operator?

Ans: Rest is one formal parameter accessing multiple actual values.

Spread is one actual value spreads into multiple formal parameters.


Ex:

<script>

function Details(id, name, price)

[Link](`Id=${id}<br>Name=${name}<br>Price=$
{price}`);

Details(...[101, "TV", 45000.44]);

</script>

Function with Return

- Function is by default "void" type.

- "Void" is used to discard the memory allocated for function.

- Hence the function memory is not accessible outside after the function
ends.

- "Return" is a jump statement, which can keep the memory of function


alive as it will not allows to end the function.

- The data of function can be stored in function memory and accessed


from any location.

- Function with return can perform the functionality and store the data
globally.

Syntax:

function Name()

return value;

}
Name() = value;

Ex:

<script>

function Addition(x, y){

return x + y;

function PrintResult(){

[Link](`Addition=${Addition(30, 50)}`);

PrintResult();

</script>

- A function can have various return types

a) Primitive

b) Non-Primitive

c) Function

Ex:

<script>

function GetProducts(){

var products = [{title: "TV"}, {title: "Mobile"}, {title: "Nike"}];

return products;

GetProducts().map(function(product){

[Link]([Link] + "<br>");

})
</script>

Ex:

<script>

function Login(){

return function(){

[Link](`

<h2>User Login</h2>

<dl>

<dt>User Name</dt>

<dd><input type="text"> </dd>

</dl>

`);

Login()();

</script>

- A function can have multiple returns, It uses a conditional rendering


mechanism to render various return value according to the state and
situation.

Syntax:

function Name(param)

if(condition)

return function(){ }
}

else {

return function(){ }

Ex:

<script>

function Component(name){

if(name==="login"){

return function(){

[Link](`

<h2>User Login</h2>

<dl>

<dt>User Name</dt>

<dd><input type="text"> </dd>

</dl>

<button>Login</button>

`);

} else if(name==="register") {

return function(){

[Link](`

<h2>Register</h2>

<dl>

<dt>Email</dt>

<dd><input type="email"> </dd>

</dl>
<button>Register</button>

`);

} else {

return function(){

[Link]("You can import only login or register


components");

Component("register")();

</script>

FAQ: Can a void function have "return" keyword?

Ans: Yes.

FAQ: What is the use of return in void function?

Ans: It is used to terminate the function. It configure un-reachable code.

Ex:

<script>

function PrintStatement(){

[Link]("Statement-1<br>");

[Link]("Statement-2<br>");

[Link]("Statement-3<br>");

[Link]("Statement-4<br>");
return;

[Link]("Statement-5<br>");

PrintStatement();

</script>

Note: "return" is used to configure stubs, which can terminate the


program before reaching the next level of statements.

Function Closure

- Closure is a mechanism implemented for functions.

- In closure the members of outer function are directly accessible to inner


functions.

- How ever the members of inner function are not accessible to outer.

Syntax:

function outer()

// outer members;

function inner(){

// inner members;

// outer members;

// inner members are not accessible

Ex:

<script>

function Outer(){
var x = 10;

function Inner(){

var y = 20;

return x + y;

[Link]("Z=" + Inner());

Outer();

</script>

Function Call back

- Call back is a mechanism where a function executes according to state


and situation.

- It is not called explicitly.

- Call backs will be implicit.

- Call back uses anonymous function.

- Call back uses "sync" technique.

- "Sync" is blocking technique where it will not allow any another task to
perform until it completes the given task.

Ex:

<script>

function FetchData(url, success, failure)

if(url==="[Link] {

success();

} else {

failure();

}
}

FetchData(prompt("Enter URL"), function(){

[Link]("Data Fetched Successfully..");

}, function(){

[Link]("Invalid URL");

})

</script>

Class comments

You might also like