Java Script
Java Script
Client-side: It supplies objects to control a browser and its Document Object Model (DOM).
Like if client-side extensions allow an application to place elements on an HTML form and
respond to user events such as mouse clicks, form input, and page navigation. Use full
libraries for the client-side are AngularJS, ReactJS, VueJS and so many others.
Server-side: It supplies objects relevant to running JavaScript on a server. Like if the server-
side extensions allow an application to communicate with a database, and provide continuity
of information from one invocation to another of the application, or perform file
manipulations on a server. The useful framework which is the most famous these days
is [Link].
History of JavaScript:
It was created in 1995 by Brendan Eich while he was an engineer at Netscape.
It was originally going to be named LiveScript but was renamed.
Unlike most programming languages, the JavaScript language has no concept of input or
output.
It is designed to run as a scripting language in a host environment, and it is up to the host
environment to provide mechanisms for communicating with the outside world.
The most common host environment is the browser.
JS Structure:
<script type="text/javascript">
// Your javaScript code
</script>
JavaScript was created in the first place for DOM manipulation. Earlier websites were
mostly static, after JS was created dynamic Web sites were made.
Functions in JS are objects. They may have properties and methods just like another object.
They can be passed as arguments in other functions.
Performs Form Validation although the forms are created using HTML.
No compiler needed.
Web Applications: With technology, browsers have improved to the extent that a language
was required to create robust web applications. When we explore a map in Google Maps
then we only need to click and drag the mouse. All detailed view is just a click away, and
this is possible only because of JavaScript. It uses Application Programming
Interfaces(APIs) that provide extra power to the code. The Electron and React is helpful in
this department.
Server Applications: With the help of [Link], JavaScript made its way from client to
server and [Link] is the most powerful in the server-side.
Games: Not only in websites, JavaScript also helps in creating games for leisure. The
combination of JavaScript and HTML 5 makes JavaScript popular in game development as
well. It provides the EaseJS library which provides solutions for working with rich graphics.
Smartwatches: JavaScript is being used in all possible devices and applications. It provides
a library PebbleJS which is used in smartwatch applications. This framework works for
applications that require the internet for its functioning.
Art: Artists and designers can create whatever they want using JavaScript to draw on HTML
5 canvas, make sound more effective also can be used [Link] library.
Machine Learning: This JavaScript [Link] library can be used in web development by
using machine learning.
Advantages of JS:
JavaScript executed on the user’s browsers not on the webserver so it saves bandwidth and
load on the webserver.
The JavaScript language is easy to learn it offers syntax that is close to English language.
In JavaScript, if you ever need any certain feature then you can write it by yourself and use
an add-on like Greasemonkey to implement it on the web page.
It does not require a compilation process so no compiler is needed user’s browsers do the
task.
JavaScript is easy to debug, and there are lots of frameworks available that you can use and
become master on that.
Disadvantages of JS:
JavaScript codes are visible to the user so user can place some code into the site that
compromises the security of data over the website. That will be security issue.
All browsers interpret JavaScript that is correct, but they interpret differently to each other.
It only supports single inheritance, so in few cases may require the object-oriented
language characteristic.
A single error in code can totally stop the website’s code rendering on the website.
JavaScript stores number as a 64-bit floating-point number but operators operate on 32-bit
bitwise operands.
JavaScript Statements:
1. Semicolons:
Example:
<html>
<body>
<h2>Welcome</h2>
<p id="bit"></p>
<script type=”javascript”>
// Statement 1
var a, b, c;
// Statement 2
a = 2;
// Statement 3
b = 3;
// Statement 4
c = a + b;
[Link](
"bit").innerHTML =
"The value of c is " + c + ".";
</script>
</body>
</html>
2. Code Blocks:
JavaScript statements can be grouped together inside curly brackets.
Such groups are known as code blocks.
The purpose of grouping is to define statements to be executed together.
Example:JavaScript function
<html>
<body>
<p>Welcome</p>
<button type="button"
> Click Me!
</button>
<p id="para1"></p>
<p id="para2"></p>
<script>
function myFunction() {
3. White Space:
The best place to break a code line in Javascript, if it doesn’t fits, is after an operator.
Example:
[Link]("para").innerHTML =
"Hello Geek!";
5. Keywords:
Keywords are reserved words and cannot be used as variable name.
A Javascript keyword tells about what kind of operation it will perform.
continue: This is used to skip a particular iteration in a loop and move to next
iteration.
do…. while: In this the statements written within do block are executed till the
condition in while is true.
6. Comments in JavaScript
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands. For
example:
1. var sum=10+20;
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
40M
747
- Subtraction 20-10 = 10
/ Division 20/10 = 2
= Assign 10+10 = 20
Operator Description
(?:) Conditional Operator returns value based on the condition. It is like if-
else.
Method Description
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Operators</h2>
<p>x = 5, y = 2, calculate z = x + y, and display z:</p>
<p id="demo"></p>
<script>
let x = 5;
let y = 2;
let z = x + y;
[Link]("demo").innerHTML = z;
</script>
</body>
</html>
Example 2:
<!DOCTYPE html>
<html>
<body>
<h2>The += Operator</h2>
<p id="demo"></p>
<script>
var x = 10;
x += 5;
[Link]("demo").innerHTML = x;
</script>
</body>
</html>
Adding to String to number:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Operators</h2>
<p>adding a number and a string, returns a string.</p>
<p id="demo"></p>
<script>
let x = 5 + 5;
let y = "5" + 5;
let z = "Hello" + 5;
[Link]("demo").innerHTML =
x + "<br>" + y + "<br>" + z;
</script>
</body>
</html>
When the script needs to run on some event, such as when a user clicks somewhere, then that
script in the head as follows −
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert(“My World")
}
//-->
</script>
</head>
<body>
<input type = "button" value = "Click" />
</body>
</html>
When a script needs to run as the page loads so that the script generates content in the page,
then the script goes in the <body> portion of the document. In this case, it would not have any
function defined using JavaScript.
<html>
<head>
</head>
<body>
<script type = "text/javascript">
<!--
[Link]("Hello World")
//-->
</script>
We can include the JavaScript code in <head> and <body> section altogether as follows −
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<script type = "text/javascript">
<!--
[Link]("Hello World")
//-->
</script>
There exist some situation where we are reusing identical JavaScript code on multiple pages of
a site.
The script tag provides a mechanism to allow to store JavaScript in an external file and then
include it into your HTML files.
Here is an example to show how you can include an external JavaScript file in your HTML
code using script tag and its src attribute.
<html>
<head>
<script type = "text/javascript" src = "[Link]" ></script>
</head>
<body>
.......
</body>
</html>
JavaScript Variables
Like many other programming languages, JavaScript has variables. Variables can be thought of
as named containers. You can place data into these containers and then refer to the data simply
by naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are declared
with the var keyword as follows.
<script type = "text/javascript">
<!--
var money;
var name;
//-->
</script>
You can also declare multiple variables with the same var keyword as follows −
<script type = "text/javascript">
<!--
var money, name;
//-->
</script>
Storing a value in a variable is called variable initialization. You can do variable initialization
at the time of variable creation or at a later point in time when you need that variable.
For instance, you might create a variable named money and assign the value 2000.50 to it later.
For another variable, you can assign a value at the time of initialization as follows.
<script type = "text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>
The scope of a variable is the region of your program in which it is defined. JavaScript variables
have only two scopes.
Global Variables − A global variable has global scope which means it can be defined
anywhere in your JavaScript code.
Local Variables − A local variable will be visible only within a function where it is
defined. Function parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global variable with the
same name. If you declare a local variable or function parameter with the same name as a global
variable, you effectively hide the global variable.
<html>
<body > <script type = "text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
[Link](myVar);
}
//-->
</script>
</body>
</html>
While naming your variables in JavaScript, keep the following rules in mind.
You should not use any of the JavaScript reserved keywords as a variable name. These
keywords are mentioned in the next section. For example, break or boolean variable
names are not valid.
JavaScript variable names should not start with a numeral (0-9). They must begin with a
letter or an underscore character. For example, 123test is an invalid variable name
but _123test is a valid one.
JavaScript variable names are case-sensitive. For example, Name and name are two
different variables.
A list of all the reserved words in JavaScript are given in the following table. They cannot be
used as JavaScript variables, functions, methods, loop labels, or any object names.
double in super
Javascript Conditions:
JavaScript supports conditional statements which are used to perform different actions based on
different conditions. Here we will explain the if..else statement.
The following flow chart shows how the if-else statement works.
JavaScript supports the following forms of if..else statement −
if statement
if...else statement
if...else if... statement.
if statement
The if statement is the fundamental control statement that allows JavaScript to make decisions
and execute statements conditionally.
Syntax
The syntax for a basic if statement is as follows −
if (expression) {
Statement(s) to be executed if expression is true
}
Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s)
are executed. If the expression is false, then no statement would be not executed. Most of the
times, you will use comparison operators while making decisions.
Example
<html>
<body>
<script type = "text/javascript">
var age = 20;
}
</script>
<p id=”para1”>Set the variable to different value and then try...</p>
</body>
</html>
Output
Qualifies for driving
Set the variable to different value and then try...
if...else statement
The 'if...else' statement is the next form of control statement that allows JavaScript to execute
statements in a more controlled way.
Syntax
if (expression) {
Statement(s) to be executed if expression is true
} else {
Statement(s) to be executed if expression is false
}
Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in
the ‘if’ block, are executed. If the expression is false, then the given statement(s) in the else
block are executed.
Example
<html>
<body>
<script type = "text/javascript">
var age = 15;
Output
Does not qualify for driving
Set the variable to different value and then try...
The if...else if... statement is an advanced form of if…else that allows JavaScript to make a
correct decision out of several conditions.
Syntax
The syntax of an if-else-if statement is as follows −
if (expression 1) {
Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
Statement(s) to be executed if expression 3 is true
} else {
Statement(s) to be executed if no expression is true
}
There is nothing special about this code. It is just a series of if statements, where each if is a part
of the else clause of the previous statement. Statement(s) are executed based on the true
condition, if none of the conditions is true, then the else block is executed.
Example
<html>
<body>
<script type = "text/javascript">
var book = "maths";
if( book == "history" ) {
[Link]("<b>History Book</b>");
} else if( book == "maths" ) {
[Link]("<b>Maths Book</b>");
} else if( book == "economics" ) {
[Link]("<b>Economics Book</b>");
} else {
[Link]("<b>Unknown Book</b>");
}
</script>
<p>Set the variable to different value and then try...</p>
</body>
<html>
Output
Maths Book
Set the variable to different value and then try...
JavaScript supports all the necessary loops to ease down the pressure of programming.
The most basic loop in JavaScript is the while loop which would be discussed in this chapter.
The purpose of a while loop is to execute a statement or code block repeatedly as long as
an expression is true. Once the expression becomes false, the loop terminates.
Flow Chart
The flow chart of while loop looks as follows −
Syntax
The syntax of while loop in JavaScript is as follows −
while (expression) {
Statement(s) to be executed if expression is true
}
Example
<html>
<body>
[Link]("Loop stopped!");
</script>
Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
Set the variable to different value and then try...
The do...while loop is similar to the while loop except that the condition check happens at the
end of the loop. This means that the loop will always be executed at least once, even if the
condition is false.
Flow Chart
The flow chart of a do-while loop would be as follows −
Syntax
The syntax for do-while loop in JavaScript is as follows −
do {
Statement(s) to be executed;
} while (expression);
Example
<html>
<body>
<script type = "text/javascript">
var count = 0;
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Loop Stopped!
Set the variable to different value and then try...
The 'for' loop is the most compact form of looping. It includes the following three important
parts −
The loop initialization where we initialize our counter to a starting value. The
initialization statement is executed before the loop begins.
The test statement which will test if a given condition is true or not. If the condition is
true, then the code given inside the loop will be executed, otherwise the control will
come out of the loop.
The iteration statement where you can increase or decrease your counter.
You can put all the three parts in a single line separated by semicolons.
Flow Chart
Syntax
The syntax of for loop is JavaScript is as follows −
for (initialization; test condition; iteration statement) {
Statement(s) to be executed if test condition is true
}
Example
Try the following example to learn how a for loop works in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var count;
[Link]("Starting Loop" + "<br />");
Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
Set the variable to different value and then try...
JavaScript Popup Boxes
JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.
Alert Box
An alert box is often used if you want to make sure information comes through to the user.
When an alert box pops up, the user will have to click "OK" to proceed.
Syntax
[Link]("sometext");
<html>
<body>
<h2>JavaScript Alert</h2>
<script>
function myFunction() {
</script>
</body>
</html>
Confirm Box
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.
Syntax
[Link]("sometext");
<html>
<body>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
if (confirm("Press a button!")) {
} else {
[Link]("demo").innerHTML = txt;
</script>
</body>
</html>
Prompt Box
A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after
entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns
null.
Syntax
[Link]("sometext","defaultText");
<html>
<body>
<h2>JavaScript Prompt</h2>
<p id="demo"></p>
<script>
function myFunction() {
let text;
} else {
[Link]("demo").innerHTML = text;
</script>
</body>
</html>
External JavaScript
External scripts are practical when the same code is used in many different web pages.
To use an external script, put the name of the script file in the src (source) attribute of
a <script> tag:
You can place an external script reference in <head> or <body> as you like.
The script will behave as if it was located exactly where the <script> tag is located.
HTML File:
<html>
<body>
<h2>External JavaScript</h2>
<script src="[Link]"></script>
</body>
</html>
Advanced JavaScript
JavaScript is designed on a simple object-based paradigm.
An object is a collection of properties, and a property is an association between a name
(or key) and a value.
A property's value can be a function, in which case the property is known as a method.
Objects overview
Objects in JavaScript, just as in many other programming languages, can be compared to
objects in real life. The concept of objects in JavaScript can be understood with real life,
tangible objects.
In JavaScript, an object is a standalone entity, with properties and type. Compare it with a
cup, for example. A cup is an object, with properties.
A cup has a color, a design, weight, a material it is made of, etc. The same way, JavaScript
objects can have properties, which define their characteristics.
3. Object properties are basically the same as ordinary JavaScript variables, except for the
attachment to objects. The properties of an object define the characteristics of the object.
[Link]
Like all JavaScript variables, both the object name (which could be a normal variable) and
property name are case sensitive. We can define a property by assigning it a value. For
example, let's create an object named myCar and give it properties named make, model,
and year as follows:
It is written using an object initializer, which is a comma-delimited list of zero or more
pairs of property names and associated values of an object, enclosed in curly braces ({}):
var myCar = {
make: 'Ford',
model: 'Mustang',
year: 1969,
};
Unassigned properties of an object are undefined (and not null).
[Link]; // undefined
Properties of JavaScript objects can also be accessed or set using a bracket notation
Objects are sometimes called associative arrays, since each property is associated with a string
value that can be used to access it.
Syntax
for (variable in object) {
// code to be executed
}
The block of code inside of the for...in loop will be executed once for each property.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Object Properties</h2>
<p id="demo"></p>
<script>
var txt = "";
var person = {fname:"John", lname:"Doe", age:25};
var x;
for (x in person) {
txt =txt+ person[x] + " ";
}
[Link]("demo").innerHTML = txt;
</script>
</body>
</html>
You can add new properties to an existing object by simply giving it a value.
Assume that the person object already exists - you can then give it new properties:
<!DOCTYPE html>
<html>
<body>
[Link]("demo").innerHTML =
[Link] + " is from " + [Link] + ".";
</script>
</body>
</html>
Deleting Properties
The delete keyword deletes both the value of the property and the property itself.
After deletion, the property cannot be used before it is added back again.
The delete operator is designed to be used on object properties. It has no effect on variables or
functions.
The delete operator should not be used on predefined JavaScript object properties. It can crash
your application.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Object Properties</h2>
<p>You can delete object properties.</p>
<p id="demo"></p>
<script>
var person = {
firstname:"John",
lastname:"Doe",
age:50,
eyecolor:"blue"
};
delete [Link];
[Link]("demo").innerHTML =
[Link] + " is " + [Link] + " years old.";
</script>
</body>
</html>
Property Value
firstName John
lastName Doe
age 50
eyeColor Blue
<!DOCTYPE html>
<html>
<body>
<h2>The JavaScript <i>this</i> Keyword</h2>
<p>In this example, <b>this</b> represents the <b>person</b> object.</p>
<p>Because the person object "owns" the fullName method.</p>
<p id="demo"></p>
<script>
// Create an object:
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return [Link] + " " + [Link];
}
};
[Link]()
You will typically describe fullName() as a method of the person object, and fullName as a
property.
The fullName property will execute (as a function) when it is invoked with ().
<!DOCTYPE html>
<html>
<body>
<p>Creating and using an object method.</p>
<p>A method is actually a function definition stored as a property value.</p>
<p id="demo"></p>
<script>
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return [Link] + " " + [Link];
}
};
[Link]("demo").innerHTML = [Link]();
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
};
[Link] = function() {
return [Link] + " " + [Link];
};
[Link]("demo").innerHTML =
"My father is " + [Link]();
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Display Object Properties</h2>
<p id="demo"></p>
<script>
var person = {name:"John", age:50, city:"New York"};
[Link]("demo").innerHTML = [Link] + " " + [Link] + ","
+ [Link];
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Display Object Properties</h2>
<p id="demo"></p>
<script>
var x, txt = "";
var person = {name:"John", age:50, city:"New York"};
for (x in person) {
txt += person[x] + " ";
};
[Link]("demo").innerHTML = txt;
</script>
</body>
</html>
Using [Link]()
Syntax:
var person = {name:"John", age:30, city:"New York"};
Example program:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Display Objects</h2>
<p>[Link]() converts an object to an array.</p>
<p id="demo"></p>
<script>
var person = {name:"John", age:50, city:"New York"};
var myArray = [Link](person);
[Link]("demo").innerHTML = myArray;
</script>
</body>
</html>