Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

Unit 5 JavaScript

JavaScript is a lightweight, interpreted programming language essential for web development, known for its ease of integration with HTML and widespread browser support. Learning JavaScript is crucial for software engineers due to its popularity, versatility in front-end and back-end development, and high demand in the job market. The document also covers JavaScript syntax, data types, variable scope, loops, conditional statements, and functions.

Uploaded by

sdgamerz48
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Unit 5 JavaScript

JavaScript is a lightweight, interpreted programming language essential for web development, known for its ease of integration with HTML and widespread browser support. Learning JavaScript is crucial for software engineers due to its popularity, versatility in front-end and back-end development, and high demand in the job market. The document also covers JavaScript syntax, data types, variable scope, loops, conditional statements, and functions.

Uploaded by

sdgamerz48
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

JavaScript

JavaScript is a lightweight, interpreted programming language. It is designed for creating


network-centric applications. It is complimentary to and integrated with Java. JavaScript is very
easy to implement because it is integrated with HTML. It is open and cross-platform.

Why to Learn Javascript


Javascript is a MUST for students and working professionals to become a great Software
Engineer specially when they are working in Web Development Domain. I will list down some
of the key advantages of learning Javascript:

 Javascript is the most popular programming language in the world and that makes it a
programmer‟s great choice. Once you learnt Javascript, it helps you developing great
front-end as well as back-end softwares using different Javascript based frameworks like
jQuery, Node.JS etc.
 Javascript is everywhere, it comes installed on every modern web browser and so to learn
Javascript you really do not need any special environment setup. For example Chrome,
Mozilla Firefox , Safari and every browser you know as of today, supports Javascript.
 Javascript helps you create really beautiful and crazy fast websites. You can develop your
website with a console like look and feel and give your users the best Graphical User
Experience.
 JavaScript usage has now extended to mobile app development, desktop app
development, and game development. This opens many opportunities for you as
Javascript Programmer.
 Due to high demand, there is tons of job growth and high pay for those who know
JavaScript. You can navigate over to different job sites to see what having JavaScript
skills looks like in the job market.
 Great thing about Javascript is that you will find tons of frameworks and Libraries
already developed which can be used directly in your software development to reduce
your time to market.

There could be 1000s of good reasons to learn Javascript Programming. But one thing for sure,
to learn any programming language, not only Javascript, you just need to code, and code and
finally code until you become expert.

Hello World using Javascript

<html>
<body>
<script language = "javascript" type = "text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>
Advantages of JavaScript
The merits of using JavaScript are −

 Less server interaction − You can validate user input before sending the page off to the
server. This saves server traffic, which means less load on your server.
 Immediate feedback to the visitors − They don't have to wait for a page reload to see if
they have forgotten to enter something.
 Increased interactivity − You can create interfaces that react when the user hovers over
them with a mouse or activates them via the keyboard.
 Richer interfaces − You can use JavaScript to include such items as drag-and-drop
components and sliders to give a Rich Interface to your site visitors.

Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the following
important features −

 Client-side JavaScript does not allow the reading or writing of files. This has been kept
for security reason.
 JavaScript cannot be used for networking applications because there is no such support
available.
 JavaScript doesn't have any multi-threading or multiprocessor capabilities.

JavaScript - Syntax

JavaScript can be implemented using JavaScript statements that are placed within the <script>...
</script> HTML tags in a web page.

You can place the <script> tags, containing your JavaScript, anywhere within your web page,
but it is normally recommended that you should keep it within the <head> tags.

The <script> tag alerts the browser program to start interpreting all the text between these tags as
a script. A simple syntax of your JavaScript will appear as follows.

<script ...>
JavaScript code
</script>

The script tag takes two important attributes −

 Language − This attribute specifies what scripting language you are using. Typically, its
value will be javascript. Although recent versions of HTML (and XHTML, its successor)
have phased out the use of this attribute.
 Type − This attribute is what is now recommended to indicate the scripting language in
use and its value should be set to "text/javascript".

So your JavaScript segment will look like −

<script language = "javascript" type = "text/javascript">


JavaScript code
</script>

Your First JavaScript Code


Let us take a sample example to print out "Hello World". We added an optional HTML comment
that surrounds our JavaScript code. This is to save our code from a browser that does not support
JavaScript. The comment ends with a "//-->". Here "//" signifies a comment in JavaScript, so we
add that to prevent a browser from reading the end of the HTML comment as a piece of
JavaScript code. Next, we call a function document.write which writes a string into our HTML
document.

This function can be used to write text, HTML, or both. Take a look at the following code.

<html>
<body>
<script language = "javascript" type = "text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>

This code will produce the following result −

Hello World!

Javascript Data Types

JavaScript provides different data types to hold different types of values. There are two types of
data types in JavaScript.

1. Primitive data type


2. Non-primitive (reference) data type

JavaScript is a dynamic type language, means you don't need to specify type of the variable
because it is dynamically used by JavaScript engine. You need to use var here to specify the data
type. It can hold any type of values such as numbers, strings etc. For example:
1. var a=40;//holding number
2. var b="Rahul";//holding string

JavaScript primitive data types


There are five types of primitive data types in JavaScript. They are as follows:

Data Type Description


