JavaScript V1.0
JavaScript V1.0
JavaScript V1.0
Scripting languages
• Scripting languages are programming languages that a program called an interpreter translates into a
• Scripts contain a series of commands that a software, application or scripting engine interprets one at a
JavaScript : Introduction
• JavaScript often abbreviated as JS, is a programming language and core technology of the World Wide
• As of 2024, 98.9% of websites use JavaScript on the client side for webpage behavior, often
• All major web browsers have a dedicated JavaScript engine to execute the code on users' devices.
4 JavaScript | © SmartCliff | Internal | Version 1.1
JavaScript Basics
JavaScript: Introduction
• JavaScript is a multi-paradigm, dynamic language with types and operators, standard built-in objects, and
methods.
• Its syntax is based on the Java and C languages — many structures from those languages apply to
JavaScript as well.
JavaScript: Introduction
• Core JavaScript can be extended for a variety of purposes by supplementing it with additional objects;
For Example,
• Client-side JavaScript extends the core language by supplying objects to control a browser and its
• Server-side JavaScript extends the core language by supplying objects relevant to running JavaScript
on a server.
Javascript : Introduction
• Client-side JavaScript:
• To be interpreted by the browser, the script must be included in or linked from an HTML document.
• It means that a web page can now incorporate programs that interact with the user, control the browser,
and dynamically create HTML content, rather than just static HTML.
• For ex. Use JavaScript to verify that a user has provided a valid email address in a form field.
• When the user submits the form, the Script code gets executed, and the form is submitted to the Web
Javascript : Advantages
• Less server interaction − Before transmitting the page to the server, we can validate the user's input.
• Immediate feedback to the visitors − They don't have to wait for the page to reload to see if they lost
something.
• Increased interactivity − We can make interfaces that respond when the user moves their mouse over
• Richer interfaces − To provide a Rich Interface to your site users, we can utilize JavaScript to
Javascript : Advantages
• Interoperability - We can embed it into any webpage or inside the script of another programming
language.
• Versatility - JavaScript can now be used for both front-end and back-end development.
• Less Overhead
• By reducing the code length, JavaScript enhances the efficiency of websites and web apps.
• The usage of numerous built-in methods reduces the amount of overhead in the code.
Javascript : Advantages
• Popularity - Since all modern browsers support JavaScript, it is seen almost everywhere.
• Extended Functionality - Third-party add-ons allow the developers to add snippets of predefined code
• Asynchronous Programming – This model facilitates non-blocking operations, making it well-suited for
tasks that involve fetching data from servers, handling user input, and managing concurrent processes.
The actual content of The look of the page Easily control and alter
the page like color, style the HTML
Javascript : A heed
• File reading and writing on the client side are not supported by JavaScript.
• A single code error can cause the entire JavaScript code on the page to stop rendering.
• The <script> element, which contains JavaScript, can be placed anywhere on the page, however it is
advised to put it within the <head> tags.
• The <script> tag alerts the browser program to begin interpreting all the text between these tags as a
script.
• Syntax of JavaScript will be as follows:
<script>
Javascript Code
</script>
• language:
• The use of this feature has been phased out in current versions of HTML (and its successor,
XHTML).
• type:
• The value of this attribute should be set to "application/javascript" or “text/javascript" in order
to identify the scripting language in use.
<!DOCTYPE html>
<html>
<head>
<script type="application/javascript">
alert('Hello, World!');
</script>
</head>
<body>
</body>
</html>
• There is a flexibility given to include JavaScript code anywhere in an HTML document. But there are
• Script in <head>...</head> section: If you want to have a script run on some event, such as when a
user clicks somewhere, then you will place that script in the head.
• Script in <body>...</body> section: If you need a script to run as the page loads so that the script
generates content in the page, the script goes in the <body> portion of the document.
• The script tag provides a mechanism to allow you to store JavaScript in an external file and then
include it in your HTML files.
• To use JavaScript from an external file source, you need to write all JavaScript source code in a simple
text file with the extension ".js".
//filename.js
alert('Hello, World!');
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
Basic Elements
JavaScript is case-sensitive
• Everything in JavaScript is case-sensitive, including variables, function names, class names, and
operators.
• It indicates that the counter and Counter variables are not the same.
Identifiers
• The first character must be a letter (a-z, or A-Z), an underscore(_), or a dollar sign ($).
• The other characters can be letters (a-z, A-Z), numbers (0-9), underscores (_), and dollar signs ($).
• A block comment starts with forward-slash(/) and asterisk(*) characters and ends with asterisk(*) and
forward-slash(/) characters.
/*
*/
Statements
var a = 10;
var b = 20;
Expressions
• An expression is a piece of code that evaluates to a value.
For example:
c=2 + 1
• JavaScript defines a list of keywords and reserved words that have special uses.
• var
• let
• const
var message;
message = "Hello";
• You can also assign a value to the variable when you declare it:
Note:
• The general rules for constructing names for variables (unique identifiers) are:
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
var x = "Sachin";
var x = 0;
document.write(x);
</script> Output:
</body>
0
</html>
{
var x = 2;
}
// x can be used here
<html>
<body>
<script type="text/javascript">
const PI = 3.141592653589793;
document.write(PI);
</script>
</body>
Output:
</html> 3.141592653589793
<html>
<body>
<script type="text/javascript">
const PI ;
PI = 3.141592653589793;
document.write(PI);
</script>
</body> Output:
• Declaring a variable with const is similar to let when it comes to Block Scope.
• For Example: The x declared in the block is not the same as the x declared outside the block
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
++ Increment
-- Decrement
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
**= x **= y x = x ** y
== equal to
!= not equal
? ternary operator
38 JavaScript | © SmartCliff | Internal | Version 1.1
JavaScript Basics
Operator Description
|| logical or
! logical not
(?:) Conditional Operator returns value based on the condition. It is like if-else.
x = 5; // Now x is a Number
• Strings are written with quotes. single or double quotes can be used.
• We can use quotes inside a string, as long as they don't match the quotes surrounding the string:
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
let Name1 = "Sachin"; // Using double quotes
let Name2 = 'Sachin'; // Using single quotes
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
let x1 = 34.50; // Written with decimals
let x2 = 34; // Written without decimals
</body>
</html>
<body>
<script type="text/javascript">
let x = 5;
let y = 5;
let z = 6;
document.write("(x == y) : "+(x == y) +"<br/>");
document.write("(x == z) : "+(x == z) );
</script>
</body>
</html>
• Array indexes are zero-based, which means the first item is [0], the second is [1], and so on.
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
const cars = ["Saab", "Volvo", "BMW"];
document.write("Cars : "+cars +"<br/><br/>");
for (let i = 0; i < cars.length; i++) {
document.write("Car at index " + i + ": " + cars[i] + "<br/>"); }
</script>
</body>
</html>
<html>
<body>
<script type="text/javascript">
</script>
</body>
</html>
<html>
<body>
<script>
document.write(5 + 6);
</script>
</body>
</html>
• The window object is the global scope object, that means that variables, properties, and methods by
default belong to the window object.
<!DOCTYPE html>
<html>
<body>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
52 JavaScript | © SmartCliff | Internal | Version 1.1
JavaScript : Fundamentals
• For debugging purposes, you can call the console.log() method in the browser to display data.
<!DOCTYPE html>
<html>
<body>
<script>
console.log(5 + 6);
</script>
</body>
</html>
if (condition) {
// block of code to be executed if the condition is true
}
<script type="application/javascript">
</script>
<script type="application/javascript">
var age = 15;
if( age > 18 ){
document.write("<b>Qualifies for driving</b>");
}else{
document.write("<b>Does not qualify for driving</b>");
}
</script>
if (condition1) {
} else if (condition2) {
} else {
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
<script type="application/javascript">
var grade='A';
switch (grade) {
case 'A': document.write("Good job<br />");
break;
case 'B': document.write("Pretty good<br />");
break;
case 'C': document.write("Passed<br />");
break;
break;
break;
</script>
<script type="application/javascript">
var count = 0;
count++; }
</script>
do{
Statement(s) to be executed;
} while (expression);
<script type="application/javascript">
var count = 0;
document.write("Starting Loop…." + "<br /><br />");
do{
document.write("Current Count : " + count + "<br />");
count++;
}while (count < 10);
document.write("<br />Loop stopped!");
</script>
<script type="application/javascript">
</script>
63 JavaScript | © SmartCliff | Internal | Version 1.1
JavaScript Basics
Basic Elements : Control Flow Statements
break Statement
<script type="application/javascript">
var x = 1;
document.write("Entering the loop<br /> <br />");
while (x < 20){
if (x == 5){
break; // breaks out of the loop completely
}
x = x + 1;
document.write( x + "<br />");
}
document.write(" <br /> Exiting the loop!<br /> ");
</script>
<script type="application/javascript">
</script>
var x = 1;
</script>
<script type="application/javascript">
if (j == 3){
continue outerloop;
</script>
70 JavaScript | © SmartCliff | Internal | Version 1.1
JavaScript Basics
Syntax:
function functionName(parameter-list){
statements
}
• A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses
().
• Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
• The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...)
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function sayHello() {
alert("Hello there");
</script>
</head>
<body>
<script type="text/javascript">
sayHello();
</script>
</body>
</html>
• A confirmation dialog box is mostly used to take the 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.
<html>
<head>
<script>
function myConfirmbox(){
var retVal = confirm("Do you want to continue ?");
if( retVal == true ){
alert("User wants to continue!");
}
else{
alert("User does not want to continue!");
}
}
</script>
</head>
75 JavaScript | © SmartCliff | Internal | Version 1.1
JavaScript Basics
Basic Elements : DialogBoxes
Confirmation Dialog Box:
<body>
<script>
myConfirmbox();
</script>
</body>
</html>
• The window method prompt() returns the entered value when the user clicks on OK button.
<html>
<head>
<script>
function myPrompt(){
var retVal = prompt("Enter your name : ", "your name here");
alert("You have entered : " + retVal );
}
</script>
</head>
<body>
<script>
myPrompt();
</script>
</body></html>
• "Everything" in JavaScript is an Object. Even primitive data types (except null and undefined) can be
treated as objects.
Object Properties
Syntax:
• objectName.propertyName
• objectName["propertyName"]
Object Properties:
Property Property Value
firstName Sachin
lastName Tendulkar
age 50
Example:
person.lastName; // Tendulkar
Or
person["lastName"];
83 JavaScript | © SmartCliff | Internal | Version 1.1
JavaScript Objects
Introduction
Object Methods
objectName.methodName()
<html>
<body>
<script type="text/javascript">
</script>
</body>
</html>
<html>
<body>
<script type="text/javascript">
person.fullName=function(){
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
person.fullName=function(){
</script>
</body>
</html>
Arrays
• In JavaScript, arrays aren't primitives but are instead Array objects with the following core
characteristics:
• JavaScript arrays are resizable and can contain a mix of different data types.
• JavaScript arrays are not associative arrays and so, array elements cannot be accessed using arbitrary
Arrays
Creating an array
• Using literal
• Using Constructor
Arrays: Iteration
• Using forEach:
const arrayItems = ['item1', 'item2', 'item3'];
const copyItems = [];
arrayItems.forEach(function(item){
copyItems.push(item);
})
console.log(copyItems);
• Using for…of:
const students = ['John', 'Sara', 'Jack'];
// using for...of
for ( let element of students ) {
console.log(element);
}
Methods Description
push() Adds new elements to the end of an array, and returns the new length
pop() Removes the last element of an array, and returns that element
shift() Removes the first element of an array, and returns that element
unshift() Adds new elements to the beginning of an array, and returns the new length
find() Returns the value of the first element in an array that pass a test
filter() Creates a new array with every element in an array that pass a test
keys() Returns a Array Iteration Object, containing the keys of the original array
map() Creates a new array with the result of calling a function for each array element
Methods Description
reduce() Reduce the values of an array to a single value (going left-to-right)
indexOf() Search the array for an element and returns its position
lastIndexOf() Search the array for an element, starting at the end, and returns its position
• But strings can also be defined as objects with the keyword new:
//checks both the values and the data types, and they are different (string vs. object)
document.write("Comparison using === operator: "+(x===z)+"<br/>");
//checking the two different string objects but they have the same string value
document.write("Comparison using == operator: "+(z==z1)+"<br/>");
//checks both values and data types but not with objects
document.write("Comparison using === operator: "+(z===z1)+"<br/>");
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
</script>
</body>
</html>
97 JavaScript | © SmartCliff | Internal | Version 1.1
JavaScript Objects
String Methods
Possible String Methods:
Method Description
charAt() Returns the character at the specified index.
concat() Combines the text of two strings and returns a new string.
indexOf() Returns the index within the calling String object of the first occurrence of the specified value,
or -1 if not found.
lastIndexOf() Returns the index within the calling String object of the last occurrence of the specified value,
or -1 if not found.
match() Used to match a regular expression against a string.
replace() Used to find a match between a regular expression and a string, and to replace the matched
substring with a new substring.
search() Executes the search for a match between a regular expression and a specified string.
split() Splits a String object into an array of strings by separating the string into substrings.
98 JavaScript | © SmartCliff | Internal | Version 1.1
JavaScript Objects
String Methods
Possible String Methods:
Method Description
substr() Returns the characters in a string beginning at the specified location through the
specified number of characters.
substring() Returns the characters in a string between two indexes into the string.
toLocaleLowerCase() The characters within a string are converted to lower case while respecting the
current locale.
toLocaleUpperCase() The characters within a string are converted to upper case while respecting the
current locale.
• slice() extracts a part of a string and returns the extracted part in a new string.
• The method takes 2 parameters: the start position, and the end position (end not included).
• The positive starting index(from left to right) is 0 and the negative starting index(from right to left) is -1.
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
</script>
</body>
</html>
</script>
</body>
</html>
102 JavaScript | © SmartCliff | Internal | Version 1.1
JavaScript Objects
String Methods: Example #3
• The difference is that the second parameter specifies the length of the extracted part.
• If you omit the second parameter, substr() will slice out the rest of the string.
Replacing String
• The replace() method replaces a specified value with another value in a string.
• The replace() method does not change the string it is called on.
• To replace all matches, use a regular expression with a /g flag (global match).
<body>
<script type="text/javascript">
Method Description
constructor() Returns the function that created this object's instance. By default this is the Number
object.
toExponential() Forces a number to display in exponential notation, even if the number is in the range in
which JavaScript normally uses standard notation.
toFixed() Formats a number with a specific number of digits to the right of the decimal.
toLocaleString() Returns a string value version of the current number in a format that may vary according
to a browser's locale settings.
toPrecision() Defines how many total digits (including digits to the left and right of the decimal) to
display of a number.
toString() Returns the string representation of the number's value.
• All number methods can be used on any type of number (literals, variables, or expressions).
<!DOCTYPE html>
<html>
<body>
<script>
let x = 123;
document.write("Number as a String: "+x.toString()+"<br/><br/>");
document.write("Number as a String: "+(123).toString()+"<br/><br/>");
document.write("Number as a String: "+(100 + 23).toString());
</script>
</body>
</html>
109 JavaScript | © SmartCliff | Internal | Version 1.1
JavaScript Objects
Global Methods
Converting Variables to Numbers
• There are 3 JavaScript methods that can be used to convert a variable to a number:
Method Description
Number() Returns a number converted from its argument.
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
document.write("Converting boolean variable to number: "+Number(true)+"<br/><br/>");
document.write("Converting boolean variable to number: "+Number(false)+"<br/><br/>");
document.write("Converting string variable to number: "+Number("50")+"<br/><br/>");
document.write("Converting string variable to number: "+Number("50.50")+"<br/><br/>");
document.write("Converting string variable to number: "+Number("Hi"));
</script>
</body>
</html>
Date
• Date objects encapsulate an integral number that represents milliseconds since the midnight at the
• There are various methods that allow you to interact with the timestamp stored in the date.
• There are always two ways to interpret a timestamp: as a local time or as a Coordinated Universal Time
(UTC), the global standard time defined by the World Time Standard.
117 JavaScript | © SmartCliff | Internal | Version 1.1
JavaScript Objects
Creating Date
• To create a new Date object call new Date(). That is creating an object or instance of Date.
• The following snippet creates a date object with current date and time.
• You can create a Date object by passing individual date and time components (year, month, day, hour,
Creating Date
• You can create a Date object by passing a date and time string as an argument to the constructor. The
• You can create a Date Object by passing a timestamp, representing the total number of seconds (or
Methods Description
getFullYear() Get year as a four digit number (yyyy)
Methods Description
• The search pattern can be used for text search and text replace operations.
• When you search for data in a text, you can use this search pattern to describe what you are searching
for.
• Regular expressions can be used to perform all types of text search and text replace operations.
Here,
• pattern:
• attributes:
• An optional string containing any of the "g", "i", and "m" attributes that specify global, case-
Expression Description
Expression Description
Method Description
exec() Executes a search for a match in its string parameter. If it finds a match, it returns the
matched text ; otherwise, it returns null.
test() Tests for a match in its string parameter. This method returns true if it finds a match,
otherwise it returns false.
toSource() Returns an object literal representing the specified object; you can use this value to
create a new object.
<html>
<body>
<script type="text/javascript">
var str = "Javascript is an interesting scripting language";
var re = new RegExp( "script", "g" );
var result = re.exec(str);
document.write("Test 1 - returned value : " + result);
re = new RegExp( "pushing", "g" );
var result = re.exec(str);
document.write("<br />Test 2 - returned value : " + result);
</script>
</body>
</html>
<html>
<body>
<script type="text/javascript">
var str = "Javascript is an interesting scripting language";
var re = new RegExp( "script", "g" );
var result = re.test(str);
document.write("Test 1 - returned value : " + result);
re = new RegExp( "pushing", "g" );
var result = re.test(str);
document.write("<br />Test 2 - returned value : " + result);
</script>
</body>
</html>
Event Description
onchange Script runs when the element changes
onsubmit Script runs when the form is submitted
onreset Script runs when the form is reset
onselect Script runs when the element is selected
onblur Script runs when the element loses focus
onfocus Script runs when the element gets focus
onkeydown Script runs when key is pressed
onkeypress Script runs when key is pressed and released
onkeyup Script runs when key is released
onclick Script runs when a mouse click
ondblclick Script runs when a mouse double-click
Event Description
• This is the most frequently used event type which occurs when a user clicks the mouse’s left button.
<html>
<head>
<script type="text/javascript">
function sayHello() {
alert("Hello World")
}
</script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello"/>
</body>
</html>
• The events can be used to trigger a function when the user mouses over, or out of, an HTML element.
<html>
<head>
<script type="text/javascript">
function over() { alert("Mouse Over"); }
function out() { alert("Mouse Out"); }
</script>
</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover="over()" onmouseout="out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>
134 JavaScript | © SmartCliff | Internal | Version 1.1
JavaScript Events
Example: #2
• "The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows
programs and scripts to dynamically access and update the content, structure, and style of a
document."
Introduction
• The HTML DOM is a standard object model and programming interface for HTML.
• It defines:
• When a web page is loaded, the browser creates a Document Object Model of the page.
• The HTML DOM model is constructed as a tree of Objects.
Document
Root
<HTML>
Element Element
<head> <body>
• HTML DOM methods are actions you can perform (on HTML Elements).
• HTML DOM properties are values (of HTML Elements) that you can set or change.
• The innerHTML property is the simplest way to access the content of an element. The innerHTML
• Any element’s HTML content, including <html> and <body>, can be retrieved or changed using the
innerHTML property.
• In the HTML DOM object model, the document object represents a web page.
• The document object is the owner of all other objects in a web page.
• Always start with accessing the document object to access objects in an HTML page.
Method Description
<!DOCTYPE html>
<html>
<body>
<p id="intro">Hello World!</p>
<p id="demo"></p>
<script>
myElement = document.getElementById("intro");
document.getElementById("demo").innerHTML =
"The text from the intro paragraph is " + myElement.innerHTML;
</script>
</body>
</html>
• This example finds the element with id="main", and then finds all by tag name <p> elements inside
"main".
<!DOCTYPE html>
<html>
<body>
<p>Hello World!</p>
<div id="main">
<p>The DOM is very useful.</p>
<p>This example demonstrates the <b>getElementsByTagName</b> method</p>
</div>
<p id="demo"></p>
<script>
var x = document.getElementById("main");
var y = x.getElementsByTagName("p");
document.getElementById("demo").innerHTML =
"<b>"+y[0].innerHTML+"</b>";
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
const x = document.getElementsByClassName("intro");
document.getElementById("demo").innerHTML =
</script>
</body>
</html>
Method Description
• The easiest way to modify the content of an HTML element is by using the innerHTML property.
Syntax:
document.getElementById(id).innerHTML = new HTML
<!DOCTYPE html>
<html>
<body>
<p id="p1">Hello World!</p>
<p id="p2"></p>
<script>
</script>
</body>
</html>
Syntax:
document.getElementById(id).attribute = new value
<!DOCTYPE html>
<html>
<body>
<img id="Img1" src="sun.gif" width="200" height="300">
<script>
document.getElementById("Img2").src = "smiley.png";
</script>
</body>
</html>
Syntax:
document.getElementById(id).setAttribute(“attribute”, “new value”);
<!DOCTYPE html>
<html>
<body>
<img id="Img1" src="sun.gif" width="200" height="300">
<script>
document.getElementById("Img2").
setAttribute("src","smiley.png");
</script>
</body>
</html>
Syntax:
document.getElementById(id).style.attribute = new value
<!DOCTYPE html>
<html>
<body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").style.color='maroon';
</script>
</body>
</html>
Method Description
function CreateElement() {
div = document.getElementById("section");
heading = document.createElement("h3");
paragraph = document.createElement("p");
AppendElement();
}
function AppendElement() {
heading.textContent = "You can do Everything";
div.appendChild(heading);
paragraph.textContent = "Have a good day";
div.appendChild(paragraph);
}
function ReplaceElement() {
oldValue=document.getElementById("para");
newValue = document.createElement("p");
newValue.appendChild(document.createTextNode('Have a Wonderful Day'));
oldValue.replaceChild(newValue, oldValue.lastChild);
}
function RemoveElement() {
div.removeChild(paragraph);
}
</script>
• The onchange event occurs when the value of an element has been changed.
• For radio buttons and checkboxes, the onchange event occurs when the checked state has been
changed.
• The upperCase() function will be called when a user changes the content of an input field.
<html>
<head>
<script>
function upperCase(){
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</head>
162 JavaScript | © SmartCliff | Internal | Version 1.1
DOM(Document Object Model)
HTML DOM Events: onchange Event : Example #1
<body>
<p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>
</body>
</html>
onfocus Event:
onblur Event:
• This event is often used with form validation (when the user leaves a form field).
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Click "Try it" to execute the displayDate() function.</p>
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
document.getElementById("myBtn").onclick = function(){displayDate()};
</script>
</body>
</html>
• This method attaches an event handler to an element without overwriting existing event handlers.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Click "Try it" to execute the displayDate() function.</p>
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
document.getElementById("myBtn"). addEventListener("click", displayDate);
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
</body>
</html>
169 JavaScript | © SmartCliff | Internal | Version 1.1
DOM(Document Object Model)
HTML DOM Event Listener : Example #1
<!DOCTYPE html>
<html>
<body>
<button id="myBtn">Try it</button>
<script>
document.getElementById("myBtn").addEventListener("click", myFunction);
function myFunction() {
alert ("Hello World!");
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
var x = document.getElementById("myBtn");
x.addEventListener("mouseover", myFunction);
x.addEventListener("click", mySecondFunction);
x.addEventListener("mouseout", myThirdFunction);
<style>
#myDiv1 {
background-color: coral;
padding: 50px;
}
#myP1 {
background-color: white;
font-size: 20px;
border: 1px solid;
padding: 20px;
}
</style>
</head>
<body>
<div id="myDiv1">
<h2>Bubbling:</h2>
<p id="myP1">Click me!</p>
</div><br>
<script>
document.getElementById("myP1").addEventListener("click", function() {
alert("You clicked the white element!"); });
document.getElementById("myDiv1").addEventListener("click", function() {
alert("You clicked the orange element!"); });
</script>
</body>
</html>
function myFunction() {
</script>
</body>
</html>
179 JavaScript | © SmartCliff | Internal | Version 1.1
DOM(Document Object Model)
HTML DOM Collections : Example #1
</body>
</html>
182 JavaScript | © SmartCliff | Internal | Version 1.1
DOM(Document Object Model)
HTML DOM Collections : Example #2
Using Events
• The HTML DOM allows you to execute code when an event occurs.
• Events are generated by the browser when "things happen" to HTML elements:
• An element is clicked on
• The page has loaded
• Input fields are changed
<!DOCTYPE html>
<html>
<body>
<h1 id="id1">My Heading 1</h1>
<button type="button" onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script>
function removeElement() {
document.getElementById("imgbox1").style.display = "none";
}
function changeVisibility() {
document.getElementById("imgbox2").style.visibility = "hidden";
}
function resetElement() {
document.getElementById("imgbox1").style.display = "block";
document.getElementById("imgbox2").style.visibility = "visible";
}
</script>
186 JavaScript | © SmartCliff | Internal | Version 1.1
DOM(Document Object Model)
The DOM CSS : Example #2
<style>
.imgbox {
float: left;
text-align: center;
width: 120px;
height: 145px;
margin: 4px;
padding: 0;
.thumbnail {
width: 110px;
height: 90px;
margin: 3px;
}
.box {
width: 110px;
padding: 0;
</style>
</head>
<body>
<div style="text-align:center">
<div style="width:394px;height:160px;margin-left:auto;margin-right:auto;text-align:left;border:1px solid gray;">
<div class="imgbox" id="imgbox1">Box 1<br>
<img class="thumbnail" src="klematis_small.jpg" width="107" height="90" alt="Klematis">
<input class="box" type="button" onclick="removeElement()" value="Remove">
</div>
<div class="imgbox" id="imgbox2">Box 2<br>
<img class="thumbnail" src="klematis2_small.jpg" width="107" height="90" alt="Klematis">
<input class="box" type="button" onclick="changeVisibility()" value="Hide">
</div>
<div class="imgbox">Box 3<br>
<img class="thumbnail" src="klematis3_small.jpg" width="107" height="90" alt="Klematis">
<input class="box" type="button" onclick="resetElement()" value="Reset All">
</div> </div> </div>
</body>
</html>
189 JavaScript | © SmartCliff | Internal | Version 1.1
DOM(Document Object Model)
The DOM CSS : Example #2
Attribute Description
<!DOCTYPE html>
<html>
<body>
<h2>HTML Validation</h2>
<form action=" " method="post">
<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
let x = document.forms["Form1"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}}
</script>
</head>
HTML5 Canvas
• The HTML canvas element provides HTML a bitmapped surface to work with.
• The HTML 5 <canvas> tag is used to draw graphics using scripting language like JavaScript.
• The <canvas> element is only a container for graphics, we must need a scripting language to draw the
graphics.
• The <canvas> element allows for dynamic and scriptable rendering of 2D shapes and bitmap images.
• Canvas has several methods for drawing paths, boxes, circles, text, and adding images.
HTML5 Canvas
• By default, the <canvas> element has no border and no content, it is like a container.
• Always specify an id attribute (to be referred to in a script), and a width and height attribute to define
<!DOCTYPE html>
<html>
<body>
</canvas>
</body>
</html>
Canvas - Line
• After creating the rectangular canvas area, we must add JavaScript to do the drawing.
• If you want to draw a straight line on the canvas, we can use the following two methods.
• If we draw a line whose starting point is (0,0) and the end point is (200,100), use the stroke method to
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
</script>
</body>
</html>
Canvas - Circle
• If we want to draw a circle on the canvas, we can use the arc() method:
• To sketch a circle on an HTML canvas, use one of the ink() methods, like stroke() or fill().
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(150,100,90,0,2*Math.PI);
ctx.stroke();
</script>
</body>
</html>
Canvas - Text
• There are properties and methods used for drawing text on the canvas.
• font property:
• fillText(text,x,y) method:
• strokeText(text,x,y) method:
• It is also used to draw text on the canvas, but the text is unfilled.
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = “40px Arial";
ctx.fillText("Hello World",50,50);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = “40px Arial";
ctx.strokeText("Hello World",50,50);
</script>
</body>
</html>
Canvas - Gradient
• createLinearGradient(x,y,x1,y1)
• createRadialGradient(x,y,r,x1,y1,r1)
Canvas - Gradient
• Once we have a gradient object, we must add two or more color stops.
• The addColorStop() method specifies the color stops, and its position along the gradient.
• To use the gradient, set the fillStyle or strokeStyle property to the gradient.
<!DOCTYPE html>
<html>
<body>
</canvas>
<script>
var c = document.getElementById("myCanvas");
// Create gradient
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");
ctx.fillStyle = grd;
ctx.fillRect(10,10,250,180);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
</canvas>
<script>
var c = document.getElementById("myCanvas");
// Create gradient
var grd = ctx.createRadialGradient(160,100,5,90,60,150);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");
ctx.fillStyle = grd;
ctx.fillRect(10,10,250,180);
</script>
</body>
</html>
Canvas - Image
• canvas drawImage() function is used to display an image or video on canvas.
• This function can be used to display the whole image or just a small part of the image.
Canvas - Image
• img: the image or video to draw on canvas.
<!DOCTYPE html>
<html>
<body>
<p>Image to use:</p>
<p>Canvas:</p>
</canvas>
<script>
window.onload = function() {
var c = document.getElementById("myCanvas");
</script>
</body>
</html>
Canvas - Image
<!DOCTYPE html>
<html>
<body>
<p>Image to use:</p>
<p>Canvas:</p>
</canvas>
<script>
window.onload = function() {
var c = document.getElementById("myCanvas");
</script>
</body>
</html>
Canvas - Image
<!DOCTYPE html>
<html>
<body>
<p>Image to use:</p>
<p>Canvas:</p>
</canvas>
<script>
window.onload = function() {
var c = document.getElementById("myCanvas");
ctx.drawImage(img, 100,60,50,60,10,10,50,60);
</script>
</body>
</html>
Canvas - Image
Anonymous Function
• Usually, while defining a function, we specify a name, sometimes parameters, and then whatever we
• Anonymous Functions are functions that are not given any name or identity. In other words, they are
Syntax:
(function (parameters){
//body of the function
});
Anonymous Function
• It is mandatory to use a semicolon because it returns an object. Otherwise, it generates a run time
error.
function (){
console.log(“Anonymous Function");
}
• Anonymous functions can only be called as and when declared without any hassle, they are preferred in
(function () {
console.log("Anonymous Function");
})();
• Because the functions were kept inside the brackets(), it returned an object which is used in the function
call.
• An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is
defined.
• Functions lie at the heart of JavaScript, serving as the building blocks that make this versatile
• This unique characteristic of JavaScript functions empowers developers to write clean, modular, and
expressive code.
• In JavaScript, functions are not just pieces of code that perform tasks; they are first-class citizens of the
language.
• First-class functions, also known as first-class citizens or first-class objects, are a fundamental concept in
programming languages.
• They refer to functions that can be treated in the same way as any other data type, such as numbers,
strings, or objects.
• In JavaScript, this means that functions can be assigned to a variable, passed as arguments, and
• These abilities makes a function more powerful and leads to achieve great features of the JavaScript
language.
• Functions as Values: Functions are treated as values, which means they can be assigned to variables
• Function Expressions: Functions can be defined as expressions and assigned to variables. This
• Passing Functions as Arguments: Functions can be passed as arguments to other functions. This is a
• Functions as Return Values: Functions can be returned as the result of another function. This is
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
function calculate(operation, num1, num2) {
return operation(num1, num2);
}
//Passing the function as argument
console.log(calculate(add, 5, 10)); //15
console.log( calculate(subtract, 10, 5)); //5
234 JavaScript | © SmartCliff | Internal | Version 1.1
Functions – A Deep Dive
function multiplier(factor) {
return function(x){
return x * factor;
}
}
console.log(double(5)); // 10
console.log(triple(5)); // 15
Higher-Order Functions
• In essence, a higher-order function operates on other functions, either by using them to perform tasks or
• Higher-order functions are a powerful concept in JavaScript and functional programming, enabling code
• Function as an Argument: Higher-order functions can accept other functions as arguments, often
referred to as callback functions. They are used for data processing, filtering, or handling events.
• Function as a Return Value: Higher-order functions can return another function, allowing for the
• Abstraction: Higher-order functions abstract common patterns and operations, promoting code
• Composition: Multiple higher-order functions can be combined to create complex data transformations
or processing pipelines.
function doubleElements(x){
return 2*x;
let DoubleResult=[1,2,3,4,5,6].map(doubleElements)
function filterElemLesThanTwo(x){
return x<2
let ResultLessThanTwo=[1,2,3,4,5,6].filter(filterElemLesThanTwo)
console.log(DoubleResult)
console.log(ResultLessThanTwo)
238 JavaScript | © SmartCliff | Internal | Version 1.1
Functions – A Deep Dive
Function Composition
• Function composition is the process of chaining together multiple functions to form a new function.
• It involves applying a series of transformations or operations to an input value, where the output of one
function becomes the input of the next function in the composition chain.
• To harness the power of function composition, we need to define the compose function. As a simple
implementation, the compose function accepts any number of functions as arguments and returns a new
function that iterates over the functions in reverse order using reduceRight() of Array.
• The ‘compose()’ function takes in two or more functions and returns a new function that applies these
Currying
• Currying is a technique used in functional programming that allows you to transform a function with
multiple arguments into a sequence of functions, each taking only one argument at a time.
• In JavaScript, currying is a powerful tool that can improve code reusability, composability, and
maintainability.
function add(x) {
return function(y) {
return x + y;
};
}
console.log(add(3)(4));
Pure Functions
• Pure functions are essential for a variety of purposes, including functional programming, reliable
• You can use pure functions to ensure your code is clean, maintainable, and testable.
• These functions are ideal for these tasks because they are predictable and do not modify external states.
No Side Effects
• A side effect refers to any modification of state or behavior outside the function's scope, such as
Scope
• The scope is the current context of execution in which values and expressions are "visible" or can be
referenced.
• If a variable or expression is not in the current scope, it will not be available for use.
• Scopes can be layered in a hierarchy, so that child scopes have access to parent scopes, but not vice
versa.
• Global scope: The default scope for all code running in script mode.
• Block scope: The scope created with a pair of curly braces (a block).
Scope Chain
• A scope chain refers to the unique spaces that exist from the scope where a variable got called to the
global scope.
• In the following example, there are four (4) spaces from fullName’s invocation scope to its lexical scope
• JavaScript's scope chain determines the hierarchy of places the computer must go through — one after
the other — to find the lexical scope (origin) of the specific variable that got called.
Scope Chain
• Note: The global scope is the last link in JavaScript's scope chain.
Lexical Scope
• An item's lexical scope is the place in which the item got created.
Lexical Scope
• myName’s lexical scope is not the function’s local scope but the global scope because we defined
• An alternative to the lexical scope is the dynamic scope — but it rarely gets used in programming.
Closures
• Closures are functions that refer to independent (free) variables. In other words, the function defined in
• Free variables are variables that are neither locally declared nor passed as parameter.
• In JavaScript, closures are created every time a function is created, at function creation time.
Closure – Example 1
function makeFunc() {
const name = “Smith";
function displayName() {
console.log(name);
}
return displayName;
}
console.log(myFunc);
console.dir(myFunc);
Closure – Example 2
function makeAdder(x) {
return function (y) {
return x + y;
};
}
const add5 = makeAdder(5);
const add10 = makeAdder(10);
console.log(add5(2)); // 7
console.log(add10(2)); // 12
console.log(add5);
console.dir(add10);
Introduction
• ES6 or ECMAScript 2015 is the 6th version of the ECMAScript programming language.
• ECMAScript is the standardization of JavaScript which was released in 2015, and subsequently
• It was introduced by ‘ECMA International’ and is basically an implementation with which we learn how to
• It allows us to write code in a clever way which basically makes the code more modern and more
readable. It’s fair to say that with the use of ES6 features we write less and do more.
Why ES6?
• No wonder ES6 is one of the efficient programming languages used for building robust applications.
• ES6 offers wonderful features such as Arrow functions, destruction methods, modules, block-scoped
• The great thing about ES6 is that it is the next-generation JavaScript language.
• Block-scoped variables are the variables that hold their value until the end of the block only.
• After that, the variables will take the values of the outer block.
• The variables are declared using const and let keywords follow block-scoping rules.
Block
Variables
const let
Block Variables
• ‘let’ Keyword
• ES6 provides a new way of declaring a block scope variable by using the let keyword.
Example:
let x = 10;
if (x == 10) {
let x = 20;
console.log(x); // 20: reference x inside the block
}
console.log(x); // 10: reference at the begining of the script
Block Variable
• ‘const’ keyword
• Like the let keyword, the const keyword declares blocked-scope variables.
• However, the block-scoped variables declared by the const keyword can’t be reassigned.
• The variables declared by the let keyword are mutable. But the variables created by const keyword
are immutable.
const RATE = 0.1;
RATE = 0.2; // TypeError
const person = { age: 20 }; // const with objects
person.age = 30; // OK
console.log(person.age); // 30
259 JavaScript | © SmartCliff | Internal | Version 1.1
ES6
Default Parameters
• Default parameters are parameters which are given by default while declaring a function.
Syntax:
function fn(param1=default1, param2=default2,..) {
}
Example:
function say(message='Hi') {
console.log(message);
}
say(); // 'Hi'
say(undefined); // 'Hi'
say('Hello’); // 'Hello'
Rest Parameters
• ES6 provides a new kind of parameter called rest parameter that has a prefix of three dots (...).
Syntax:
function fn(a,b,...args) {
//...
}
Example:
function sum(...args) {
let total = 0;
for (const a of args) {
total += a;
}
return total;
}
sum(1, 2, 3);
261 JavaScript | © SmartCliff | Internal | Version 1.1
ES6
Spread Operator
• ES6 provides a new operator called spread operator that consists of three dots (...).
• The spread operator allows you to spread out elements of an iterable object such as an array, map, or
set.
Example:
const odd = [1,3,5];
const combined = [2,4,6, ...odd];
console.log(combined); // Output: [ 2, 4, 6, 1, 3, 5 ]
for…of Loop
• ES6 introduced a new statement for...of that iterates over an iterable object such as:
• Gives the values of the objects where as for…in gives the indexes .
Syntax:
for (variable of iterable) {
// ...
}
Example:
let scores = [80, 90, 70];
• ES6 provides a new feature called destructuring assignment that allows you to destructure properties of
• Array Destructuring: This method allows destructuring arrays by swapping variables. Otherwise, we
need to use temporary variables. Using this method, we can easily assign elements of arrays to
variables.
Example:
function getScores() { let [x, y ,...args] = getScores();
return [70, 80, 90, 100]; console.log(x); // 70
} console.log(y); // 80
console.log(args); // [90, 100]
• It is yet another destructuring method that allows assigning object properties to variables. Moreover, this
method assigns default values to variables if object properties are absent. When we use this method, we
must put values in curly brackets, which will help to retrieve object properties.
Example:
let person = {
firstName: 'John',
lastName: 'Doe’
};
let { firstName: fname, lastName: lname } = person;
(OR)
let { firstName, lastName } = person;
Modules
• Modules can load each other and use special directives export and import to interchange functionality,
• export keyword labels variables and functions that should be accessible from outside the module.
• It means that any variables or functions declared in the module won’t be added automatically to the
global scope.
268 JavaScript | © SmartCliff | Internal | Version 1.1
ES6
Executing Modules
message.js:
<!DOCTYPE html>
export let message = 'ES6 Modules'; <html>
<head>
<meta charset="utf-8"> <title>ES6 Modules</title>
app.js:
</head>
<body>
import { message } from './message.js'
<script type="module" src="./app.js"></script>
const h1 = document.createElement('h1');
</body>
h1.textContent = message;
</html>
document.body.appendChild(h1)
Exporting Modules
• To export a variable, a function, or a class, you place the export keyword in front of it.
• Allows you to define a variable, a function, or a class first and then export it later also.
log.js :
log.js :
let message = 'Hi';
export let message = 'Hi';
function getMessage() {
export function getMessage() {
return message;
return message; (OR) }
}
function setMessage(msg) {
export function setMessage(msg) {
message = msg;
message = msg;
}
}
export message, getMessage, setMessage;
Importing Modules
• Once you define a module with exports, you can access the exported variables, functions, and classes in
• Syntax:
• First, specify what to import inside the curly braces, which are called bindings.
• Then, specify the module from which you import the given bindings.
• When you import a binding from a module, the binding behaves like it was defined using const. It means
you can’t have another identifier with the same name or change the value of the binding.
271 JavaScript | © SmartCliff | Internal | Version 1.1
ES6
Importing Modules
// greeting.js // app.js
cal.js:
export let a = 10,
b = 20, app.js:
result = 0;
export function sum() { import {a, b, result, sum, multiply } from './cal.js';
result = a + b; sum();
return result; console.log(result); // 30
}
export function multiply() { multiply();
result = a * b; console.log(result); // 200
return result;
}
app.js:
app.js:
Classes
• A JavaScript class is a blueprint for creating objects. A class encapsulates data and functions that
manipulate data.
• Classes are the backbone of Object-oriented programming languages simply because they provide
• To create a class, we need to use the class keyword in curly brackets followed by the name of the class.
• Important note is that we need to use the constructor method whenever we use a class.
Creating Class
Class Expressions
Example:
• Similar to functions, classes have expression forms.
let Person = class {
constructor(name) {
• A class expression provides you with an alternative
this.name = name;
way to define a new class. }
Static Methods
• Static methods are not bounded to the instances rather they are bounded to the classes.
• Therefore, static methods are useful for defining helper or utility methods.
Example:
static createAnonymous(gender) {
class Person {
let name = gender == "male" ? "John
constructor(name) {
Doe" : "Jane Doe";
this.name = name;
return new Person(name);
}
}
getName() {
}
return this.name;
let anonymous = Person.createAnonymous("male");
}
280 JavaScript | © SmartCliff | Internal | Version 1.1
ES6 – Arrow Functions
Arrow Functions
• ES6 arrow functions provide you with an alternative way to write a shorter syntax compared to the
function expression.
• Arrow functions eliminate the need to use the return keyword, function keyword, and curly brackets.
• We can use arrow functions with other functions such as filter, reduce, map, etc.
• Note that you must define arrow functions before you use them.
Syntax:
let func = (arg1, arg2, ..., argN) => expression;
Example - 1:
let add = () => 10+20; Example - 4:
console.log(add()); // 30;
// Dynamic creation of functions
let age = prompt("What is your age?", 18);
Example - 2: // with parameter
let add = (x, y) => x + y;
let welcome = (age < 18) ?
console.log(add(10, 20)); // 30;
() => alert('Hello!') :
() => alert("Greetings!");
• An arrow function doesn’t have its own this value and the arguments object.
• Event Handlers
• Object Methods
• Prototype Methods
Iteration
• Iterable:
• An iterable is a data structure that wants to make its elements accessible to the public.
• Iterator:
• An iterator is a pointer for traversing the elements of a data structure (think cursors in databases)
Iteration Protocols
• There are two iteration protocols: iterable protocol and iterator protocol.
Iterator protocol
• An object is an iterator when it implements an interface (or API) that answers two questions:
• Is there any element left? And If there is, what is the element?
• An object is an iterator when it has a next() method that returns an object with two properties:
• done: a boolean value indicating whether there are any more elements that could be iterated upon.
• Each time you call the next(), it returns the next value in the collection
Iteration Protocols
Iterable protocol
• An object is iterable when it contains a method called [Symbol.iterator] that takes no argument and
returns an object which conforms to the iterator protocol.
Iterators
• Since ES6 provides built-in iterators for the collection types Array, Set, and Map, you don’t have to
create iterators for these objects.
• If you have a custom type and want to make it iterable so that you can use the for...of loop construct, you
need to implement the iteration protocols.
Iterators – Example
let result = { value: nextIndex, done: false }
Example : // Iterators
nextIndex += this.interval;
class Sequence {
counter++;
constructor( start = 0, end = Infinity, interval = 1 ) {
return result;
this.start = start;
}
this.end = end;
return { value: counter, done: true };
this.interval = interval;
}
}
}
[Symbol.iterator]() {
}
let counter = 0;
};
let nextIndex = this.start;
let evenNumbers = new Sequence(2, 10, 2);
return {
for (const num of evenNumbers) {
next: () => {
console.log(num);
if ( nextIndex <= this.end ) {
}
289 JavaScript | © SmartCliff | Internal | Version 1.1
ES6
Generators
• A regular function is executed based on the run-to-completion model. It cannot pause midway and then
• ES6 introduces a new kind of function that is different from a regular function: function generator or
generator.
• A generator can pause midway and then continues from where it paused.
• You can think of generators as processes (pieces of code) that you can pause and resume while
Generators – Examples
Example - 2:
Example - 1 : class Sequence {
function* forever() { constructor( start = 0, end = Infinity, interval = 1 ) {
this.start = start;
let index = 0;
this.end = end;
while (true) { this.interval = interval;
yield index++; }
* [Symbol.iterator]() {
}
for( let index = this.start; index <= this.end; index += this.interval ) {
} yield index;
}
let f = forever(); }
}
console.log(f.next()); // 0
let oddNumbers = new Sequence(1, 10, 2);
console.log(f.next()); // 1 for (const num of oddNumbers) {
console.log(f.next()); // 2 console.log(num);
}
291 JavaScript | © SmartCliff | Internal | Version 1.1
ES6 – Promises
Promises
• A Promise is a proxy for a value not necessarily known when the promise is created.
• It allows you to associate handlers with an asynchronous action's eventual success value or failure
reason.
Benefits of Promises
Promise – States
Creating a promise
• It may also be defined as a carrier which takes data from promise and further executes it successfully.
Syntax:
.then(function(result){
//handle success
}, function(error){
//handle error
})
• catch() is invoked when a promise is either rejected or some error has occurred in execution. It is used
Syntax:
.catch(function(error){
//handle error
})
• Sometimes, you want to execute the same piece of code whether the promise is fulfilled or rejected.
Syntax:
.finally(() => {
render();
})
Example - 1:
var promise = new Promise(function(resolve,
reject) {
promise.
const x = “admin";
then(function () {
const y = “admin"
console.log('Success, You are a valid person');
if(x === y) {
}).
resolve();
catch(function () {
} else {
console.log('Some error has occurred');
reject();
});
}
});
Example - 2: Example - 3:
var promise = new Promise(function(resolve, var promise = new Promise(function(resolve,
reject) { reject) {
resolve(‘Resolved'); reject('Rejected')
}) })
promise promise
.then(function(successMessage) { .then(function(successMessage) {
//success handler function is invoked console.log(successMessage);
console.log(successMessage); }, function(errorMessage) {
}, function(errorMessage) { //error handler function is invoked
console.log(errorMessage); console.log(errorMessage);
}) })
Promise Chaining
• Used to execute two or more related asynchronous operations, where the next operation starts with the
Collections: Map
• ES6 provides a new collection type called Map that addresses the following deficiencies of an object
mapping:
• A key of an object must be a string or a symbol, you cannot use an object as a key.
• An object does not have a property that represents the size of the map.
Map
• When iterating a Map object, each iteration returns a 2-dimentional array of [key, value].
• The iteration order follows the insertion order which corresponds to the order in which each key-value
pair was first inserted into the Map by the set() method.
• delete(key) – removes an element specified by the key. It returns if the element is in the map, or false if it
does not.
• entries() – returns a new Iterator object that contains an array of [key, value] for each element in the map
object. The order of objects in the map is the same as the insertion order.
• forEach(callback[, thisArg]) – invokes a callback for each key-value pair in the map in the insertion
order. The optional thisArg parameter sets the this value for each callback.
• get(key) – returns the value associated with the key. If the key does not exist, it returns undefined.
• has(key) – returns true if a value associated with the key exists or false otherwise.
• keys() – returns a new Iterator that contains the keys for elements in insertion order.
• set(key, value) – sets the value for the key in the map object. It returns the map object itself therefore
• values() – returns a new iterator object that contains values for each element in insertion order.
Collections: SET
• ES6 provides a new type named Set that stores a collection of values.
• A set is a collection of items that are unique i.e no element can be repeated.
• Set in ES6 are ordered: elements of the set can be iterated in the insertion order.
Syntax :
let setObject = new Set(iterableObject);
Creating Set
Example :
// it contains ["sumit","amit","anil","anish"]
var set1 = new Set(["sumit","sumit","amit","anil","anish"]);
// it is an empty set
var set4 = new Set();
• forEach(callback [, thisArg]) – calls a callback for each element with value sets to thisArg in each call.
• has(value) – returns true if an element with a given value is in the set, or false if it is not.
Synchronous Code
• When a line is completely executed, then and then only does the code move forward to execute the next
let greet_salute = "Hello"
line.
let greet_to= "World!!!"
console.log(greet_ salute)
for(let i=0;i<1000000000;i++){
}
console.log(greet_to);
• The execution order of the above code will be as follows:
• greet_salute logs first. Then it waits for a couple of seconds and then logs greet_to. This is called
Synchronous code.
• For example, if a certain piece of code takes 10 seconds to execute, the code after it won't be able to
• The reason for this is that this JavaScript program is single-threaded. A thread is a sequence of
• Because the program consists of a single thread, it can only do one thing at a time: so if it is waiting for
Solution
• Have that function start the operation and return immediately, so that our program can still be responsive
to other events.
• Have the function execute the operation in a way that does not block the main thread, for example by
Asynchronous Code
• JavaScript runs code sequentially in top-down order. However, there are some cases that code runs (or
must run) after something else happens and also not sequentially. This is asynchronous programming.
• Asynchronous programming is a technique that enables your program to start a potentially long-
running task and still be able to be responsive to other events while that task runs, rather than having to
• Once that task has finished, your program is presented with the result.
setTimeout(function, milliseconds)
• Let’s have a look at some techniques that are useful for asynchronous JavaScript:
• Async / await: It is a more recent technique for creating asynchronous JavaScript code. It helps you
write more succinct and readable code that will execute after a set period of time or when a set
condition is met.
• Promises: It enables you to create code that runs after a predetermined period of time or when a
Callback Function
• In JavaScript, functions are objects. So, we can also pass functions as parameters to other functions.
• A callback function is a function passed into another function as an argument, which is then invoked
• The caller is responsible for passing the right parameters into the callback function.
• The caller may also expect a particular return value from the callback function, which is used to instruct
Callback Function
• Synchronous
• Asynchronous
• Synchronous callbacks are called immediately after the invocation of the outer function, with no
• Asynchronous callbacks are called at some point later, after an asynchronous operation has
completed.
callback(param);
function consoleMyDetails(person){
if(person){
function consoleMyDetails(person) {
if (person) {
Asynchronous - Promise
• A promise is an object returned by an asynchronous function, which represents the current state of the
operation.
• At the time the promise is returned to the caller, the operation often isn't finished, but the promise object
• With a promise-based API, the asynchronous function starts the operation and returns a Promise object.
• You can then attach handlers to this promise object, and these handlers will be executed when the
);
console.log(fetchPromise);
fetchPromise.then((response) => {
});
console.log("Started request…");
Async / Await
• Since JavaScript is a synchronous language, Async functions let us write promise-based code as if it
were synchronous, but without blocking the execution thread that allows the code to run
asynchronously.
• Roughly, async functions provide better syntax for code that uses Promises.
• Adding async at the start of a function makes it an async function. It will always return a value.
• Using async implies that a promise will be returned. If a promise is not returned, JavaScript automatically
Async / Await
function example() {
console.log(example());
Async function without using Promise:
console.log(example());
Async / Await
• await is another useful keyword that is often used alongside async functions.
• The keyword await makes JavaScript wait until that promise settles and returns its result.
Async / Await
• This above code will give the error as above. The correct code has given below.
async function runProcess() {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const json = await response.json();
console.log(json)
}
runProcess();
329 JavaScript | © SmartCliff | Internal | Version 1.1
Asynchronous JS
Introduction
• Murphy’s law states that "Anything that can go wrong will go wrong.“ This is applies in the
• If you create an application, chances are you’ll create bugs and other issues. Errors in JavaScript are
• It can happen when a program doesn’t know how to handle the job at hand, such as when trying to open
a non-existent file or reaching out to a web-based API endpoint while there’s no network connectivity.
• The program collects as much information as possible about the error and then reports that it can not
move ahead.
Introduction
• Intelligent programmers try to predict and cover these scenarios so that the user doesn’t have to figure
• Instead, they show a much more understandable message: “The page could not be found.”
• Exception handling is a crucial aspect of writing robust and maintainable JavaScript code.
• It allows developers to manage errors gracefully, ensuring that the application continues to function,
• When a JavaScript statement results in an error, it’s said to throw an exception. JavaScript creates and
Error Object
• In JavaScript, errors are represented by the Error object or one of its subclasses.
• The Error object is a built-in object that provides a standard set of properties
• These standard and custom properties of Error helps to understand the cause and effects of the error.
• stack: The stack trace of the code executed when the error occurred.
Error Object
• Additionally, errors can also carry properties like columnNumber, lineNumber, fileName, etc., to describe
• However, these properties are not standard and may or may not be present in every error object
console.log(customError.name); // "Error"
Stack Trace
• A stack trace is the list of method calls a program was in when an event such as an exception or a
warning occurs.
• Syntax Errors: Syntax errors occur due to incorrect code structure, such as missing semicolons or
mismatched parentheses. These are typically caught by the JavaScript interpreter at compile time.
• Reference Errors: Reference errors occur when a developer attempts to access a variable or object that
doesn’t exist in the current scope. This can lead to a reference to an undefined variable or property.
• Type Errors: Type errors arise when there’s an attempt to perform an operation on a data type that’s
incompatible with the operation. An example is when you are trying to call a non-existent function or
• Range Errors: Range errors happen when an operation is performed outside the valid range, often
encountered with array manipulation, like accessing an index that doesn’t exist.
• Runtime Errors: Runtime errors occur during the execution of code and are often caused by logical
• Network Errors: These errors relate to network-related operations, such as failing to fetch resources
• Custom Errors: Developers can create custom errors to handle application-specific issues or exceptions
• The most fundamental way of handling errors that have been thrown either manually or by the runtime is
to catch them.
• Like most other languages, JavaScript offers a set of keywords to handle errors.
• throw:
• As evident, the throw keyword is used to throw errors to create exceptions in the JavaScript runtime
manually.
throw TypeError("Please provide a string")
• It allows you to execute a block of code and catch any exceptions that may occur during its execution.
• If an exception is thrown within the ‘try’ block, the code in the ‘catch’ block will be executed.
• It’s important to note that a catch block must always follow the try block to handle errors effectively.
try {
// business logic code
} catch (exception) {
// error handling code
}
342 JavaScript | © SmartCliff | Internal | Version 1.1
Exception Handling
function divide(a, b) {
if (b === 0) {
throw new Error('Division by zero is not allowed');
}
return a / b;
}
try {
const result = divide(10, 0);
console.log(result);
} catch (error) {
console.log(`An error occurred: ${error.message}`);
}
• The finally block is an optional part of the try-catch statement that is always executed, regardless of
• It is useful for performing cleanup tasks, such as closing resources or releasing memory.
try {
// Code that might throw an exception
} catch (error) {
// Handle the exception
} finally {
// Code to always execute, regardless of whether an exception occurred
}
finally – Example
try {
console.log('Resource closed'); }
Error Events
• When an error is not caught within a try-catch block, it propagates to the global level, triggering the error
event.
• You can attach an event listener to the window object to handle global errors:
• This technique is useful for logging unhandled errors or notifying users about issues.
Error Events
• You can listen for this event to handle unhandled promise rejections:
});
• The catch() method allows you to handle errors within a promise chain:
fetch('https://api.example.com/data')
• The async/await syntax allows you to handle errors in a more synchronous-like manner.
• You can use try-catch blocks within an async function to handle errors:
• To create more specific error types, you can extend the built-in Error class.
• This allows us to create custom error types with their own names and messages, making it easier to
super(message);
this.name = 'ValidationError';
}
}
class EmailValidationError extends ValidationError {
constructor(message) {
super(message);
this.name = 'EmailValidationError';
}
}
constructor(message) {
super(message);
this.name = 'PasswordValidationError';
if (!email.includes('@')) {
if (password.length < 8) {
throw new PasswordValidationError('Password must be at least 8 characters long');
}
return true;
}
try {
validateUserInput('invalidemail.com', 'short');
} catch (error) {
if (error instanceof ValidationError) {
console.log(`Validation error: ${error.message}`);
} else {
console.log(`Unknown error: ${error.message}`);
}
}