0% found this document useful (0 votes)
7 views

JavaScript Unit 1

Uploaded by

Agam Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

JavaScript Unit 1

Uploaded by

Agam Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 90

JavaScript(Unit 1)

JavaScript
Modules
Export & Import
const
let
var
arrow functions
Classes
Properties
Methods
Spread & Rest Operator
Destructuring Outcome:
Array functions Understand advanced javascript concepts
JavaScript

JavaScript is a dynamic computer programming language. It is lightweight


and most commonly used as a part of web pages, whose implementations
allow client-side script to interact with the user and make dynamic pages.
It is an interpreted programming language with object-oriented
capabilities.

Client-side JavaScript

Client-side JavaScript is the most common form of the language. The


script should be included in or referenced by an HTML document for the
code to be interpreted by the browser.

It means that a web page need not be a static HTML, but can include
programs that interact with the user, control the browser, and dynamically
create HTML content.
How to use Java Script

-It is available in your browser


-node
Use editor for the same(VS Code)
-Code runner must be installed from extensions(VS Code)
-Live Server must be installed from extensions(VS Code)

Or
jsbin.com
JavaScript Comments

• Single line comments


// Change heading:

• Multi Line Comments


/*Hi Welcome
To your first class */
JavaScript Variables

• Variables used to store data


• We can use variable by using
• let (introduced in ES6 2015)
• Const
• Var (for mostly older browsers) e.g.
• Using nothing

e.g. const a = 10;

Var a=20 const b = 10;

let a=25 let c = a + b;

Const a=30

a=40
JavaScript Variables

• If you will declare a variable with var it will keep the previous
value(if no value is given now)
• e.g. var a=‘apple’
var a;

• But the above statement is not valid with let and const
• We can directly add number or strings in variable
• e.g. let a=2+3+5 or let b= “abc” + ” “ + ”def”

• What will be the output of let a =5 +5+’3’ and let a=‘5’+5+3?


JavaScript Variables

• let have block scope


• { let x=10}
• X can not be used outside that block
• But the above thing is not valid for var
• We can initialize variable first and can declare later on in case of
var (is called hoisting)
• ab=10
• var ab
• We can not initialize variable first and can declare later on in case
of let (is called hoisting)
• ab=10
• let ab (will give error)
JavaScript Variables

• const have block scope


• { const x=10}
• X can not be used outside that block
• const can not be reassigned
• const can not be redeclared
• Use const where you know your value is not going to be change
• e.g. with Array, with object, with function, with regexp
• const defines a constant reference to a value
• You can change the values of const array and properties of const
object
JavaScript Identifiers

Identifiers are the unique names given to variables with some


restrictions

•Names can contain letters, digits, underscores, and dollar signs.

•Names must begin with a letter.

•Names can also begin with $ and _

•Names are case sensitive (a and A are different variables).

•Reserved words (like JavaScript keywords) cannot be used as names.


JavaScript Functions

• Block of code designed to do a specific task


• let a = myFunction(5, 5); // Function is called, return value will
end up in a
function myFunction(x, y) {
return x* y; // Function returns the product of x and y
}
• Reuse Code

• Task to make a arrow function for finding factorial of a


number.
JavaScript Arrow Functions

• For shorter function syntax


• let myFunction = (x, y) => a * b;
• myFunction(10,20);
• Const hello = () => "Hello World!";( by default it return the
value)
• Arrow functions with parameters [hello = (val) => "Hello " + val;]
• If we have only one parameter then we can skip parentheses
[hello = val => "Hello " + val;]

• Task to make a arrow function for finding factorial of a number.


JavaScript Modules

You can easily break up your code into separate files. Modules
uses import and export statements.

Export : Named export and default export


Create a *.js file and
const message = () => {
export const name = “Rohit"; const name = “Rohit";
export const age = 20; const age = 20;
or return name + ' is ' + age + 'years
const name = “Rohit"; old.';
const age = 20; };
export {name, age}; export default message;
JavaScript Modules
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Modules</h1>

<p id="demo"></p>