String represents sequence of characters e.g. "hello"
Number represents numeric values e.g. 100
Boolean represents boolean value either false or true
Undefined represents undefined value
Null represents null i.e. no value at all

JavaScript non-primitive data types


The non-primitive data types are as follows:

Data Type Description


Object represents instance through which we can access members
Array represents group of similar values
RegExp represents regular expression

Variables in JavaScript: Variables in JavaScript are containers that hold reusable data. It is the
basic unit of storage in a program.

 The value stored in a variable can be changed during program execution.


 A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
 In JavaScript, all the variables must be declared before they can be used.

Before ES2015, JavaScript variables were solely declared using the var keyword followed by
the name of the variable and semi-colon. Below is the syntax to create variables in JavaScript:

var var_name;
var x;

The var_name is the name of the variable which should be defined by the user and should be
unique. These types of names are also known as identifiers. The rules for creating an identifier
in JavaScript are, the name of the identifier should not be any pre-defined word(known as
keywords), the first character must be a letter, an underscore (_), or a dollar sign ($). Subsequent
characters may be any letter or digit or an underscore or dollar sign.

Notice in the above code sample, we didn‟t assign any values to the variables. We are only
saying they exist. If you were to look at the value of each variable in the above code sample, it
would be undefined.

We can initialize the variables either at the time of declaration or also later when we want to use
them.

Below are some examples of declaring and initializing variables in JavaScript:

// Declaring single variable


var name;

// Declaring multiple variables


var name, title, num;

// Initializing variables
var name = "Harsh";
name = "Rakesh";

JavaScript is also known as untyped language. This means, that once a variable is created in
JavaScript using the keyword var, we can store any type of value in this variable supported by
JavaScript.

Below is an example of this:

// Creating variable to store a number


var num = 5;

// Store string in the variable num


num = "GeeksforGeeks";

The above example executes well without any error in JavaScript, unlike other programming
languages.
Variables in JavaScript can also evaluate simple mathematical expressions and assume their
value.

// Storing a mathematical expression


var x = 5 + 10 + 1;
console.log(x); // 16

Variable Scope in Javascript: The scope of a variable is the part of the program from which the
variable may directly be accessible.

In JavaScript, there are two types of scopes:


 Global Scope: Scope outside the outermost function attached to the window.
 Local Scope: Inside the function being executed.

Let‟s look at the code below. We have a global variable defined in the first line in the global
scope. Then we have a local variable defined inside the function fun().

Example:

let globalVar = "This is a global variable";

function fun() {
let localVar = "This is a local variable";

console.log(globalVar);
console.log(localVar);
}

fun();

Output:

This is a global variable

JavaScript Loops

The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in
loops. It makes the code compact. It is mostly used in array.

There are four types of loops in JavaScript.

1. for loop
2. while loop
3. do-while loop
4. for-in loop

1) JavaScript For loop


The JavaScript for loop iterates the elements for the fixed number of times. It should be used if
number of iteration is known. The syntax of for loop is given below.

for (initialization; condition; increment)


{
code to be executed
}
 <script>
 for (i=1; i<=5; i++)
 {
 document.write(i + "<br/>")
 }
 </script>

Output:

1
2
3
4
5

2) JavaScript while loop


The JavaScript while loop iterates the elements for the infinite number of times. It should be
used if number of iteration is not known. The syntax of while loop is given below.

1. while (condition)
2. {
3. code to be executed
4. }

Let‟s see the simple example of while loop in javascript.

1. <script>
2. var i=11;
3. while (i<=15)
4. {
5. document.write(i + "<br/>");
6. i++;
7. }
8. </script>

Output:

11
12
13
14
15

3) JavaScript do while loop


The JavaScript do while loop iterates the elements for the infinite number of times like while
loop. But, code is executed at least once whether condition is true or false. The syntax of do
while loop is given below.

1. do{
2. code to be executed
3. }while (condition);

Let‟s see the simple example of do while loop in javascript.

1. <script>
2. var i=21;
3. do{
4. document.write(i + "<br/>");
5. i++;
6. }while (i<=25);
7. </script>
8. Output:
9. 21
22
23
24
25

4) JavaScript for in loop


For-in loop in JavaScript is used to iterate over the properties of an object. It can be a great
debugging tool if we want to show the contents of an object. The for-in loop iterates only over
those keys of an object which have their enumerable property set to “true”. The key values in an
object have four attributes (value, writable, enumerable, and configurable). Enumerable when set
to “true” means that we can iterate over that property. You can read about the four key attributes
in the property attributes section of Objects in JavaScript. Read more on enumerable Enumerable
Properties in JavaScript.

Syntax:

for (let i in obj1) {


// Prints all the keys in
// obj1 on the console
console.log(i);
}

Important Points:

 Use the for-in loop to iterate over non-array objects. Even though we can use a for-in
loop for an array, it is generally not recommended. Instead, use a for loop for looping
over an array.
 The properties iterated with the for-in loop also include the properties of the objects
higher in the Prototype chain.
 The order in which properties are iterated may not match the properties that are defined
in the object.

Example: A simple example to illustrate the for-in loop.

//declaring a object employee


const courses = {
firstCourse: 'JavaScript',
secondCourse: 'React',
thirdCourse: 'Angular'
};
let value = '';

//using for in loop


