MMC105 WEB TECHNOLOGIES(JAVASCRIPT)
Learn JavaScript Tutorial
Our JavaScript Tutorial is designed for beginners and professionals both. JavaScript
is used to create client-side dynamic pages.
JavaScript is an object-based scripting language which is lightweight and cross-
platform.
JavaScript is not a compiled language, but it is a translated language. The JavaScript
Translator (embedded in the browser) is responsible for translating the JavaScript
code for the web browser.
What is JavaScript
JavaScript (js) is a light-weight object-oriented programming language which is used
by several websites for scripting the webpages. It is an interpreted, full-fledged
programming language that enables dynamic interactivity on websites when applied
to an HTML document. It was introduced in the year 1995 for adding programs to
the webpages in the Netscape Navigator browser. Since then, it has been adopted by
all other graphical web browsers. With JavaScript, users can build modern web
applications to interact directly without reloading the page every time. The
traditional website uses js to provide several forms of interactivity and simplicity.
Although, JavaScript has no connectivity with Java programming language. The name
was suggested and provided in the times when Java was gaining popularity in the
market. In addition to web browsers, databases such as CouchDB and MongoDB uses
JavaScript as their scripting and query language.
Features of JavaScript
1 PROF.SACHIN.G.A,
CIT,MANDYA
MMC105 WEB TECHNOLOGIES(JAVASCRIPT)
There are following features of JavaScript:
1. All popular web browsers support JavaScript as they provide built-in execution
environments.
2. JavaScript follows the syntax and structure of the C programming language.
Thus, it is a structured programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast
(depending on the operation).
4. JavaScript is an object-oriented programming language that uses prototypes
rather than using classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including, Windows,
macOS, etc.
8. It provides good control to the users over the web browsers.
History of JavaScript
In 1993, Mosaic, the first popular web browser, came into existence. In the year
1994, Netscape was founded by Marc Andreessen. He realized that the web
needed to become more dynamic. Thus, a 'glue language' was believed to be
provided to HTML to make web designing easy for designers and part-time
programmers. Consequently, in 1995, the company recruited Brendan Eich intending
to implement and embed Scheme programming language to the browser. But,
before Brendan could start, the company merged with Sun Microsystems for adding
Java into its Navigator so that it could compete with Microsoft over the web
technologies and platforms. Now, two languages were there: Java and the scripting
language. Further, Netscape decided to give a similar name to the scripting language
as Java's. It led to 'Javascript'. Finally, in May 1995, Marc Andreessen coined the first
code of Javascript named 'Mocha'. Later, the marketing team replaced the name with
'LiveScript'. But, due to trademark reasons and certain other reasons, in December
1995, the language was finally renamed to 'JavaScript'. From then, JavaScript came
into existence.
Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used for:
2 PROF.SACHIN.G.A,
CIT,MANDYA
MMC105 WEB TECHNOLOGIES(JAVASCRIPT)
o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm
dialog box and prompt dialog box),
o Displaying clocks etc.
JavaScript Example
1. <script>
2. document.write("Hello JavaScript by JavaScript");
3. </script>
3 Places to put JavaScript code
1. Between the body tag of html
2. Between the head tag of html
3. In .js file (external javaScript)
1) JavaScript Example : code between the body tag
In the above example, we have displayed the dynamic content using JavaScript. Let’s
see the simple example of JavaScript that displays alert dialog box.
1. <script type="text/javascript">
2. alert("Hello Javatpoint");
3. </script>
Test it Now
2) JavaScript Example : code between the head tag
Let’s see the same example of displaying alert dialog box of JavaScript that is
contained inside the head tag.
In this example, we are creating a function msg(). To create function in JavaScript,
you need to write function with function_name as given below.
3 PROF.SACHIN.G.A,
CIT,MANDYA
MMC105 WEB TECHNOLOGIES(JAVASCRIPT)
To call function, you need to work on event. Here we are using onclick event to call
msg() function.
1. <html>
2. <head>
3. <script type="text/javascript">
4. function msg(){
5. alert("Hello Javatpoint");
6. }
7. </script>
8. </head>
9. <body>
10. <p>Welcome to JavaScript</p>
11. <form>
12. <input type="button" value="click" onclick="msg()"/>
13. </form>
14. </body>
15. </html>
External JavaScript file
We can create external JavaScript file and embed it in many html page.
It provides code re usability because single JavaScript file can be used in several
html pages.
An external JavaScript file must be saved by .js extension. It is recommended to
embed all JavaScript files into a single file. It increases the speed of the webpage.
Let's create an external JavaScript file that prints Hello Javatpoint in a alert dialog
box.
message.js
1. function msg(){
2. alert("Hello Javatpoint");
3. }
Let's include the JavaScript file into html page. It calls the JavaScript function on
button click.
4 PROF.SACHIN.G.A,
CIT,MANDYA
MMC105 WEB TECHNOLOGIES(JAVASCRIPT)
index.html
1. <html>
2. <head>
3. <script type="text/javascript" src="message.js"></script>
4. </head>
5. <body>
6. <p>Welcome to JavaScript</p>
7. <form>
8. <input type="button" value="click" onclick="msg()"/>
9. </form>
10. </body>
11. </html>
Advantages of External JavaScript
There will be following benefits if a user creates an external javascript:
1. It helps in the reusability of code in more than one HTML file.
2. It allows easy code readability.
3. It is time-efficient as web browsers cache the external js files, which further
reduces the page loading time.
4. It enables both web designers and coders to work with html and js files
parallelly and separately, i.e., without facing any code conflictions.
5. The length of the code reduces as only we need to specify the location of the
js file.
Disadvantages of External JavaScript
There are the following disadvantages of external files:
1. The stealer may download the coder's code using the url of the js file.
2. If two js files are dependent on one another, then a failure in one file may
affect the execution of the other dependent file.
3. The web browser needs to make an additional http request to get the js code.
4. A tiny to a large change in the js code may cause unexpected results in all its
dependent files.
5 PROF.SACHIN.G.A,
CIT,MANDYA
MMC105 WEB TECHNOLOGIES(JAVASCRIPT)
5. We need to check each file that depends on the commonly created external
javascript file.
6. If it is a few lines of code, then better to implement the internal javascript
code.
JavaScript Variables
Variables in JavaScript can be declared using var, let, or const. JavaScript is dynamically typed, so
variable types are determined at runtime without explicit type definitions.
JavaScript var keyword
JavaScript let keyword
JavaScript const keyword
var a = 10 // Old style
let b = 20; // Prferred for non-const
const c = 30; // Preferred for const (cannot be changed)
console.log(a);
console.log(b);
console.log(c);
Output
10
20
30
Declaring Variables in JavaScript
1. JavaScript var keyword
6 PROF.SACHIN.G.A,
CIT,MANDYA
MMC105 WEB TECHNOLOGIES(JAVASCRIPT)
var is a keyword in JavaScript used to declare variables and it is Function-scoped and hoisted,
allowing redeclaration but can lead to unexpected bugs.
var a = "Hello Geeks";
var b = 10;
console.log(a);
console.log(b);
2. JavaScript let keyword
let is a keyword in JavaScript used to declare variables and it is Block-scoped and not hoisted to the
top, suitable for mutable variables
let a = 12
let b = "gfg";
console.log(a);
console.log(b);
3. JavaScript const keyword
const is a keyword in JavaScript used to declare variables and it is Block-scoped, immutable bindings
that can’t be reassigned, though objects can still be mutated.
const a = 5
let b = "gfg";
console.log(a);
console.log(b);
Rules for Naming Variables
When naming variables in JavaScript, follow these rules
7 PROF.SACHIN.G.A,
CIT,MANDYA
MMC105 WEB TECHNOLOGIES(JAVASCRIPT)
Variable names must begin with a letter, underscore (_), or dollar sign ($).
Subsequent characters can be letters, numbers, underscores, or dollar signs.
Variable names are case-sensitive (e.g., age and Age are different variables).
Reserved keywords (like function, class, return, etc.) cannot be used as variable names.
let userName = "Suman"; // Valid
let $price = 100; // Valid
let _temp = 0; // Valid
let 123name = "Ajay"; // Invalid
let function = "gfg"; // Invalid
Controls Statements
JavaScript If-else
The JavaScript if-else statement is used to execute the code whether condition is
true or false. There are three forms of if statement in JavaScript.
1. If Statement
2. If else statement
3. if else if statement
JavaScript If statement
It evaluates the content only if expression is true. The signature of JavaScript if
statement is given below.
1. if(expression){
2. //content to be evaluated
3. }
Flowchart of JavaScript If statement
8 PROF.SACHIN.G.A,
CIT,MANDYA
MMC105 WEB TECHNOLOGIES(JAVASCRIPT)
Let’s see the simple example of if statement in javascript.
1. <script>
2. var a=20;
3. if(a>10){
4. document.write("value of a is greater than 10");
5. }
6. </script>
Output of the above example
value of a is greater than 10
JavaScript If...else Statement
9 PROF.SACHIN.G.A,
CIT,MANDYA
MMC105 WEB TECHNOLOGIES(JAVASCRIPT)
It evaluates the content whether condition is true of false. The syntax of JavaScript if-
else statement is given below.
1. if(expression){
2. //content to be evaluated if condition is true
3. }
4. else{
5. //content to be evaluated if condition is false
6. }
Flowchart of JavaScript If...else statement
Let’s see the example of if-else statement in JavaScript to find out the even or odd
number.
1. <script>
2. var a=20;
3. if(a%2==0){
4. document.write("a is even number");
5. }
6. else{
7. document.write("a is odd number");
10 PROF.SACHIN.G.A,
CIT,MANDYA
MMC105 WEB TECHNOLOGIES(JAVASCRIPT)
8. }
9. </script>
Output of the above example
a is even number
JavaScript If...else if statement
It evaluates the content only if expression is true from several expressions. The
signature of JavaScript if else if statement is given below.
1. if(expression1){
2. //content to be evaluated if expression1 is true
3. }
4. else if(expression2){
5. //content to be evaluated if expression2 is true
6. }
7. else if(expression3){
8. //content to be evaluated if expression3 is true
9. }
10. else{
11. //content to be evaluated if no expression is true
12. }
Let’s see the simple example of if else if statement in javascript.
1. <script>
2. var a=20;
3. if(a==10){
4. document.write("a is equal to 10");
5. }
6. else if(a==15){
7. document.write("a is equal to 15");
8. }
9. else if(a==20){
10. document.write("a is equal to 20");
11. }
11 PROF.SACHIN.G.A,
CIT,MANDYA
MMC105 WEB TECHNOLOGIES(JAVASCRIPT)
12. else{
13. document.write("a is not equal to 10, 15 or 20");
14. }
15. </script>
JavaScript Loops
Loops in JavaScript are used to reduce repetitive tasks by repeatedly executing a
block of code as long as a specified condition is true. This makes code more
concise and efficient.
Suppose we want to print ‘Hello World’ five times. Instead of manually writing the
print statement repeatedly, we can use a loop to automate the task and execute it
based on the given condition.
for (let i = 0; i < 5; i++) {
console.log("Hello World!");
}
Output
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Let’s now discuss the different types of loops available in JavaScript
1. JavaScript for Loop
The for loop repeats a block of code a specific number of times. It contains
initialization, condition, and increment/decrement in one line.
Syntax
for (initialization; condition; increment/decrement) {
// Code to execute
}
12 PROF.SACHIN.G.A,
CIT,MANDYA
MMC105 WEB TECHNOLOGIES(JAVASCRIPT)
for (let i = 1; i <= 3; i++) {
console.log("Count:", i);
}
Output
Count: 1
Count: 2
Count: 3
In this example
Initializes the counter variable (let i = 1).
Tests the condition (i <= 3); runs while true.
Executes the loop body and increments the counter (i++).
2. JavaScript while Loop
The while loop executes as long as the condition is true. It can be thought of as a
repeating if statement.
Syntax
while (condition) {
// Code to execute
}
let i = 0;
13 PROF.SACHIN.G.A,
CIT,MANDYA
MMC105 WEB TECHNOLOGIES(JAVASCRIPT)
while (i < 3) {
console.log("Number:", i);
i++;
}
Output
Number: 0
Number: 1
Number: 2
In this example
Initializes the variable (let i = 0).
Runs the loop body while the condition (i < 3) is true.
Increments the counter after each iteration (i++).
3. JavaScript do-while Loop
The do-while loop is similar to while loop except it executes the code block at least
once before checking the condition.
Syntax
do {
// Code to execute
} while (condition);
let i = 0;
do {
console.log("Iteration:", i);
i++;
} while (i < 3);
Output
Iteration: 0
14 PROF.SACHIN.G.A,
CIT,MANDYA
MMC105 WEB TECHNOLOGIES(JAVASCRIPT)
Iteration: 1
Iteration: 2
In this example:
Executes the code block first.
Checks the condition (i < 3) after each iteration.
4. JavaScript for-in Loop
The for…in loop is used to iterate over the properties of an object. It only iterate
over keys of an object which have their enumerable property set to “true”.
Syntax
for (let key in object) {
// Code to execute
}
const obj = { name: "Ashish", age: 25 };
for (let key in obj) {
console.log(key, ":", obj[key]);
}
Output
name : Ashish
age : 25
In this example:
Iterates over the keys of the person object.
Accesses both keys and values.
5. JavaScript for-of Loop
The for…of loop is used to iterate over iterable objects like arrays, strings, or sets.
It directly iterate the value and has more concise syntax than for loop.
Syntax
for (let value of iterable) {
// Code to execute
}
let a = [1, 2, 3, 4, 5];
for (let val of a) {
console.log(val);
}
Output
1
2
3
4
5
15 PROF.SACHIN.G.A,
CIT,MANDYA
MMC105 WEB TECHNOLOGIES(JAVASCRIPT)
Choosing the Right Loop
Use for loop when the number of iterations is known.
Use while loop when the condition depends on dynamic factors.
Use do-while loop to ensure the block executes at least once.
Use for…in loop to iterate over object properties.
Use for…of loop for iterating through iterable objects.
JavaScript Array
JavaScript array is an object that represents a collection of similar type of elements.
There are 3 ways to construct array in JavaScript
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
1) JavaScript array literal
The syntax of creating array using array literal is given below:
1. var arrayname=[value1,value2.....valueN];
As you can see, values are contained inside [ ] and separated by , (comma).
Let's see the simple example of creating and using array in JavaScript.
1. <script>
2. var emp=["Sonoo","Vimal","Ratan"];
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br/>");
5. }
6. </script>
Test it Now
The .length property returns the length of an array.
Output of the above example
16 PROF.SACHIN.G.A,
CIT,MANDYA
MMC105 WEB TECHNOLOGIES(JAVASCRIPT)
Sonoo
Vimal
Ratan
2) JavaScript Array directly (new keyword)
The syntax of creating array directly is given below:
1. var arrayname=new Array();
Here, new keyword is used to create instance of array.
Let's see the example of creating array directly.
1. <script>
2. var i;
3. var emp = new Array();
4. emp[0] = "Arun";
5. emp[1] = "Varun";
6. emp[2] = "John";
7.
8. for (i=0;i<emp.length;i++){
9. document.write(emp[i] + "<br>");
10. }
11. </script>
Test it Now
Output of the above example
Arun
Varun
John
3) JavaScript array constructor (new keyword)
Here, you need to create instance of array by passing arguments in constructor so
that we don't have to provide value explicitly.
The example of creating object by array constructor is given below.
1. <script>
2. var emp=new Array("Jai","Vijay","Smith");
3. for (i=0;i<emp.length;i++){
17 PROF.SACHIN.G.A,
CIT,MANDYA
MMC105 WEB TECHNOLOGIES(JAVASCRIPT)
4. document.write(emp[i] + "<br>");
5. }
6. </script>
Test it Now
Output of the above example
Jai
Vijay
Smith
JavaScript Array Methods
Let's see the list of JavaScript array methods with their description.
Methods Description
concat() It returns a new array object that
contains two or more merged
arrays.
copywithin() It copies the part of the given array
with its own elements and returns
the modified array.
entries() It creates an iterator object and a
loop that iterates over each
key/value pair.
every() It determines whether all the
elements of an array are satisfying
the provided function conditions.
flat() It creates a new array carrying sub-
array elements concatenated
recursively till the specified depth.
flatMap() It maps all array elements via
mapping function, then flattens the
result into a new array.
fill() It fills elements into an array with
static values.
18 PROF.SACHIN.G.A,
CIT,MANDYA
MMC105 WEB TECHNOLOGIES(JAVASCRIPT)
from() It creates a new array carrying the
exact copy of another array
element.
filter() It returns the new array containing
the elements that pass the
provided function conditions.
find() It returns the value of the first
element in the given array that
satisfies the specified condition.
findIndex() It returns the index value of the first
element in the given array that
satisfies the specified condition.
forEach() It invokes the provided function
once for each element of an array.
includes() It checks whether the given array
contains the specified element.
indexOf() It searches the specified element in
the given array and returns the
index of the first match.
isArray() It tests if the passed value ia an
array.
join() It joins the elements of an array as
a string.
keys() It creates an iterator object that
contains only the keys of the array,
then loops through these keys.
lastIndexOf() It searches the specified element in
the given array and returns the
index of the last match.
map() It calls the specified function for
every array element and returns the
new array
19 PROF.SACHIN.G.A,
CIT,MANDYA
MMC105 WEB TECHNOLOGIES(JAVASCRIPT)
of() It creates a new array from a
variable number of arguments,
holding any type of argument.
pop() It removes and returns the last
element of an array.
push() It adds one or more elements to
the end of an array.
reverse() It reverses the elements of given
array.
reduce(function, It executes a provided function for
initial) each value from left to right and
reduces the array to a single value.
reduceRight() It executes a provided function for
each value from right to left and
reduces the array to a single value.
some() It determines if any element of the
array passes the test of the
implemented function.
shift() It removes and returns the first
element of an array.
slice() It returns a new array containing
the copy of the part of the given
array.
sort() It returns the element of the given
array in a sorted order.
splice() It add/remove elements to/from
the given array.
toLocaleString() It returns a string containing all the
elements of a specified array.
toString() It converts the elements of a
specified array into string form,
without affecting the original array.
20 PROF.SACHIN.G.A,
CIT,MANDYA
MMC105 WEB TECHNOLOGIES(JAVASCRIPT)
unshift() It adds one or more elements in the
beginning of the given array.
values() It creates a new iterator object
carrying values for each index in
the array.
JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript function
many times to reuse the code.
Advantage of JavaScript function
There are mainly two advantages of JavaScript functions.
1. Code reusability: We can call a function several times so it save coding.
2. Less coding: It makes our program compact. We don’t need to write many lines of
code each time to perform a common task.
JavaScript Function Syntax
The syntax of declaring function is given below.
1. function functionName([arg1, arg2, ...argN]){
2. //code to be executed
3. }
JavaScript Functions can have 0 or more arguments.
JavaScript Function Example
Let’s see the simple example of function in JavaScript that does not has arguments.
1. <script>
2. function msg(){
3. alert("hello! this is message");
4. }
21 PROF.SACHIN.G.A,
CIT,MANDYA
MMC105 WEB TECHNOLOGIES(JAVASCRIPT)
5. </script>
6. <input type="button" onclick="msg()" value="call function"/>
Output of the above example
JavaScript Function Arguments
We can call function by passing arguments. Let’s see the example of function that
has one argument.
1. <script>
2. function getcube(number){
3. alert(number*number*number);
4. }
5. </script>
6. <form>
7. <input type="button" value="click" onclick="getcube(4)"/>
8. </form>
Output of the above example
Function with Return Value
We can call function that returns a value and use it in our program. Let’s see the
example of function that returns value.
1. <script>
2. function getInfo(){
3. return "hello javatpoint! How r u?";
4. }
5. </script>
6. <script>
7. document.write(getInfo());
8. </script>
Output of the above example
hello javatpoint! How r u?
JavaScript Function Object
22 PROF.SACHIN.G.A,
CIT,MANDYA
MMC105 WEB TECHNOLOGIES(JAVASCRIPT)
In JavaScript, the purpose of Function constructor is to create a new Function
object. It executes the code globally. However, if we call the constructor directly, a
function is created dynamically but in an unsecured way.
Syntax
1. new Function ([arg1[, arg2[, ....argn]],] functionBody)
Parameter
arg1, arg2, .... , argn - It represents the argument used by function.
functionBody - It represents the function definition.
ADVERTISEMENT
JavaScript Function Methods
Let's see function methods with description.
Method Description
apply() It is used to call a function contains this value
and a single array of arguments.
bind() It is used to create a new function.
call() It is used to call a function contains this value
and an argument list.
toString() It returns the result in a form of a string.
JavaScript Function Object Examples
Example 1
Let's see an example to display the sum of given numbers.
23 PROF.SACHIN.G.A,
CIT,MANDYA
MMC105 WEB TECHNOLOGIES(JAVASCRIPT)
1. <script>
2. var add=new Function("num1","num2","return num1+num2");
3. document.writeln(add(2,5));
4. </script>
Output:
Example 2
Let's see an example to display the power of provided value.
1. <script>
2. var pow=new Function("num1","num2","return Math.pow(num1,num2)");
3. document.writeln(pow(2,3));
4. </script>
Output:
24 PROF.SACHIN.G.A,
CIT,MANDYA