Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 34

What is JavaScript

JavaScript is a programming language that executes on the browser. It turns static


HTML web pages into interactive web pages by dynamically updating content,
validating form data, controlling multimedia, animate images, and almost everything
else on the web pages.

JavaScript is the third most important web technology after HTML and CSS.
JavaScript can be used to create web and mobile applications, build web servers,
create games, etc.

JavaScript Example
JavaScript can be used in various activities like data validation, displaying popup
messages, handling events of HTML elements, modifying CSS, etc. The following
sample form uses JavaScript to validate data and change the color of the form.

First Name:
Middle Name:
Last Name:
Date of Birth:
Address:
City:
Zip Code:
Submit

The responsive UI and menu of this website is also using JavaScript. There is no
website in this world that does not use JavaScript or JavaScript-based frameworks.

JavaScript History
In early 1995, Brendan Eich from Netscape designed and implemented a new
language for non-java programmers to give newly added Java support in Netscape
navigator. It was initially named Mocha, then LiveScript, and finally JavaScript.

Nowadays, JavaScript can execute not only on browsers but also on the server or any
device with a JavaScript Engine . For example, Node.js is a framework based on
JavaScript that executes on the server.

JavaScript and ECMAScript


Often you will hear the term ECMAScript while working with JavaScript. Let's clear
the confusion before it arises.

As you now know, JavaScript was primarily developed to execute on browsers. There
are many different browsers from different companies. So, there was a need to
standardize the execution of the JavaScript code to achieve the same functionality in
all the browsers.

Ecma International is a non-profit organization that creates standards for


technologies. ECMA International publishes the specification for scripting languages is
called 'ECMAScript'. ECMAScript specification defined in ECMA-262 for creating a
general-purpose scripting language.

JavaScript implements the ECMAScript standards, which includes features specified in


ECMA-262 specification as well as other features which are not based on ECMAScript
standards.

There are different editions of ECMAScript. Most browsers have implemented ECMA-
262 5.1 edition.

 ECMA-262 5.1 edition, June 2011


 ECMA-262, 6th edition, June 2015
 ECMA-262, 7th edition, June 2016
 ECMA-262, 8th edition, June 2017
 ECMA-262, 9th edition, June 2018
 ECMA-262, 10th edition, June 2019

JavaScript Engine
JavaScript engine interprets, compiles, and executes JavaScript code. It also does
memory management, JIT compilation, type system, etc. Different browsers use
different JavaScript engines, as listed in the below table.
Setup JavaScript Development Environment
Here, we are going to use JavaScript in developing a web application. So, we must
have at least two things, a browser, and an editor to write the JavaScript code.

Although we also need a webserver to run a web application, but we will use a single
HTML web page to run our JavaScript code. So, no need to install it for now.

Browser
Mostly, you will have a browser already installed on your PC, Microsoft Edge on the
Windows platform, and Safari on Mac OS.

You can also install the following browser as per your preference:

 Microsoft Edge
 Google Chrome
 Mozilla FireFox
 Safari
 Opera

IDEs for JavaScript Application Development

You can write JavaScript code using a simple editor like Notepad. However, you can
install any open-sourced or licensed IDE (Integrated Development Environment) to
get the advantage of IntelliSense support for JavaScript and syntax error/warning
highlighter for rapid development.

The followings are some of the well-known JavaScript editors:

 Visual Studio Code (Free, cross-platform)


 Eclipse (Free, cross-platform)
 Atom (Free, cross-platform)
 Notepad++ (Free, Windows)
 Code Lobster (Free, cross-platform)
 WebStorm (Paid, cross-platform)

Online Editors for JavaScript


Use the online editor to quickly execute the JavaScript code without any installation.
The followings are free online editors:

 jsfiddle.net
 jsbin.com
 playcode.io
HTML <script> Tag
The HTML script tag <script> is used to embed data or executable client side
scripting language in an HTML page. Mostly, JavaScript or JavaScript based API code
inside a <script></script> tag.