for (let item in courses) {
value += courses[item] + " ";
}
console.log(value);

Conditional Statements in JavaScript: if, else, and else if

JavaScript Conditional Statements


There are mainly three types of conditional statements in JavaScript.

1. if Statement: An „if‟ statement executes code based on a condition.


2. if…else Statement: The if…else statement consists of two blocks of code; when a
condition is true, it executes the first block of code and when the condition is false, it
executes the second block of code.
3. if…else if…else Statement: When multiple conditions need to be tested and different
blocks of code need to be executed based on which condition is true, the if…else if…else
statement is used.
4. How to use Conditional Statements
5. Conditional statements are used to decide the flow of execution based on different
conditions. If a condition is true, you can perform one action and if the condition is false,
you can perform another action.

If statement
Syntax:
if(condition)
{
lines of code to be executed if condition is true
}
You can use if statement if you want to check only a specific condition.

<html>

<head>

<title>IF Statments!!!</title>

<script type="text/javascript">

var age = prompt("Please enter your age");

if(age>=18)

document.write("You are an adult <br />");


if(age<18)

document.write("You are NOT an adult <br />");

</script>

</head>

<body>

</body>

</html>

If…Else statement

Syntax:
if(condition)
{
lines of code to be executed if the condition is true
}
else
{
lines of code to be executed if the condition is false
}

You can use If….Else statement if you have to check two conditions and execute a different set of
codes.

<html>
<head>
<title>If...Else Statments!!!</title>
<script type="text/javascript">
// Get the current hours
var hours = new Date().getHours();
if(hours<12)
document.write("Good Morning!!!<br />");
else
document.write("Good Afternoon!!!<br />");
</script>
</head>
<body>
</body>
</html>

If…Else If…Else statement


Syntax:
if(condition1)
{
lines of code to be executed if condition1 is true
}
else if(condition2)
{
lines of code to be executed if condition2 is true
}
else
{
lines of code to be executed if condition1 is false and condition2 is false
}

You can use If….Else If….Else statement if you want to check more than two conditions.

<html>
<head>
<script type="text/javascript">
var one = prompt("Enter the first number");
var two = prompt("Enter the second number");
one = parseInt(one);
two = parseInt(two);
if (one == two)
document.write(one + " is equal to " + two + ".");
else if (one<two)
document.write(one + " is less than " + two + ".");
else
document.write(one + " is greater than " + two + ".");
</script>
</head>
<body>
</body>
</html>

Functions in JavaScript

A function is a set of statements that take inputs, do some specific computation, and produce
output. The idea is to put some commonly or repeatedly done tasks together and make a function
so that instead of writing the same code again and again for different inputs, we can call that
function.

Example 1: A basic javascript function, here we create a function that divides the 1st element by
the second element.