<script type="module">
import { name, age } from "./first.js";

let text = "My name is " + name + ", I am " + age + ".";

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>
JavaScript Modules
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Modules</h1>

<p id="demo"></p>

<script type="module">
import message from "./default.js";

document.getElementById("demo").innerHTML = message();

</script>

</body>
</html>
JavaScript Modules(How to access multiple)
JavaScript Classes

• Classes are blueprints for objects


• Contains property(are like variables) and methods(are like
functions)

class apple {
constructor(name, price) {
this.name = name;
this.price = price;
}
}
It is not an object but template for JavaScript objects.
You can use classes for creating objects
let apple1 = new apple(“A", 200);
let apple2 = new apple(“B", 100);
JavaScript Class Methods

• Constructor method have the same name as constructor


• Executed automatically when the object is created
• Used to initialize object properties
• Class methods are created after the constructor method

• Task to create a class for printing your name by using


constructor and method.
JavaScript Class Example

• Constructor method have the same name as constructor


• Executed automatically when the object is created
• Used to initialize object properties
• Class methods are created after the constructor method

• Task to create a class for printing your name by using


constructor and method.
JavaScript Class Properties and Methods

• Constructor method have the same name as constructor


• Executed automatically when the object is created
• Used to initialize object properties
• Class methods are created after the constructor method

• Task to create a class for printing your name by using


constructor and method.
JavaScript Spread and Rest Operator (…)

• Split up array elements or object parameters


JavaScript Spread (…)
JavaScript Spread (…)
JavaScript Spread (…)
JavaScript Rest Operator (…)
JavaScript (Destructuring)

• Easily extract array elements or object properties and store them in variables.
JavaScript (Destructuring)
JavaScript Arrays

• To hold many values under a single name


const array_name = [item1, item2, ...];
const fruits = [“apple", “orange", “guava"];
OR
const array_name= [];
cars[0]= “apple";
cars[1]= “orange";
cars[2]= “guava";
OR
const cars = new Array(“apple", “orange", “guava”);
JavaScript Arrays

• Access Array elements


• Array_name[0]
• Change array elements
• Array_name[0] = “Mango";
• Array Methods
• Array_name.length
• Array_name.sort()
• Access last element by [length-1]
• Arrays are objects (typeof operator return object)
JavaScript Arrays

• Looping array functions


• const fruit = [‘Apple’, ‘Orange’, ‘Banana’, ‘Mango’];
let len = fruit.length;
for (let i = 0; i < len; i++) {
fruit[i] ; }
• Foreach Loop
• const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.forEach(myFunction);
function myFunction(value) {
value ; }
• Adding Array Elements
• const fruit = ["Banana", "Orange", "Apple"];
fruit.push("Lemon");
JavaScript Arrays

• Adding Array Elements


• <button onclick="myFunction()">Try it</button>
• <p id="demo"></p>
• <script>
• const fruits = ["Banana", "Orange", "Apple"];
• document.getElementById("demo").innerHTML = fruits;
• function myFunction() {
• fruits[fruits.length] = "Lemon";
• document.getElementById("demo").innerHTML = fruits;
• }
• </script>

• Adding elements with high indexes can create undefined


"holes" in an array:
JavaScript Arrays

• A Common Error
const points = [40]; //creates array with one element
• is not the same as:
const points = new Array(40); //creates array with 40
elements

• How to Recognize an Array


let type = typeof fruit;
Array.isArray(fruit);
JavaScript Arrays
JavaScript Arrays Methods
toString()
Join()
Pop()
Push()
Shift()
unshift()
Delete
Concat() (for two arrays and three arrays)
Splice()
Slice()
Sort()
Reverse()
JavaScript Array Map Method
JavaScript Array Map Method
JavaScript Array Map Method
JavaScript Array Map Method
JavaScript Array Map Method
JavaScript Syntax
JavaScript can be implemented using JavaScript statements that are placed within
the <script>... </script> HTML tags in a web page.

<script ...>
JavaScript code
</script>

JavaScript with type attribute:

<script type="text/javascript">
JavaScript code
</script>

Where to place JavaScript?


 JavaScript can be placed in the <head> section of an HTML page.
 JavaScript can be placed in the <body> section of an HTML page.
 JavaScript can also be placed in external files and then linked to HTML Page.
JavaScript in the Head Section

<!DOCTYPE html>
<html>
<head>
<script>
function abc()
{
document.getElementById("ab").innerHTML = "LPU expects some
better placements out of you";
}
</script>
</head>
<body>
<p id="ab">Welcome to LPU</p>
<input type="submit" onclick="abc()">
</body>
</html>
JavaScript in Body Section

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="abc">Welcome to LPU</p>
<input type="submit" onclick="abc()">
<script>
function abc()
{
document.getElementById("abc").innerHTML = "LPU expects some better
placements out of you";
}
</script>
</body>
</html>

NB: It is a good idea to place scripts at the bottom of the <body> element.
This can improve page load, because script compilation can slow down the display.
External JavaScript (b.js)

. function abc()
{
document.getElementById("abc").innerHTML = "LPU expects some better
placements out of you";
}

a.html

<!DOCTYPE html>
<html>
<head>
<script src=“b.js"></script>
</head>
<body>
<p id="abc">Welcome to LPU</p>
<input type="submit" onclick="abc()">
</body>
</html>
JavaScript Dialog Boxes

JavaScript supports three important types of dialog boxes. These dialog


boxes can be used to raise and alert, or to get confirmation on any input or
to have a kind of input from the users.

Alert Dialog Box

An alert dialog box is mostly used to give a warning message to the users.
For example, if one input field requires to enter some text but the user does
not provide any input, then as a part of validation, you can use an alert box
to give a warning message.

Nonetheless, an alert box can still be used for friendlier messages. Alert
box gives only one button "OK" to select and proceed.
Example

<!DOCTYPE html>
<html>
<head>
<script>
function abc()
{
window.alert("Welcome to LPU");
document.write("HTML Alert Dialog Box Example");
}
</script>
</head>
<body>
<input type="submit" onclick="abc()">
</body>
</html>
Confirmation Dialog Box

A confirmation dialog box is mostly used to take user's consent on any option.
It displays a dialog box with two buttons: OK and Cancel.

If the user clicks on the OK button, the window method confirm() will return
true. If the user clicks on the Cancel button, then confirm() returns false.
Example

<!DOCTYPE html>
<html>
<head>
<script>
function abc()
{
var retVal = confirm("Do you want to continue ?");
if( retVal == true ){
document.write ("User wants to continue!");
return true;
}
else{
document.write ("User does not want to continue!");
return false;
}
}
</script>
</head>
<body>
<input type="submit" onclick="abc()">
</body>
</html>
Prompt Dialog Box

The prompt dialog box is very useful when you want to pop-up a text box to
get user input. Thus, it enables you to interact with the user. The user needs to
fill in the field and then click OK.

This dialog box is displayed using a method called prompt() which takes two
parameters:
(i) a label which you want to display in the text box
(ii) a default string to display in the text box.

This dialog box has two buttons: OK and Cancel. If the user clicks the OK
button, the window method prompt() will return the entered value from the
text box. If the user clicks the Cancel button, the window
method prompt()returns null.
Example

<!DOCTYPE html>
<html>
<head>
<script>
function abc()
{
var retVal = prompt("Enter your name : ", "your name here");
document.write("You have entered : " + retVal);

}
</script>
</head>
<body>
<input type="submit" onclick="abc()">
</body>
</html>
Events in JavaScript

JavaScript's interaction with HTML is handled through events that occur when the
user or the browser manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click
too is an event. Other examples include events like pressing any key, closing a
window, resizing a window, etc.

onclick Event

This is the most frequently used event type which occurs when a user clicks the
left button of his mouse. You can put your validation, warning etc., against this
event type.
Example

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">

function abc() {
alert("Welcome to the School of CSE")
}
</script>
</head>
<body>
<form>
<input type="button" onclick="abc()" value="Test" />
</form>

</body>
</html>
onsubmit Event
onsubmit is an event that occurs when you try to submit a form. You can put your form
validation against this event type.

Example

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validate() {
alert("Validated");
}
</script>
</head>
<body>
<form method="POST" onsubmit="return validate()">
<input type="submit" value="Submit" >
</form>
</body>
</html>
onmouseover and onmouseout Events

These two event types will help you create nice effects with images or even with text as well.
The onmouseover event triggers when you bring your mouse over any element and
the onmouseout triggers when you move your mouse out from that element.

Example:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function over() {
document.write ("Mouse Over");
}
</script>
</head>
<body>
<div onmouseover="over()">
Hello LPU
</div>
</body>
</html>
Example

<!DOCTYPE html>
<html>
<head>

<script type="text/javascript">
function out()
{
document.write ("Mouse Out");
}
</script>
</head>
<body>
<div onmouseout="out()">
Hello LPU
</div>
</body>
</html>
onkeypress Event
The onkeypress event occurs when the user presses a key (on the keyboard).

Example

<!DOCTYPE html>
<html>
<head>

<script type="text/javascript">

function abc() {
document.write ("Pressed");
}
</script>
</head>
<body>
<input type="text" onkeypress="abc()">
</body>
</html>
onload Event
The onload event occurs when an object has been loaded. onload is most often used
within the <body> element to execute a script once a web page has completely loaded all
content (including images, script files, CSS files, etc.).
Example

<!DOCTYPE html>
<html>
<head>

<script type="text/javascript">

function abc() {
document.write ("Example of Text on Page Loading");
}
</script>
</head>
<body onload="abc()">
</body>
</html>
JavaScript Form Validation

Form validation normally used to occur at the server, after the client had
entered all the necessary data and then pressed the Submit button.

If the data entered by a client was incorrect or was simply missing, the server
would have to send all the data back to the client and request that the form be
resubmitted with correct information. This was really a lengthy process which
used to put a lot of burden on the server.

JavaScript provides a way to validate form's data on the client's computer


before sending it to the web server.
Example1: Matching Password and Confirm Password

<script type="text/javascript">
function CanSubmit() {
//alert("ok");
var pwd = document.forms[0].txtPassword.value
var cpwd = document.forms[0].txtConfirmPassword.value
if (pwd == cpwd)
return true;
else {
alert("Please make sure that Password and Confirm Password are Same");
return false;
}
}
</script>

<form action="" method="post" onsubmit ="return CanSubmit()">


Password: <input type="password" name="txtPassword" value="" /> <br />
ConfirmPassword: <input type="password" name="txtConfirmPassword" value="" />
<br />
<input type="submit" name="btnSubmit" value="Submit" />
</form>
Example 2: Providing alert before data will be deleted

function CanDelete()
{
return confirm("Are you Sure to delete your Data");
}

<input type="submit" name="btnDelete" value="Delete" onclick ="return CanDelete()" /


Example 3: Validate Textboxes for any data in arithmetic operations

function ValidateMathFunction()
{
var FN = document.forms[1].txtFN.value;
var SN = document.forms[1].txtSN.value;
if (FN == "" || SN == "") {
alert("Please ensure that data is inserted in both textboxes");
return false;
}
else
return true;
}
<form action="/" method="post" onsubmit="return ValidateMathFunction()">
Enter First Number <input type="text" name="txtFN" value="" /> <br />
Enter Second Number <input type="text" name="txtSN" value="" /><br />
<input type="submit" name="btnAdd" value="+" />
<input type="submit" name="btnSub" value="-" />
<input type="submit" name="btnMul" value="*" />
<input type="submit" name="btnDel" value="/" />
</form>
Example 4 Denominator cant be zero

function CheckDenominator() {
var SN = document.forms[1].txtSN.value;
if (SN == 0) {
alert("Denominator cant be zero");
return false;
}
else
return true;
}

<input type="submit" name="btnDel" value="/" onclick="return CheckDenominator()"/>


Example 5 Whether the values entered in textboxes are numbers or not?

function ValidateMathFunction()
{
var FN = document.forms[1].txtFN.value;
var SN = document.forms[1].txtSN.value;
if (FN == "" || SN == ""|| isNaN(FN)||isNaN(SN)) {
alert("Please ensure that valid data is inserted in both textboxes");
return false;
}
else
return true;
}
Example 6 Validating Email using Regular Expressions

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validateEmail()
{
var emailTextBox = document.getElementById("txtEmail");
var email = emailTextBox.value;
var emailRegEx = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".
+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+
[a-zA-Z]{2,}))$/;

emailTextBox.style.color = "white";
if (emailRegEx.test(email))
{
emailTextBox.style.backgroundColor = "green";
}
else
{
emailTextBox.style.backgroundColor = "red";
}
}
</script>

</head>
<body>
Email : <input type="text" id="txtEmail" onkeyup="validateEmail()" />

</body>
</html>
JavaScript Timing Events

In JavaScript a piece of code can be executed at specified time interval. For


example, you can call a specific JavaScript function every 1 second. This concept in
JavaScript is called timing events.

The global window object has the following 2 methods that allow us to execute a piece
of JavaScript code at specified time intervals.

setInterval(func, delay) - Executes a specified function, repeatedly at specified time


interval. This method has 2 parameters. The func parameter specifies the name of the
function to execute. The delay parameter specifies the time in milliseconds to wait
before calling the specified function.

setTimeout(func, delay) - Executes a specified function, after waiting a specified


number of milliseconds. This method has 2 parameters. The func parameter specifies
the name of the function to execute. The delay parameter specifies the time in
milliseconds to wait before calling the specified function. The actual wait time (delay)
may be longer.
The setInterval() method calls a function or evaluates an expression at specified
intervals (in milliseconds). The setInterval() method will continue calling the function
until clearInterval() is called, or the window is closed.

The following code displays current date and time in the div tag.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function getCurrentDateTime()
{
document.getElementById("timeDiv").innerHTML = new Date();
}

</script>
</head>
<body>
<div id="timeDiv" ></div>
<input type="submit" onclick="getCurrentDateTime()">
</body>
</html>
At the moment the time is static.
To make the time on the page dynamic, modify the script as shown below. Notice that the
time is now updated every second. In this example, we are using setInterval() method and
calling getCurrentDateTime() function every 1000 milli-seconds.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
setInterval(getCurrentDateTime, 1000);

function getCurrentDateTime()
{
document.getElementById("timeDiv").innerHTML = new Date();
}
</script>
</head>
<body>
<div id="timeDiv" ></div>
<input type=“button” onclick=“setInterval”>
</body>
Starting and stopping the clock with button click : In this example, setInterval()method
returns the intervalId which is then passed to clearInterval() method. When you click
the "Start Clock" button the clock is updated with new time every second, and when you
click "Stop Clock" button it stops the clock.
The clearInterval() method clears a timer set with the setInterval() method.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var intervalId;

function startClock()
{
intervalId = setInterval(getCurrentDateTime, 1000);
}

function stopClock()
{
clearInterval(intervalId);
}
function getCurrentDateTime()
{
document.getElementById("timeDiv").innerHTML= new Date();
}
</script>
</head>
<body>
<div id="timeDiv" ></div> <br />
<input type="button" value="Start Clock" onclick="startClock()" />
<input type="button" value="Stop Clock" onclick="stopClock()" />
</body>
</html>
Now let's look at example of using setTimeout() and clearTimeout() functions. The
syntax and usage of these 2 functions is very similar to setInterval()
and clearInterval().

Countdown timer example :

When we click "Start Timer" button, the value 10 displayed in the textbox must start
counting down. When click "Stop Timer" the countdown should stop. When you
click "Start Timer" again, it should start counting down from where it stopped and
when it reaches ZERO, it should display Done in the textbox and function should return.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var intervalId;

function startTimer(controlId)
{
var control = document.getElementById(controlId);
var seconds = control.value;
seconds = seconds - 1;
if (seconds == 0)
{
control.value = "Done";
return;
}
else
{
control.value = seconds;
}
intervalId = setTimeout(function () { startTimer('txtBox'); }, 1000);
}

function stopTimer()
{
clearTimeout(intervalId);
}
</script>
</head>
<body>
<input type="text" value="10" id="txtBox" />
<br /><br />
<input type="button" value="Start Timer" onclick="startTimer('txtBox')" />
<input type="button" value="Stop Timer" onclick="stopTimer()" />
</body>
</html>
JavaScript Image Slideshow

The slideshow should be as shown in the image below.

When you click "Start Slide Show" button the image slideshow should start and
when you click the "Stop Slide Show" button the image slideshow should stop.
<html>
<head>
<script type="text/javascript">
var intervalId;

function startImageSlideShow()
{
intervalId = setInterval(setImage, 500);
}

function stopImageSlideShow()
{
clearInterval(intervalId);
}

function setImage()
{
var imageSrc = document.getElementById("image").getAttribute("src");
var currentImageNumber = imageSrc.substring(imageSrc.lastIndexOf("/") +
1,imageSrc.lastIndexOf("/") + 2);
if (currentImageNumber == 6)
{
currentImageNumber = 0;
}
document.getElementById("image").setAttribute("src", "Images/" +
(Number(currentImageNumber) + 1) + ".jpg");
}
</script>
</head>

<body>
<img id="image" src="Images/1.jpg" style="width: 500px; height: 150px" />
<br /> <br /> <br />
<input type="button" value="Start Slide Show" onclick="startImageSlideShow()" />
<input type="button" value="Stop Slide Show" onclick="stopImageSlideShow()" />
</body>
</html>
Recursive Function in JavaScript

Recursion is a programming concept that is applicable to all programming


languages including JavaScript.

Recursive function is function that calls itself.

When writing recursive functions there must be a definite break condition,


otherwise we risk creating infinite loops.

Example : Computing the factorial of a number without recursion

<html>
<head>
<script>
function factorial(n)
{
if (n == 0 || n == 1)
{
return 1;
var result = n;
while (n > 1)
{
result = result * (n - 1)
n = n - 1;
}

return result;

}
function abc()
{
document.write(factorial(5));
}
</script>
<head>
<body>
<input type="submit" onclick="abc()">
</body>
</html>
Example : Computing the factorial of a number using a recursive function
<html>
<head>
<script>
function factorial(n)
{
if (n == 0 || n == 1)
{
return 1;
}
return n * factorial(n - 1);
}
function abc()
{
document.write(factorial(5));
}
</script>
<head>
<body>
<input type="submit" onclick="abc()">
</body>
</html>
Error handling in JavaScript

Use try/catch/finally to handle runtime errors in JavaScript. These runtime errors are
called exceptions. An exception can occur for a variety of reasons. For example,
referencing a variable or a method that is not defined can cause an exception.

The JavaScript statements that can possibly cause exceptions should be wrapped
inside a try block. When a specific line in the try block causes an exception, the control is
immediately transferred to the catch block skipping the rest of the code in the try block.
JavaScript try catch example :
<html>
<head>
<script>
function abc()
{
try
{
// Referencing a function that does not exist cause an exception
document.write(sayHello());
// Since the above line causes an exception, the following line will not be executed
document.write("This line will not be executed");
}
// When an exception occurs, the control is transferred to the catch block
catch (e)
{
document.write("Description = " + e.description + "<br/>");
document.write("Message = " + e.message + "<br/>");
document.write("Stack = " + e.stack + "<br/><br/>");
}
}
</script>
<head>
<body>
<input type="submit" onclick="abc()">
</body>
</html>

Please note : A try block should be followed by a catch block or finally block or both.

finally block is guaranteed to execute irrespective of whether there is an exception or


not. It is generally used to clean and free resources that the script was holding onto during
the program execution. For example, if your script in the try block has opened a file for
processing, and if there is an exception, the finally block can be used to close the file.
Example with finally block

<html>
<head>
<script>
function abc()
{
try
{
// Referencing a function that does not exist cause an exception
document.write(sayHello());
// Since the above line causes an exception, the following line will not be
executed
document.write("This line will not be executed");
}
// When an exception occurs, the control is transferred to the catch block
catch (e)
{
document.write("Description = " + e.description + "<br/>");
document.write("Message = " + e.message + "<br/>");
document.write("Stack = " + e.stack + "<br/><br/>");
}
finally
{
document.write("This line is guaranteed to execute");
}

}
</script>
<head>
<body>
<input type="submit" onclick="abc()">
</body>
</html>

Syntax errors and exceptions in JavaScript


try/catch/finally block can catch exceptions but not syntax errors.

Example : In the example, below we have a syntax error - missing the closing
parentheses. The associated catch block will not catch the syntax errors.
<html>
<head>
<script>
function abc()
{
try
{
alert("Hello";
}
// When an exception occurs, the control is transferred to the catch block
catch (e)
{
document.write("JavaScript syntax errors cannot be caught in the catch block");
}
}
</script>
<head>
<body>
<input type="submit" onclick="abc()">
</body>
</html>
JavaScript throw statement : Use the throw statement to raise a customized exceptions.

JavaScript throw exception example :

<html>
<head>
<script>
function divide()
{
var numerator = Number(prompt("Enter numerator"));
var denominator = Number(prompt("Enter denominator"));

try
{
if (denominator == 0)
{
throw {
error: "Divide by zero error",
message: "Denominator cannot be zero"
};
}
else
{
alert("Result = " + (numerator / denominator));
}
}
catch (e)
{
document.write(e.error + "<br/>");
document.write(e.message + "<br/>");
}
}
</script>
<head>
<body>
<input type="submit" onclick="divide()">
</body>
</html>
Front End Development

• Everything What we see on a website


• buttons
• links
• animations
• design
• look
• Content
• Logos
• Search bars

is a task of front end developer to convert clients requirement into the real
and the website must look good in laptops, phones and tablets.
Three main things you must know for front end developments are
HTML,CSS and JavaScript.
Front End Development

• CSS Frameworks, Libraries, and Preprocessors


• Bootstrap
• Tailwind CSS
• Bulma
• Materialize
• Semantic UI
• JavaScript libraries and frameworks
• React
• Angular
• Vue
• Testing and Debugging skills
• Version control (Learn Git)
• Problem Solving
Best Practices for Optimizing front end Performance

• Minify Resources
• Reduce the Number of Server Calls
• Remove Unnecessary Custom Fonts
• Compress Files
• Optimize the Images
• Apply Lazy Loading
• Caching
• Enable Prefetching
• Use a Content Delivery Network

https://blog.bitsrc.io/9-best-practices-for-optimizing-frontend-
loading-time-763211621061
SPA(Single Page Application) VS MPA(Multi Page Application)
• If you want your web app runs without any interference, then it must be
supported by the right technology to get high performance and speed.
• You can develop your web apps by two ways: SPA(single-page applications)
and MPA(multi-page applications)
• A single-page application is a modern approach used by Google, Facebook,
Twitter, etc to app development. It works inside a browser and does not
require page reloading during use.
• Multiple-page application is classical approach to app development. The
multi-page design pattern requires a page reload every time the content
changes. It’s a preferred option for large companies with extensive product
portfolios, such as e-commerce businesses.
https://blog.bitsrc.io/9-best-practices-for-optimizing-frontend-
SPA(Single Page Application) VS MPA(Multi Page Application)
• Speed is fast in SPA than MPA.
• Coupling: SPA is strongly decoupled, meaning that the front-end and
back-end are separate. SPA applications use APIs developed by server-
side developers to read and display data. In MPA’s, the front-end and
back-end are interdependent. All coding is usually housed under one
project.
• Search Engine Optimization MPA is more SEO friendly than SPA.
• User Experience
• Security: SPA is more secure due to its size.
• Development process
• JavaScript dependency
THANKS

You might also like