Java Script
Java Script
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.
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.
There are different editions of ECMAScript. Most browsers have implemented ECMA-
262 5.1 edition.
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
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.
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.
<!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
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.
<!DOCTYPE html>
<html>
<head>
<script>
alert('Executing JavaScript 1')
</script>
</head>
<body>
<h1> JavaScript Tutorials</h1>
<script>
alert('Executing JavaScript 2')
</script>
<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.
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.
<!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.
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.
<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.
<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.
Whitespaces
JavaScript ignores multiple spaces and tabs. The following statements are the same.
Code Comments
A comment is single or multiple lines, which give some information about the current
program. Comments are not for execution.
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.
Number
JavaScript allows you to work with any type of number like integer, float,
hexadecimal etc. Number must NOT be wrapped in quotation marks.
Boolean
As in other languages, JavaScript also includes true and false as a boolean value.
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.
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:
<!DOCTYPE html>
<html>
<body>
<h1>Demo: alert()</h1>
<script>
alert("This is an alert message box."); // display string message
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.
var userPreference;
Example:
<!DOCTYPE html>
<html>
<body>
<h1>Demo: confirm()</h1>
<p id="msg"></p>
<script>
var userPreference;
} else {
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.
if (tenure != null) {
alert("You have entered " + tenure + " years" );
}
Try it
<!DOCTYPE html>
<html>
<body>
<h1>Demo: prompt()</h1>
<p id="msg"></p>
<script>
</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.
Syntax:
var <variable-name>;
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.
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>
<script>
var msg;
</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.
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>
var
one
=
1,
two
=
"two"
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.
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.
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
Example:
<!DOCTYPE html>
<html>
<body>
<script>
function myfunction(){
myfunction();
alert(greet);//can access global variable
</script>
</body>
</html>
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.
function myfunction(){
msg = "Hello JavaScript!";
}
myfunction();
alert(msg); // msg becomes global variable so can be accessed here
Points to Remember
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.
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:
<!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.
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.
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.
ShowMessage("Steve", "Jobs");
ShowMessage("Bill", "Gates");
ShowMessage(100, 200);
Try it
Example:
<!DOCTYPE html>
<html>
<body>
<script>
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.
function ShowMessage() {
alert("Hello " + arguments[0] + " " + arguments[1]);
}
ShowMessage("Steve", "Jobs");
Try it
Return Value
A function can return zero or one value using return keyword.
Example:
<!DOCTYPE html>
<html>
<body>
<p id="p1"></p>
<p id="p2"></p>
<script>
};
document.getElementById("p1").innerHTML = Sum(10,20);
};
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.
function multiple(x) {
function fn(y)
{
return x * y;
}
return fn;
}
<script>
function multiple(x) {
function fn(y)
{
return x * y;
}
return fn;
}
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.
<!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.
<!DOCTYPE html>
<html>
<body>
<script>
alert("Hello World!");
};
showMessage();
};
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.
<!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.
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:
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:
Second, the this value inside the event handler is equivalent to the event’s target element:
Third, the event handler can access the element’s properties, for example:
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:
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.
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:
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.
It is possible to add multiple event handlers to handle a single event, like this:
btn.addEventListener('click',function(event) {
alert('Clicked!');
});
Code language: JavaScript (javascript)
// 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.