function myFunction(g1, g2) {

return g1 / g2;

const value = myFunction(8, 2); // Calling the function

console.log(value);
Output:

Syntax: The basic syntax to create a function in JavaScript is shown below.

function functionName(Parameter1, Parameter2, ...)


{
// Function body
}

To create a function in JavaScript, we have to first use the keyword function, separated by the
name of the function and parameters within parenthesis. The part of the function inside the curly
braces {} is the body of the function.

In javascript, functions can be used in the same way as variables for assignments, or calculations.

Function Definition: Before, using a user-defined function in JavaScript we have to create one.
We can use the above syntax to create a function in JavaScript. A function definition is
sometimes also termed a function declaration or function statement. Below are the rules for
creating a function in JavaScript:

 Every function should begin with the keyword function followed by,
 A user-defined function name that should be unique,
 A list of parameters enclosed within parentheses and separated by commas,
 A list of statements composing the body of the function enclosed within curly braces {}.

Example 2: This example shows a basic declaration of a function in javascript.

function calcAddition(number1, number2) {

return number1 + number2;

console.log(calcAddition(6,9));

Output
15

In the above example, we have created a function named calcAddition,

 This function accepts two numbers as parameters and returns the addition of these two
numbers.
 Accessing the function with just the function name without () will return the function
object instead of the function result.

There are three ways of writing a function in JavaScript:


Function Declaration: It declares a function with a function keyword. The function declaration
must have a function name.

Syntax:

function geeksforGeeks(paramA, paramB) {


// Set of statements
}

Function Expression: It is similar to a function declaration without the function name. Function
expressions can be stored in a variable assignment.

Syntax:

let geeksforGeeks= function(paramA, paramB) {


// Set of statements
}

Example 3: This example explains the usage of the Function expression.

const square = function (number) {

return number * number;

};

const x = square(4); // x gets the value 16

console.log(x);
Output
16

Arrow Function: It is one of the most used and efficient methods to create a function in
JavaScript because of its comparatively easy implementation. It is a simplified as well as a more
compact version of a regular or normal function expression or syntax.

Syntax:

let function_name = (argument1, argument2 ,..) => expression

Example 4: This example describes the usage of the Arrow function.

const a = ["Hydrogen", "Helium", "Lithium", "Beryllium"];

const a2 = a.map(function (s) {


return s.length;
});

console.log("Normal way ", a2); // [8, 6, 7, 9]

const a3 = a.map((s) => s.length);


console.log("Using Arrow Function ", a3); // [8, 6, 7, 9]

Output
Normal way [ 8, 6, 7, 9 ]
Using Arrow Function [ 8, 6, 7, 9 ]

Function Parameters: Till now, we have heard a lot about function parameters but haven‟t
discussed them in detail. Parameters are additional information passed to a function. For
example, in the above example, the task of the function calcAddition is to calculate the addition
of two numbers. These two numbers on which we want to perform the addition operation are
passed to this function as parameters. The parameters are passed to the function within
parentheses after the function name and separated by commas. A function in JavaScript can have
any number of parameters and also at the same time, a function in JavaScript can not have a
single parameter.

Example 4: In this example, we pass the argument to the function.

function multiply(a, b) {

b = typeof b !== "undefined" ? b : 1;

return a * b;

console.log(multiply(69)); // 69

Output
69

Calling Functions: After defining a function, the next step is to call them to make use of the
function. We can call a function by using the function name separated by the value of parameters
enclosed between the parenthesis and a semicolon at the end. The below syntax shows how to
call functions in JavaScript:

Syntax:

functionName( Value1, Value2, ..);

Example 5: Below is a sample program that illustrates the working of functions in JavaScript:

function welcomeMsg(name) {

return ("Hello " + name + " welcome to GeeksforGeeks");

}
// creating a variable

let nameVal = "Admin";

// calling the function

console.log(welcomeMsg(nameVal));

Output:

Hello Admin welcome to GeeksforGeeks

Return Statement: There are some situations when we want to return some values from a
function after performing some operations. In such cases, we can make use of the return
statement in JavaScript. This is an optional statement and most of the time the last statement in a
JavaScript function. Look at our first example with the function named as calcAddition. This
function is calculating two numbers and then returns the result.

Syntax: The most basic syntax for using the return statement is:

return value;

JavaScript Arrays

JavaScript Array is a single variable that is used to store elements of different data types.
JavaScript arrays are zero-indexed. The Javascript Arrays are not associative in nature.

Arrays are used when we have a list of items. An array allows you to store several values with
the same name and access them by using their index number.

Declaration of an Array

There are basically two ways to declare an array.

1. Creating an array using array literal:


let arrayName = [value1, value2, ...];
// Initializing while declaring

let courses = ["HTML", "CSS", "Javascript", "React"];

console.log(courses)
Output

[ 'HTML', 'CSS', 'Javascript', 'React' ]

2. Creating an array using the JavaScript new keyword:


let arrayName = new Array();
// Initializing while declaring

let arr1 = new Array(3)

arr1[0] = 10

arr1[1] = 20

arr1[2] = 30

console.log("Array 1: ", arr1)

// Creates an array having elements 10, 20, 30, 40, 50

let arr2 = new Array(10, 20, 30, 40, 50);

console.log("Array 2: ", arr2)

// Creates an array of 5 undefined elements

let arr3 = new Array(5);

console.log("Array 3: ", arr3)

// Creates an array with one element

let arr4 = new Array("1BHK");

console.log("Array 4: ", arr4)

Output

Array 1: [ 10, 20, 30 ]


Array 2: [ 10, 20, 30, 40, 50 ]
Array 3: [ <5 empty items> ]
Array 4: [ '1BHK' ]

Note: Both the above methods do exactly the same. Use the array literal method for efficiency,
readability, and speed.
Accessing Elements of an Array

Any element in the array can be accessed using the index number. The index in the arrays starts
with 0.

const courses = ["HTML", "CSS", "Javascript"];

console.log(courses[0])

console.log(courses[1])

console.log(courses[2])

Output

HTML
CSS
Javascript

Change elements from a pre-defined array

We will use index based method method to change the elements of array.

const courses = ["HTML", "CSS", "Javascript"];

console.log(courses)

courses[1]= "GeeksforGeeks"

console.log(courses)

Output

[ 'HTML', 'CSS', 'Javascript' ]


[ 'HTML', 'GeeksforGeeks', 'Javascript' ]

Convert an Array to String

We have an in-built method toString() in Javascript that converts an array to a string.

const courses = ["HTML", "CSS", "Javascript"];

console.log(courses.toString())

Output

HTML,CSS,Javascript
Increase and decrease the length of an array

We can increase and decrease the length of an array using the Javascript‟s length property.

const courses = ["HTML", "CSS", "Javascript"];

courses.length = 5 // Increasing array length to 5

console.log("Array after increased length: " ,courses)

courses.length = 2 // Decreasing array length to 2

console.log("Array after decreased length: " ,courses)

Output

Array after increased length: [ 'HTML', 'CSS', 'Javascript', <2 empty items>
]
Array after decreased length: [ 'HTML', 'CSS' ]

We can also update an array after initialization.


const courses = ["HTML", "CSS", "Javascript"];

courses.length = 5 // Increasing array length to 5

console.log("Array after increased length: " ,courses)

courses[3] = 'PhP'

courses[4] = 'React'

console.log("Array after initializing: ", courses)

Output

Array after increased length: [ 'HTML', 'CSS', 'Javascript', <2 empty items>
]
Array after initializing: [ 'HTML', 'CSS', 'Javascript', 'PhP', 'React' ]

Loop through Javascript Array Elements

We can loop through the elements of a Javascript array using the for loop:

const courses = ["HTML", "CSS", "Javascript"];

for (let i = 0; i < courses.length; i++) {

console.log(courses[i])
}

Output

HTML
CSS
Javascript

This can also be done by using the Array.forEach() function of Javascript.

const courses = ["HTML", "CSS", "Javascript"];

courses.forEach(myfunc);

function myfunc(elements) {

console.log(elements);

Output

HTML
CSS
Javascript

Adding new elements to JavaScript Array

Using the Javascript in-built push() method we can add new elements to an array.

const courses = ["HTML", "CSS", "Javascript"];

console.log("Original Array: ",courses)

courses.push("React")

console.log("Array after adding an element: ",courses)

Output

Original Array: [ 'HTML', 'CSS', 'Javascript' ]


Array after adding an element: [ 'HTML', 'CSS', 'Javascript', 'React' ]

We can also add a new element to a Javascript array using the length property.

const courses = ["HTML", "CSS", "Javascript"];

console.log("Original Array: ",courses)


courses[courses.length] = "React"

console.log("Array after adding an element: ",courses)

Output

Original Array: [ 'HTML', 'CSS', 'Javascript' ]


Array after adding an element: [ 'HTML', 'CSS', 'Javascript', 'React' ]

Finding the typeof JavaScript Arrays

The Javascript typeof operator returns “object” for arrays.

const courses = ["HTML", "CSS", "Javascript"];

console.log(typeof courses)

Output

object
JavaScript Events

The change in the state of an object is known as an Event. In html, there are various events
which represents that some activity is performed by the user or by the browser. When javascript
code is included in HTML, js react over these events and allow the execution. This process of
reacting over the events is called Event Handling. Thus, js handles the HTML events via Event
Handlers.

For example, when a user clicks over the browser, add js code, which will execute the task to be
performed on the event.

Some of the HTML events and their event handlers are:

Mouse events:
Event Performed Event Handler Description
Click Onclick When mouse click on an element
Mouseover onmouseover When the cursor of the mouse comes over the element
Mouseout Onmouseout When the cursor of the mouse leaves an element
Mousedown onmousedown When the mouse button is pressed over the element
Mouseup Onmouseup When the mouse button is released over the element
Mousemove onmousemove When the mouse movement takes place.

Keyboard events:
Event Performed Event Handler Description
Keydown & Keyup onkeydown & onkeyup When the user press and then release the key

Form events:
Event Performed Event Handler Description
Focus onfocus When the user focuses on an element
Submit onsubmit When the user submits the form
Blur onblur When the focus is away from a form element
Change onchange When the user modifies or changes the value of a form element

Window/Document events
Event Event Description
Performed Handler
Load onload When the browser finishes the loading of the page
Unload onunload When the visitor leaves the current webpage, the browser unloads
it
Resize onresize When the visitor resizes the window of the browser
Let's discuss some examples over events and their handlers.

Click Event
1. <html>
2. <head> Javascript Events </head>
3. <body>
4. <script language="Javascript" type="text/Javascript">
5. <!--
6. function clickevent()
7. {
8. document.write("This is JavaTpoint");
9. }
10. //-->
11. </script>
12. <form>
13. <input type="button" onclick="clickevent()" value="Who's this?"/>
14. </form>
15. </body>
16. </html>

MouseOver Event
1. <html>
2. <head>
3. <h1> Javascript Events </h1>
4. </head>
5. <body>
6. <script language="Javascript" type="text/Javascript">
7. <!--
8. function mouseoverevent()
9. {
10. alert("This is JavaTpoint");
11. }
12. //-->
13. </script>
14. <p onmouseover="mouseoverevent()"> Keep cursor over me</p>
15. </body>
16. </html>

Focus Event
1. <html>
2. <head> Javascript Events</head>
3. <body>
4. <h2> Enter something here</h2>
5. <input type="text" id="input1" onfocus="focusevent()"/>
6. <script>
7. <!--
8. function focusevent()
9. {
10. document.getElementById("input1").style.background=" aqua";
11. }
12. //-->
13. </script>
14. </body>
15. </html>

Keydown Event
1. <html>
2. <head> Javascript Events</head>
3. <body>
4. <h2> Enter something here</h2>
5. <input type="text" id="input1" onkeydown="keydownevent()"/>
6. <script>
7. <!--
8. function keydownevent()
9. {
10. document.getElementById("input1");
11. alert("Pressed a key");
12. }
13. //-->
14. </script>
15. </body>
16. </html>

Load event
1. <html>
2. <head>Javascript Events</head>
3. </br>
4. <body onload="window.alert('Page successfully loaded');">
5. <script>
6. <!--
7. document.write("The page is loaded successfully");
8. //-->
9. </script>
10. </body>
11. </html>
JavaScript String

The JavaScript string is an object that represents a sequence of characters.

There are 2 ways to create string in JavaScript

1. By string literal
2. By string object (using new keyword)

1) By string literal
The string literal is created using double quotes. The syntax of creating string using string literal
is given below:

1. var stringname="string value";

Let's see the simple example of creating string literal.

1. <script>
2. var str="This is string literal";
3. document.write(str);
4. </script>

Output:

This is string literal

2) By string object (using new keyword)


The syntax of creating string object using new keyword is given below:

1. var stringname=new String("string literal");

Here, new keyword is used to create instance of string.

Let's see the example of creating string in JavaScript by new keyword.

1. <script>
2. var stringname=new String("hello javascript string");
3. document.write(stringname);
4. </script>

Output:

hello javascript string

JavaScript String Methods


Let's see the list of JavaScript string methods with examples.

Methods Description
charAt() It provides the char value present at the specified index.
charCodeAt() It provides the Unicode value of a character present at the specified
index.
concat() It provides a combination of two or more strings.
indexOf() It provides the position of a char value present in the given string.
lastIndexOf() It provides the position of a char value present in the given string by
searching a character from the last position.
search() It searches a specified regular expression in a given string and returns its
position if a match occurs.
match() It searches a specified regular expression in a given string and returns
that regular expression if a match occurs.
replace() It replaces a given string with the specified replacement.
substr() It is used to fetch the part of the given string on the basis of the specified
starting position and length.
substring() It is used to fetch the part of the given string on the basis of the specified
index.
slice() It is used to fetch the part of the given string. It allows us to assign
positive as well negative index.
toLowerCase() It converts the given string into lowercase letter.
toLocaleLowerCase() It converts the given string into lowercase letter on the basis of host?s
current locale.
toUpperCase() It converts the given string into uppercase letter.
toLocaleUpperCase() It converts the given string into uppercase letter on the basis of host?s
current locale.
toString() It provides a string representing the particular object.
valueOf() It provides the primitive value of string object.
split() It splits a string into substring array, then returns that newly created
array.
trim() It trims the white space from the left and right side of the string.

1) JavaScript String charAt(index) Method


The JavaScript String charAt() method returns the character at the given index.

1. <script>
2. var str="javascript";
3. document.write(str.charAt(2));
4. </script>

Output:

2) JavaScript String concat(str) Method


