JavaScript Unit 1
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
Client-side JavaScript
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
Or
jsbin.com
JavaScript Comments
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”
You can easily break up your code into separate files. Modules
uses import and export statements.
<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
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
• Easily extract array elements or object properties and store them in variables.
JavaScript (Destructuring)
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
<script ...>
JavaScript code
</script>
<script type="text/javascript">
JavaScript code
</script>
<!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
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.
<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>
function CanDelete()
{
return confirm("Are you Sure to delete your Data");
}
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;
}
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
The global window object has the following 2 methods that allow us to execute a piece
of JavaScript code at specified time intervals.
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().
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
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
<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.
<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>
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.
<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
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
• 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