The following is an example of an HTML page that contains the JavaScript code in
a <script> tag.

Example: JavaScript in a <script> Tag

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1> JavaScript Tutorials</h1>

<script>
//write JavaScript code here..
alert('Hello, how are you?')
</script>
</body>
</html>
Try it

In the above example, a <script></script> tag contains the JavaScript alert('Hello,


how are you?') that display a message box.

HTML v4 requires the type attribute to identify the language of script code embedded
within script tag. This is specified as MIME type e.g. 'text/javascript',
'text/ecmascript', 'text/vbscript', etc.

HTML v5 page does not require the type attribute because the default script language
is 'text/javascript' in a <script> tag.

An HTML page can contain multiple <script> tags in the <head> or <body> tag. The
browser executes all the script tags, starting from the first script tag from the
beginning.

Scripts without async, defer or type="module" attributes, as well as inline scripts, are
fetched and executed immediately, before the browser continues to parse the page.
Consider the following page with multiple script tags.

Example: Multiple <script> Tags

<!DOCTYPE html>
<html>
<head>
<script>
alert('Executing JavaScript 1')
</script>
</head>
<body>
<h1> JavaScript Tutorials</h1>

<script>
alert('Executing JavaScript 2')
</script>

<p>This page contains multiple script tags.</p>

<script>
alert('Executing JavaScript 3')
</script>
</body>
</html>
Try it

Above, the first <script> tag containing alert('Executing JavaScript 1') will be
executed first, then alert('Executing JavaScript 2') will be executed, and
then alert('Executing JavaScript 3') will be executed.

The browser loads all the scripts included in the <head> tag before loading and
rendering the <body> tag elements. So, always include JavaScript files/code in
the <head> that are going to be used while rendering the UI. All other scripts should
be placed before the ending </body> tag. This way, you can increase the page loading
speed.

Reference the External Script File


A <script> tag can also be used to include an external script file to an HTML web
page by using the src attribute.

If you don't want to write inline JavaScript code in the <script></script> tag, then
you can also write JavaScript code in a separate file with .js extension and include it
in a web page using <script> tag and reference the file via src attribute.

Example: JavaScript in a <script> Tag

<!DOCTYPE html>
<html>
<head>
<script src="/MyJavaScriptFile.js" ></script>
</head>
<body>
<h1> JavaScript Tutorials</h1>

</body>
</html>
Above, the <script src="/MyJavaScriptFile.js"> points to the external JavaScript file
using the src="/MyJavaScriptFile.js" attribute where the value of the src attribute is
the path or url from which a file needs to be loaded in the browser. Note that you can
load the files from your domain as well as other domains.

Global Attributes
The <script> can contain the following global attributes:

Attribute Usage
async <script async> executes the script asynchronously along
with the rest of the page.
crossorign <script crossorigin="anonymous|use-
credentials"> allows error logging for sites which use a
separate domain for static media. Value anonymous do not
send credentials, whereas use-credentials sends the
credentials.

defer <script defer> executes the script after the document is


parsed and before firing DOMContentLoaded event.

src <script src="uri\path to resource"> specifies the


URI/path of an external script file;
type <script type="text\javascript"> specifies the type of
the containing script e.g. text\javascript, text\html, text\plain,
application\json, application\pdf, etc.

referrerpolic <script referrerpolicy="no-referrer"> specifies


y which referrer information to send when fetching a script.
Values can be no-referrer, no-referrer-when-downgrade, origin,
same-origin, strict-origin, etc.
Attribute Usage
integrity <script integrity="sha384-
oqVuAfXRKap7fdgc"> specifies that a user agent can use to
verify that a fetched resource has been delivered free of
unexpected manipulation.
nomodule <script nomodule> specifies that the script should not be
executed in browsers supporting ES2015 modules.

JavaScript Syntax
Learn some important characteristics of JavaScript syntax in this section.

As mentioned in the previous chapter, JavaScript code can be written inside HTML
Script Tags or in a separate file with .js extension.

Write JavaScript Code

<script>
//Write javascript code here...

</script>

Character Set
JavaScript uses the unicode character set , so allows almost all characters,
punctuations, and symbols.

Case Sensitive
JavaScript is a case-sensitive scripting language. So, name of functions, variables
and keywords are case sensitive. For example, myfunction and MyFunction are
different, Name is not equal to nAme, etc.
Variables
In JavaScript, a variable is declared with or without the var keyword.

Example: JavaScript Statements

<script>
var name = "Steve";
id = 10;
</script>

Semicolon
JavaScript statements are separated by a semicolon. However, it is not mandatory to
end a statement with a semicolon, but it is recommended.

Example: JavaScript Statements


<script>
var one = 1; two = 2; three = 3; //three different statements

var four = 4; //single statement


var five = "Five" //single statement without ;
</script>

Whitespaces
JavaScript ignores multiple spaces and tabs. The following statements are the same.

Example: Whitespaces in JavaScript


<script>
var one =1;
var one = 1;
var one = 1;
</script>

Code Comments
A comment is single or multiple lines, which give some information about the current
program. Comments are not for execution.

Write comment after double slashes // or write multiple lines of comments


between /* and */

Example: Comment JavaScript Code


<script>
var one =1; // this is a single line comment
/* this
is multi line
comment*/

var two = 2;
var three = 3;
</script>

String
A string is a text in JavaScript. The text content must be enclosed in double or single
quotation marks.

Example: String in JavaScript


<script>
var msg = "Hello World" //JavaScript string in double quotes

var msg = 'Hello World' //JavaScript string in single quotes


</script>

Number
JavaScript allows you to work with any type of number like integer, float,
hexadecimal etc. Number must NOT be wrapped in quotation marks.

Example: Numbers in JavaScript


<script>
var num = 100;

var flot = 10.5;


</script>

Boolean
As in other languages, JavaScript also includes true and false as a boolean value.

Example: Booleans in JavaScript


<script>
var yes = true;

var no = false;
</script>

Keywords
Keywords are reserved words in JavaScript, which cannot be used as variable names
or function names.
The following table lists some of the keywords used in JavaScript.

JavaScript Reserved Keywords


var function if
else do while
for switch break
continue return try
catch finally debugger
case class this
default false true
in instanceOf typeOf
new null throw
void width delete

JavaScript Message Boxes: alert(), confirm(),


prompt()
JavaScript provides built-in global functions to display messages to users for different
purposes, e.g., displaying a simple message or displaying a message and take the
user's confirmation or displaying a popup to take the user's input value.

Alert Box
Use the alert() function to display a message to the user that requires their
attention. This alert box will have the OK button to close the alert box.

Example: JavaScript Alert Message

alert("This is an alert message box."); // display string message

alert('This is a numer: ' + 100); // display result of a concatenation

alert(100); // display number

alert(Date()); // display current date


Try it

Example:
<!DOCTYPE html>
<html>
<body>
<h1>Demo: alert()</h1>

<script>
alert("This is an alert message box."); // display string message

alert('This is a numer: ' + 100); // display result of a concatenation

alert(100); // display number

alert(Date()); // display current date


</script>
</body>
</html>

The alert() function takes a paramter of any type e.g., string, number, boolean etc.
So, no need to convert a non-string type to a string type.

Confirm Box
Sometimes you need to take the user's confirmation to proceed. For example, you
want to take the user's confirmation before saving updated data or deleting existing
data. In this scenario, use the built-in function confirm().

The confirm() function displays a popup message to the user with two
buttons, OK and Cancel. The confirm() function returns true if a user has clicked on
the OK button or returns false if clicked on the Cancel button. You can use the return
value to process further.

The following example demonstrates how to display a confirm box and then checks
which button the user has clicked.

Example: Confirm Box

var userPreference;

if (confirm("Do you want to save changes?") == true) {


userPreference = "Data saved successfully!";
} else {
userPreference = "Save Cancelled!";
}
Try it

Example:
<!DOCTYPE html>

<html>

<body>

<h1>Demo: confirm()</h1>

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

<script>

var userPreference;

if (confirm("Do you want to save changes?") == true) {

userPreference = "Data saved successfully!";

} else {

userPreference = "Save Canceled!";

document.getElementById("msg").innerHTML = userPreference;

</script>

</body>

</html>
Prompt Box
Sometimes you may need to take the user's input to do further actions. For example,
you want to calculate EMI based on the user's preferred tenure of the loan. For this
kind of scenario, use the built-in function prompt().

Syntax:
prompt([string message], [string defaultValue]);

The prompt() function takes two string parameters. The first parameter is the
message to be displayed, and the second parameter is the default value which will be
in input text when the message is displayed.

Example: Take User's Input using prompt()


var tenure = prompt("Please enter preferred tenure in years", "15");

if (tenure != null) {
alert("You have entered " + tenure + " years" );
}
Try it

<!DOCTYPE html>

<html>

<body>

<h1>Demo: prompt()</h1>

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

<script>

var tenure = prompt("Please enter preferred tenure in years",


"15");

document.getElementById("msg").innerHTML = "You have


entered " + tenure + " years";

</script>

</body>
</html>

In the above example, the first parameter is a message, and the second parameter is
"15" which will be shown to users by default. The prompt() function returns a user
entered value. If a user has not entered anything, then it returns null. So it is
recommended to check null before proceeding.

Note:
The alert(), confirm(), and prompt() functions are global functions. So, they can be called
using the window object e.g. window.alert(), window.confirm(), and window.prompt().

JavaScript Variables
Variable means anything that can vary. In JavaScript, a variable stores the data
value that can be changed later on.

Use the reserved keyword var to declare a variable in JavaScript.

Syntax:

var <variable-name>;

var <variable-name> = <value>;

A variable must have a unique name. The following declares a variable.

Example: Variable Declaration

var msg; // declaring a variable without assigning a value

Above, the var msg; is a variable declaration. It does not have any value yet. The
default value of variables that do not have any value is undefined.

You can assign a value to a variable using the = operator when you declare it or after
the declaration and before accessing it.

Example: Variable Initialization

var msg;
msg = "Hello JavaScript!"; // assigned a string value
alert(msg); // access a variable
//the following declares and assign a numeric value
var num = 100;
var hundred = num; // assigned a variable to varible

Example:

<!DOCTYPE html>

<html>

<body>

<h1>Demo: JavaScript Variables </h1>

<script>

var msg;

msg = "Hello JavaScript!"; // assigned a string value

alert(msg); // access a variable

//the following declares and assign a numeric value

var num = 100;

var hundred = num; // assigned a variable to varible

alert(num); // access a variable

alert(hundred); // access a variable

</script>

</body>

</html>
In the above example, the msg variable is declared first and then assigned
a string value in the next statement. The num variable is declared and initialized with
a numeric value in the same statement. Finally, the hundred variable is declared and
initialized with another variable's value.

Multiple Variables Declaration

Multiple variables can also be declared in a single line separated by a comma.

Example: Multiple Variables in a Single Line

var one = 1, two = 'two', three;

Example:

<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript Variables </h1>

<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>

<script>
var one = 1, two = 'two', three;

document.getElementById("p1").innerHTML = one;
document.getElementById("p2").innerHTML = two;
document.getElementById("p3").innerHTML = three;
</script>
</body>
</html>

White Spaces and Line Breaks in Variable Declaration


JavaScript allows multiple white spaces and line breaks when you declare a variable
with var keyword.

Example: Whitespace and Line Breaks

var
one
=

1,
two
=
"two"

Please note that the semicolon ; at the end is optional.


Loosely-typed Variables
C# or Java has strongly typed variables. It means a variable must be declared with
the data type that specifies the type of data a variable will store.

JavaScript is a loosely typed language. It means it does not require a data type to be
declared. You can assign any literal values to a variable, e.g., string, integer, float,
boolean, etc.

Example: Loosely Typed Variables

var myvariable = 1; // numeric value

myvariable = 'one'; // string value

myvariable = 1.1; // decimal value

myvariable = true; // Boolean value

myvariable = null; // null value

Variable Scope
In JavaScript, a variable can be declared either in the global scope or the local scope.

Global Variables

Variables declared out of any function are called global variables. They can be
accessed anywhere in the JavaScript code, even inside any function.

Local Variables

Variables declared inside the function are called local variables to that function. They
can only be accessed in the function where they are declared but not outside.

The following example includes global and local variables.

Example: Global and Local Variable

var greet = "Hello " // global variable

function myfunction(){
var msg = "JavaScript!";
alert(greet + msg); //can access global and local variable
}

myfunction();
alert(greet);//can access global variable
alert(msg); //error: can't access local variable

Learn global and local scope in JavaScript for more information.

Example:

<!DOCTYPE html>

<html>

<body>

<h1>Demo: JavaScript Global and Local Variables </h1>

<script>

var greet = "Hello " // global variable

function myfunction(){

var msg = "JavaScript!"; //local variable

alert(greet + msg); // access global and local variable

myfunction();
alert(greet);//can access global variable

alert(msg); //error: can't access local variable

</script>

</body>

</html>

Declare Variables without the var Keyword


Variables can be declared and initialize without the var keyword. However, a value
must be assigned to a variable declared without the var keyword.

The variables declared without the var keyword becomes global variables,
irrespective of where they are declared. Visit Variable Scope in JavaScript to learn
about it.

It is Not Recommended to declare a variable without var keyword because it can


accidentally overwrite an existing global variable.

Example: Variable Declaration Without var Keyword

function myfunction(){
msg = "Hello JavaScript!";
}
myfunction();
alert(msg); // msg becomes global variable so can be accessed here

Variable Names in JavaScript


 Variable names are case-sensitive in JavaScript. So, the variable
names msg, MSG, Msg, mSg are considered separate variables.
 Variable names can contain letters, digits, or the symbols $ and _.
 A variable name cannot start with a digit 0-9.
 A variable name cannot be a reserved keyword in JavaScript, e.g. var, function,
return cannot be variable names.

Points to Remember

1. Variable stores data value that can be changed later on.


2. Variables can be defined using var keyword. Variables defined without var keyword
become global variables.
3. Variables must be initialized before accessing it.
4. JavaScript allows multiple white spaces and line breaks in a variable declaration.
5. Multiple variables can be defined in a single line separated by a comma.
6. JavaScript is a loosely-typed language, so a variable can store any type value.
7. Variable names are case-sensitive.
8. Variable names can contain letters, digits, or the symbols $ and _. It cannot start with
a digit 0 - 9.
9. Variables can have local or global scope. Local variables cannot be accessed out of the
function where they are declared, whereas the global variables can be accessed from
anywhere.

JavaScript Functions
JavaScript provides functions similar to most of the scripting and programming
languages.

In JavaScript, a function allows you to define a block of code, give it a name and
then execute it as many times as you want.

A JavaScript function can be defined using function keyword.

Syntax:
//defining a function
function <function-name>()
{
// code to be executed
};

//calling a function
<function-name>();

The following example shows how to define and call a function in JavaScript.

Example: Define and Call a Function


function ShowMessage() {
alert("Hello World!");
}
ShowMessage();

Example:

<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript function</h1>

<script>
function ShowMessage() {
alert("Hello World!");
}

ShowMessage();
</script>
</body>
</html>
Try it

In the above example, we have defined a function named ShowMessage that displays
a popup message "Hello World!". This function can be execute using () operator e.g.
ShowMessage().

Function Parameters
A function can have one or more parameters, which will be supplied by the calling
code and can be used inside a function. JavaScript is a dynamic type scripting
language, so a function parameter can have value of any data type.

Example: Function Parameters


function ShowMessage(firstName, lastName) {
alert("Hello " + firstName + " " + lastName);
}

ShowMessage("Steve", "Jobs");
ShowMessage("Bill", "Gates");
ShowMessage(100, 200);
Try it

Example:

<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript function parameters</h1>

<script>
function ShowMessage(firstName, lastName) {
alert("Hello " + firstName + " " + lastName);
}
ShowMessage("Steve", "Jobs");
ShowMessage("Bill", "Gates");
ShowMessage(100, 200);

</script>
</body>
</html>

You can pass less or more arguments while calling a function. If you pass less
arguments then rest of the parameters will be undefined. If you pass more
arguments then additional arguments will be ignored.

Example: Function Parameters


function ShowMessage(firstName, lastName) {
alert("Hello " + firstName + " " + lastName);
}

ShowMessage("Steve", "Jobs", "Mr."); // display Hello Steve Jobs


ShowMessage("Bill"); // display Hello Bill undefined
ShowMessage(); // display Hello undefined undefined

The Arguments Object


All the functions in JavaScript can use arguments object by default. An arguments
object includes value of each parameter.

The arguments object is an array like object. You can access its values using index
similar to array. However, it does not support array methods.

Example: Arguments Object

function ShowMessage(firstName, lastName) {


alert("Hello " + arguments[0] + " " + arguments[1]);
}

ShowMessage("Steve", "Jobs");

ShowMessage("Bill", "Gates");

ShowMessage(100, 200);
Try it

Example:

<!DOCTYPE html>
<html>

<body>

<h1>Demo: JavaScript arguments object</h1>

<script>

function ShowMessage(firstName, lastName) {

alert("Hello " + arguments[0] + " " + arguments[1]);

ShowMessage("Steve", "Jobs");

ShowMessage("Bill", "Gates");

ShowMessage(100, 200);

</script>

</body>

</html>

An arguments object is still valid even if function does not include any parameters.

Example: Arguments Object

function ShowMessage() {
alert("Hello " + arguments[0] + " " + arguments[1]);
}

ShowMessage("Steve", "Jobs"); // display Hello Steve Jobs


Try it

An arguments object can be iterated using for loop.

Example: Iterate all Arguments


function ShowMessage() {
for(var i = 0; i < arguments.length; i++){
alert(arguments[i]);
}
}

ShowMessage("Steve", "Jobs");
Try it

Return Value
A function can return zero or one value using return keyword.

Example: Return value From a Function


function Sum(val1, val2) {
return val1 + val2;
};

var result = Sum(10,20); // returns 30

function Multiply(val1, val2) {


console.log( val1 * val2);
};

result = Multiply(10,20); // undefined


Try it

Example:

<!DOCTYPE html>

<html>

<body>

<h1>Demo: JavaScript arguments object</h1>

<p id="p1"></p>

<p id="p2"></p>

<script>

function Sum(val1, val2) {


return val1 + val2;

};

document.getElementById("p1").innerHTML = Sum(10,20);

function Multiply(val1, val2) {

console.log( val1 * val2);

};

document.getElementById("p2").innerHTML = Multiply(10,20);

</script>

</body>

</html>

In the above example, a function named Sum adds val1 & val2 and return it. So the
calling code can get the return value and assign it to a variable. The second function
Multiply does not return any value, so result variable will be undefined.

A function can return another function in JavaScript.

Example: Function Returning a Function

function multiple(x) {

function fn(y)
{
return x * y;
}

return fn;
}

var triple = multiple(3);


triple(2); // returns 6
triple(3); // returns 9
Try it
Example:
<!DOCTYPE html>
<html>
<body>
<h1>Demo: Function returing a function</h1>
<p id="p1"></p>
<p id="p2"></p>

<script>
function multiple(x) {

function fn(y)
{
return x * y;
}

return fn;
}

var triple = multiple(3);

document.getElementById("p1").innerHTML = triple(2);
document.getElementById("p2").innerHTML = triple(3);
</script>
</body>
</html>

Function Expression
JavaScript allows us to assign a function to a variable and then use that variable as a
function. It is called function expression.

Example: Function Expression


var add = function sum(val1, val2) {
return val1 + val2;
};

var result1 = add(10,20);


var result2 = sum(10,20); // not valid
Try it
Example:

<!DOCTYPE html>
<html>
<body>
<h1>Demo: Function expression</h1>
<p id="p1"></p>
<p id="p2"></p>

<script>
var add = function sum(val1, val2) {
return val1 + val2;
};

document.getElementById("p1").innerHTML = add(10,20);
document.getElementById("p2").innerHTML = sum(10,20); // not valid
</script>
</body>
</html>

Anonymous Function

Anonymous function is useful in passing callback function, creating closure or Immediately invoked
function expression.

JavaScript allows us to define a function without any name. This unnamed function is
called anonymous function. Anonymous function must be assigned to a variable.

Example: Anonymous Function

<!DOCTYPE html>

<html>

<body>

<h1>Demo: Anonymous Function</h1>

<script>

var showMessage = function (){

alert("Hello World!");

};

showMessage();

var sayHello = function (firstName) {

alert("Hello " + firstName);

};

showMessage();

sayHello("Bill");
</script>

</body>

</html>

Nested Functions
In JavaScript, a function can have one or more inner functions. These nested
functions are in the scope of outer function. Inner function can access variables and
parameters of outer function. However, outer function cannot access variables
defined inside inner functions.

Example: Nested Functions

<!DOCTYPE html>
<html>
<body>
<h1>Demo: Nested Function</h1>

<script>
function ShowMessage(firstName)
{
function SayHello() {
alert("Hello " + firstName);
}

return SayHello();
}

ShowMessage("Steve");

</script>
</body>
</html>Try it

Points to Remember :

1. JavaScript a function allows you to define a block of code, give it a name and then
execute it as many times as you want.
2. A function can be defined using function keyword and can be executed using ()
operator.
3. A function can include one or more parameters. It is optional to specify function
parameter values while executing it.
4. JavaScript is a loosely-typed language. A function parameter can hold value of any
data type.
5. You can specify less or more arguments while calling function.
6. All the functions can access arguments object by default instead of parameter names.
7. A function can return a literal value or another function.
8. A function can be assigned to a variable with different name.
9. JavaScript allows you to create anonymous functions that must be assigned to a
variable.
Handling Events in JavaScript

When an event occurs, you can create an event handler which is a piece of code that will execute to
respond to that event. An event handler is also known as an event listener. It listens to the event and
responds accordingly to the event fires.

An event listener is a function with an explicit name if it is resuable or an anonymous function in case it is
used one time.

An event can be handled by one or multiple event handlers. If an event has multiple event handlers, all
the event handlers will be executed when the event is fired.

There are three ways to assign event handlers.

1) HTML event handler attributes


Event handlers typically have names that begin with on, for example, the event handler for the click event
is onclick.

To assign an event handler to an event associated with an HTML element, you can use an HTML attribute
with the name of the event handler. For example, to execute some code when a button is clicked, you use
the following:

<input type="button" value="Save" onclick="alert('Clicked!')">


Code language: HTML, XML (xml)

In this case, when the button is clicked, the alert box is shown.

When you assign JavaScript code as the value of the onclick attribute, you need to escape the HTML
characters such as ampersand (&), double quotes ("), less than (<), etc., or you will get a syntax error.

An event handler defined in the HTML can call a function defined in a script. For example:

<script>
function showAlert() {
alert('Clicked!');
}
</script>
<input type="button" value="Save" onclick="showAlert()">
Code language: HTML, XML (xml)

In this example, the button calls the showAlert() function when it is clicked.
The showAlert() is a function defined in a separate <script> element, and could be placed in an external
JavaScript file.

Important notes

The following are some important points when you use the event handlers as attributes of the HTML
element:

First, the code in the event handler can access the event object without explicitly defining it:

<input type="button" value="Save" onclick="alert(event.type)">


Code language: HTML, XML (xml)

Second, the this value inside the event handler is equivalent to the event’s target element:

<input type="button" value="Save" onclick="alert(this.value)">


Code language: HTML, XML (xml)

Third, the event handler can access the element’s properties, for example:

<input type="button" value="Save" onclick="alert(value)">


Code language: HTML, XML (xml)

Disadvantages of using HTML event handler attributes

Assigning event handlers using HTML event handler attributes are considered as bad practices and should
be avoided as much as possible because of the following reasons:

First, the event handler code is mixed with the HTML code, which will make the code more difficult to
maintain and extend.

Second, it is a timing issue. If the element is loaded fully before the JavaScript code, users can start
interacting with the element on the webpage which will cause an error.

For example, suppose that the following showAlert() function is defined in an external JavaScript file:

<input type="button" value="Save" onclick="showAlert()">


Code language: HTML, XML (xml)

And when the page is loaded fully and the JavaScript has not been loaded, the showAlert() function is
undefined. If users click the button at this moment, an error will occur.

2) DOM Level 0 event handlers


Each element has event handler properties such as onclick. To assign an event handler, you set the
property to a function as shown in the example:

let btn = document.querySelector('#btn');


btn.onclick = function() {
alert('Clicked!');
};
Code language: JavaScript (javascript)

In this case, the anonymous function becomes the method of the button element. Therefore, the this value
is equivalent to the element. And you can access the element’s properties inside the event handler:

let btn = document.querySelector('#btn');

btn.onclick = function() {
alert(this.id);
};
Code language: JavaScript (javascript)

Output:

btn

By using the this value inside the event handler, you can access the element’s properties and methods.

To remove the event handler, you set the value of the event handler property to null:

btn.onclick = null;
Code language: JavaScript (javascript)

The DOM Level 0 event handlers are still being used widely because of its simplicity and cross-browser
support.

3) DOM Level 2 event handlers


DOM Level 2 Event Handlers provide two main methods for dealing with the registering/deregistering
event listeners:

 addEventListener() – register an event handler


 removeEventListener() – remove an event handler

These methods are available in all DOM nodes.

The addEventListener() method


The addEventListener() method accepts three arguments: an event name, an event handler function, and a
Boolean value that instructs the method to call the event handler during the capture phase (true) or during
the bubble phase (false). For example:

let btn = document.querySelector('#btn');


btn.addEventListener('click',function(event) {
alert(event.type); // click
});
Code language: JavaScript (javascript)

It is possible to add multiple event handlers to handle a single event, like this:

let btn = document.querySelector('#btn');


btn.addEventListener('click',function(event) {
alert(event.type); // click
});

btn.addEventListener('click',function(event) {
alert('Clicked!');
});
Code language: JavaScript (javascript)

The removeEventListener() method


The removeEventListener() removes an event listener that was added via the addEventListener(). However,
you need to pass the same arguments as were passed to the addEventListener(). For example:

let btn = document.querySelector('#btn');

// add the event listener


let showAlert = function() {
alert('Clicked!');
};
btn.addEventListener('click', showAlert);

// remove the event listener


btn.removeEventListener('click', showAlert);
Code language: JavaScript (javascript)

Using an anonymous event listener as the following will not work:

let btn = document.querySelector('#btn');


btn.addEventListener('click',function() {
alert('Clicked!');
});

// won't work
btn.removeEventListener('click', function() {
alert('Clicked!');
});
Code language: JavaScript (javascript)

Summary
 There are three ways to assign an event handler: HTML event handler attribute, element’s event
handler property, and addEventListener().
 Assign an event handler via the HTML event handler attribute should be avoided.

You might also like