The JavaScript String concat(str) method concatenates or joins two strings.

1. <script>
2. var s1="javascript ";
3. var s2="concat example";
4. var s3=s1.concat(s2);
5. document.write(s3);
6. </script>

Output:

javascript concat example

3) JavaScript String indexOf(str) Method


The JavaScript String indexOf(str) method returns the index position of the given string.

1. <script>
2. var s1="javascript from javatpoint indexof";
3. var n=s1.indexOf("from");
4. document.write(n);
5. </script>

Output:

11

4) JavaScript String lastIndexOf(str) Method


The JavaScript String lastIndexOf(str) method returns the last index position of the given string.
1. <script>
2. var s1="javascript from javatpoint indexof";
3. var n=s1.lastIndexOf("java");
4. document.write(n);
5. </script>

Output:

16

5) JavaScript String toLowerCase() Method


The JavaScript String toLowerCase() method returns the given string in lowercase letters.

1. <script>
2. var s1="JavaScript toLowerCase Example";
3. var s2=s1.toLowerCase();
4. document.write(s2);
5. </script>

Output:

javascript tolowercase example

6) JavaScript String toUpperCase() Method


The JavaScript String toUpperCase() method returns the given string in uppercase letters.

1. <script>
2. var s1="JavaScript toUpperCase Example";
3. var s2=s1.toUpperCase();
4. document.write(s2);
5. </script>

Output:

JAVASCRIPT TOUPPERCASE EXAMPLE

7) JavaScript String slice(beginIndex, endIndex) Method


The JavaScript String slice(beginIndex, endIndex) method returns the parts of string from given
beginIndex to endIndex. In slice() method, beginIndex is inclusive and endIndex is exclusive.

1. <script>
2. var s1="abcdefgh";
3. var s2=s1.slice(2,5);
4. document.write(s2);
5. </script>

Output:

cde

8) JavaScript String trim() Method


The JavaScript String trim() method removes leading and trailing whitespaces from the string.

1. <script>
2. var s1=" javascript trim ";
3. var s2=s1.trim();
4. document.write(s2);
5. </script>

Output:

javascript trim

9) JavaScript String split() Method

1. <script>
2. var str="This is JavaTpoint website";
3. document.write(str.split(" ")); //splits the given string.
4. </script>

Introduction to JavaScript Math Functions


The JavaScript Math is a built-in object that provides properties and methods for mathematical
constants and functions to execute mathematical operations. It is not a function object, not a
constructor. You can call the Math as an object without creating it because the properties and
methods of Math are static.

JavaScript Math Functions

The Math functions consist of methods and properties. Following is the list of methods used with
the Math object:

1. Math.round()

This method provides the value of the given number to a rounded integer. It can be written as:
Math.round(x), where x is a number.
2. Math.pow()

It provides the value of x to the power of y. It can be written as:


Math.pow(x, y), where x is a base number and y is an exponent to the given base.

3. Math.sqrt()

It gives the square root of a given integer. It can be written as:


Math.sqrt(x), where x is a number.

4. Math.abs()

It provides the absolute i.e. positive value of a number. It can be written as:
Math.abs(x); where x is a number.

5. Math.ceil()

It gives a smaller number, which is greater or equal to the given integer. It can be written as:
Math.ceil(x); where x is a number

6. Math.floor()

It gives a larger number, which is lesser or equal to the given integer. It can be written as:
Math.floor(x); where x is a number.

7. Math.sin()

It provides a sine of the given number. It can be written as:


Math.sin(x); where x is a number.

8. Math.cos()

It provides cosine of the given number. It can be written as:


Math.cos(x); where x is a number

9. Math.min() and Math.max()

The min() method is used to display the lowest value of the given arguments. It can be written
as:
Math.min(val1, val2………valn); where val1, val2………valn are numbers.

The max() method is used to display the highest value of the given arguments. It can be written
as:
Math.max(val1, val2………valn); where val1, val2………valn are numbers.
10. Math.random()

It provides a random number between 0 and 1. It can be written as:


Math.random();

11. Math.acos()

It provides an arccosine of an integer. It can be written as:


Math.acos(x); where x is a number.

12. Math.asin()

It provides arcsine of an integer. It can be written as:


Math.asin(x); where x is a number.

Examples

Let us see few examples for the above some methods of JavaScript Math Functions:

Math.abs()

Code:

<!DOCTYPE html>
<html>
<body>
<p id="abs_demo"></p>
<script>
document.getElementById("abs_demo").innerHTML = Math.abs(-5.6);
</script>
</body>
</html>

Output:

5.6

JavaScript Form

In this tutorial, we will learn, discuss, and understand the JavaScript form. We will also see the
implementation of the JavaScript form for different purposes.

Here, we will learn the method to access the form, getting elements as the JavaScript form's
value, and submitting the form.
Introduction to Forms
Forms are the basics of HTML. We use HTML form element in order to create the JavaScript
form. For creating a form, we can use the following sample code:

1. <html>
2. <head>
3. <title> Login Form</title>
4. </head>
5. <body>
6. <h3> LOGIN </h3>
7. <formform ="Login_form" onsubmit="submit_form()">
8. <h4> USERNAME</h4>
9. <input type="text" placeholder="Enter your email id"/>
10. <h4> PASSWORD</h4>
11. <input type="password" placeholder="Enter your password"/></br></br>
12. <input type="submit" value="Login"/>
13. <input type="button" value="SignUp" onClick="create()"/>
14. </form>
15. </html>

In the code:

 Form name tag is used to define the name of the form. The name of the form here is
"Login_form". This name will be referenced in the JavaScript form.
 The action tag defines the action, and the browser will take to tackle the form when it is
submitted. Here, we have taken no action.
 The method to take action can be either post or get, which is used when the form is to be
submitted to the server. Both types of methods have their own properties and rules.
 The input type tag defines the type of inputs we want to create in our form. Here, we have
used input type as 'text', which means we will input values as text in the textbox.
 Net, we have taken input type as 'password' and the input value will be password.
 Next, we have taken input type as 'button' where on clicking, we get the value of the form
and get displayed.

Other than action and methods, there are the following useful methods also which are provided
by the HTML Form Element

 submit (): The method is used to submit the form.


 reset (): The method is used to reset the form values.

Referencing forms
Now, we have created the form element using HTML, but we also need to make its connectivity
to JavaScript. For this, we use the getElementById () method that references the html form
element to the JavaScript code.

The syntax of using the getElementById() method is as follows:

1. let form = document.getElementById('subscribe');

Submitting the form

Next, we need to submit the form by submitting its value, for which we use the onSubmit()
method. Generally, to submit, we use a submit button that submits the value entered in the form.

The syntax of the submit() method is as follows:

1. <input type="submit" value="Subscribe">

When we submit the form, the action is taken just before the request is sent to the server. It
allows us to add an event listener that enables us to place various validations on the form.
Finally, the form gets ready with a combination of HTML and JavaScript code.

Let's collect and use all these to create a Login form and SignUp form and use both.

Login Form

1. <html>
2. <head>
3. <title> Login Form</title>
4. </head>
5. <body>
6. <h3> LOGIN </h3>
7. <formform ="Login_form" onsubmit="submit_form()">
8. <h4> USERNAME</h4>
9. <input type="text" placeholder="Enter your email id"/>
10. <h4> PASSWORD</h4>
11. <input type="password" placeholder="Enter your password"/></br></br>
12. <input type="submit" value="Login"/>
13. <input type="button" value="SignUp" onClick="create()"/>
14. </form>
15. <script type="text/javascript">
16. function submit_form(){
17. alert("Login successfully");
18. }
19. function create(){
20. window.location="signup.html";
21. }
22. </script>
23. </body>
24. </html>

The output of the above code on clicking on Login button is shown below:

SignUp Form

1. <html>
2. <head>
3. <title> SignUp Page</title>
4. </head>
5. <body align="center" >
6. <h1> CREATE YOUR ACCOUNT</h1>
7. <table cellspacing="2" align="center" cellpadding="8" border="0">
8. <tr><td> Name</td>
9. <td><input type="text" placeholder="Enter your name" id="n1"></td></tr>
10. <tr><td>Email </td>
11. <td><input type="text" placeholder="Enter your email id" id="e1"></td></tr>
12. <tr><td> Set Password</td>
13. <td><input type="password" placeholder="Set a password" id="p1"></td></tr>
14. <tr><td>Confirm Password</td>
15. <td><input type="password" placeholder="Confirm your password" id="p2"></td></tr>
16. <tr><td>
17. <input type="submit" value="Create" onClick="create_account()"/>
18. </table>
19. <script type="text/javascript">
20. function create_account(){
21. var n=document.getElementById("n1").value;
22. var e=document.getElementById("e1").value;
23. var p=document.getElementById("p1").value;
24. var cp=document.getElementById("p2").value;
25. //Code for password validation
26. var letters = /^[A-Za-z]+$/;
27. var email_val = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
28. //other validations required code
29. if(n==''||e==''||p==''||cp==''){
30. alert("Enter each details correctly");
31. }
32. else if(!letters.test(n))
33. {
34. alert('Name is incorrect must contain alphabets only');
35. }
36. else if (!email_val.test(e))
37. {
38. alert('Invalid email format please enter valid email id');
39. }
40. else if(p!=cp)
41. {
42. alert("Passwords not matching");
43. }
44. else if(document.getElementById("p1").value.length > 12)
45. {
46. alert("Password maximum length is 12");
47. }
48. else if(document.getElementById("p1").value.length < 6)
49. {
50. alert("Password minimum length is 6");
51. }
52. else{
53. alert("Your account has been created successfully... Redirecting to JavaTpoint.com");
54. window.location="https://www.javatpoint.com/";
55. }
56. }
57. </script>
58. </body>
59. </html>

The output of the above code is shown below:


In this way, we can create forms in JavaScript with proper validations.

Window Object

The window object represents a window in browser. An object of window is created


automatically by the browser.

Window is the object of browser, it is not the object of javascript. The javascript objects are
string, array, date etc.

Methods of window object


The important methods of window object are as follows:

Method Description
alert() displays the alert box containing message with ok button.
confirm() displays the confirm dialog box containing message with ok and cancel button.
prompt() displays a dialog box to get input from the user.
open() opens the new window.
close() closes the current window.
setTimeout() performs action after specified time like calling function, evaluating expressions etc.

Example of alert() in javascript

It displays alert dialog box. It has message and ok button.

1. <script type="text/javascript">
2. function msg(){
3. alert("Hello Alert Box");
4. }
5. </script>
6. <input type="button" value="click" onclick="msg()"/>

Output of the above example

Example of confirm() in javascript

It displays the confirm dialog box. It has message with ok and cancel buttons.

1. <script type="text/javascript">
2. function msg(){
3. var v= confirm("Are u sure?");
4. if(v==true){
5. alert("ok");
6. }
7. else{
8. alert("cancel");
9. }
10.
11. }
12. </script>
13.
14. <input type="button" value="delete record" onclick="msg()"/>

Output of the above example

Example of prompt() in javascript

It displays prompt dialog box for input. It has message and textfield.
1. <script type="text/javascript">
2. function msg(){
3. var v= prompt("Who are you?");
4. alert("I am "+v);
5.
6. }
7. </script>
8.
9. <input type="button" value="click" onclick="msg()"/>

Output of the above example

Example of open() in javascript

It displays the content in a new window.

1. <script type="text/javascript">
2. function msg(){
3. open("http://www.javatpoint.com");
4. }
5. </script>
6. <input type="button" value="javatpoint" onclick="msg()"/>

Output of the above example

Example of setTimeout() in javascript

It performs its task after the given milliseconds.

1. <script type="text/javascript">
2. function msg(){
3. setTimeout(
4. function(){
5. alert("Welcome to Javatpoint after 2 seconds")
6. },2000);
7.
8. }
9. </script>
10.
11. <input type="button" value="click" onclick="msg()"/>
JavaScript - Document Object Model or DOM

Every web page resides inside a browser window which can be considered as an object.

A Document object represents the HTML document that is displayed in that window. The
Document object has various properties that refer to other objects which allow access to and
modification of document content.

The way a document content is accessed and modified is called the Document Object Model, or
DOM. The Objects are organized in a hierarchy. This hierarchical structure applies to the
organization of objects in a Web document.

 Window object − Top of the hierarchy. It is the outmost element of the object hierarchy.
 Document object − Each HTML document that gets loaded into a window becomes a
document object. The document contains the contents of the page.
 Form object − Everything enclosed in the <form>...</form> tags sets the form object.
 Form control elements − The form object contains all the elements defined for that
object such as text fields, buttons, radio buttons, and checkboxes.

Here is a simple hierarchy of a few important objects −

There are several DOMs in existence. The following sections explain each of these DOMs in
detail and describe how you can use them to access and modify document content.

 The Legacy DOM − This is the model which was introduced in early versions of
JavaScript language. It is well supported by all browsers, but allows access only to
certain key portions of documents, such as forms, form elements, and images.
 The W3C DOM − This document object model allows access and modification of all
document content and is standardized by the World Wide Web Consortium (W3C). This
model is supported by almost all the modern browsers.
 The IE4 DOM − This document object model was introduced in Version 4 of Microsoft's
Internet Explorer browser. IE 5 and later versions include support for most basic W3C
DOM features.

DOM compatibility
If you want to write a script with the flexibility to use either W3C DOM or IE 4 DOM depending
on their availability, then you can use a capability-testing approach that first checks for the
existence of a method or property to determine whether the browser has the capability you
desire. For example −

if (document.getElementById) {
// If the W3C method exists, use it
} else if (document.all) {
// If the all[] array exists, use it
} else {
// Otherwise use the legacy DOM
}

You might also like