Form Handling and Validation in JavaScript

HTML form validation can be done with JS.

Form validation normally used on the server, after the user had fill up all the data and then hit the submit button.

If the data entered by a user was incorrect or was something missing, the server will send all the data back to the user and request that the form need to be resubmitted with correct information.

JS provides a way to validate form’s data on the user’s computer before sending it to the web server. In Form validation, there will be two functions.

  • Basic − the form will checked to make sure all the mandatory fields are filled in. It would require just a loop in the form and check for data.
  • Data Format − the data must be checked for correct form and value. Developer’s code must include with logic to test correctness of data.

Different types of form validation

There are two types of validation:

Client-side validation is validation that occurs before the data has been submitted to the server.

Client side validation is performed by a web browser, before input is sent to a web server.

Client side validation check data and then send to server in avoid  unnecessary server call

Server-side validation is validation which occurs after the data has been submitted.

This is performed by a web server, after input has been sent to the server.

A response is sent back to the user to tell what corrections to make,If the data fails authentication.



Form field (firstname) is empty, so the function alerts a message, and returns false value.

Data Validation

Data validation is the process for ensuring that user input is clean, correct.

Validation tasks are:

  • Is user filled in all required fields?
  • Is user entered a valid date?
  • Is user entered text in a numeric field?

Some Validation HTML Input Attributes:

Disabled – This is specifies that the input element should be disabled

Max – This is specifies the maximum value of an input element

Min – This is specifies the minimum value of an input element

Pattern – This is specifies the value pattern of an input element

Required – This is specifies that the input field requires an element

Type – This is specifies the type of an input element

Form Example

Read More

  1. Get multiple checkbox value in javascript
  2. Add active class onclick
  3. JavaScript Multiplication Table
  4. isPrime() Javascript : Prime number program
  5. Try Catch and Finally in JavaScript
  6. Math Object in JavaScript

Cookies in JavaScript

What are Cookies?

Normally, Cookies store user information in small text files.on your computer.

A cookie is a piece of data that is stored on your browser to be accessed by your browser. Cookies are also saved as key/value pairs.

Cookies will remember information about the user, when server forgets everything about the user after the connection is shut down.

  • When a user visits a web page, The name of user can be stored in a cookie.
  • Next time the user visits the page, the cookie “remembers” the name.

How It Works ?

Server sends some data to the visitor’s browser in the form of a cookie. The browser may accept the cookie. When the visitor go to another page, the browser sends the same cookie to the server.

Cookies are a plain text data record of 5 variable −

  • Expires − The date the cookie will expire
  • Domain − The domain name of thewebsite.
  • Path − The path to the directory or web page that set the cookie.
  • Secure − The cookie may only be retrieved with a secure server.
  • Name value – Cookies are set and retrieved in the form of key-value pairs

Create a Cookie with JavaScript

JS can create, read, and delete cookies with the document.cookie property.

A cookie can be created like this:

document.cookie = “username=Ram Das”;


Read a Cookie with JavaScript

With JS, cookies can be read like this:

var x = document.cookie;


Change a Cookie with JavaScript

With JS, cookies can be changed like this:

document.cookie = “username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/”;


In this example the cookie extend the expiry date by 1 Month.

Delete a Cookie with JavaScript

With JS, cookies can be delete like this:

Just set the expires parameter to a passed date:

document.cookie = “username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;”;


 Full Example

HTML Document Object Model (DOM) in JavaScript

The DOM is an object-oriented representation of the website pages, which is modified with a scripting language JS.

The DOM stand for Document Object Model.

When a web page is loaded, the browser creates a DOM of the page.

The DOM model is a tree of Objects.

The DOM is a platform that allows programs and scripts to dynamically access and update the content and style of a document.

It is a programming interface for HTML and XML documents. It represents the document as nodes and objects.

With the object model, JS will have all the power to create dynamic HTML:

  • It can be change all the HTML elements in the page
  • It can bechange all the HTML attributes in the page
  • It can bechange all the CSS styles in the page
  • It can be remove existing HTML elements and attributes
  • It can be add new HTML elements and attributes
  • It can be react to all existing HTML events in the page
  • It can be create new HTML events in the page

The DOM standard is separated into three different parts:

  • Core DOM – For all document types
  • XML DOM – For XML documents
  • HTML DOM – For HTML documents

For example, the standard DOM specifies that

the getElementsByTagName method must return a list of all the <P> elements in the document.

varpara = document.getElementsByTagName(“P”);


How To Access the DOM?

There is nothing special to begin using the DOM.

Different implementations of the DOM will be happened in different browsers.

Every web browser uses some document object model to make web pages accessible via JavaScript.

That DOM programming can be simple as it is displays an alert message by using the alert() function from the window object.

For Example

<body onload=”window.alert(‘Welcome to my home page!’);”>

When creating a script , whether it’s inline in a <script> element , you can immediately using the API for the document or window elements to manipulate the document.


From where the DOM came?

The DOM originated as a specification to allow JS and Java programs to be portable among web browsers.

Dynamic HTML was the immediate ancestor of the DOM, and it was originally thought of largely in terms of browsers.

However, when the DOM Working Group was formed, it was also joined by vendors in other domains, including HTML or XML editors and document repositories.

DOM Tree of Objects

Document –

Root element(html) –

          Element(head) –


                   Text(My Title)

          Element(body) –

                   Element(a) –


                             Text (My Link)

                   Element(h1) –

                             Text(My Header)

Example with DOM Method


Finding DOM HTML Element by Id

Hello World!

This example demonstrates the getElementsById method.


This example demonstrates the getElementsById method.

The text from the intro paragraph is Hello World!

Read More

  1. Popup Box in JavaScript
  2. Classes and Objects in JavaScript

This Keyword in JavaScript

This keyword refers to an object, that object which is executing the current bit of JavaScript code.

JavaScript function while executing has a reference to its current execution any function, called this.

JavaScript function while executing has a reference to its current execution any function, called this.

with this keyword,It does not matter how and where function is declared or defined.


function’s this keyword behaves differently in JavaScript compared to other language.

In most of cases, this is determined that by how avalue of function is called.

It cannot be set by assignment on time execution, and it will be different each time the function is called.

ES5 have the bind() method to set the value of a function’s this regardless of how it’s called, and ES2015 introduced arrow functions which don’t provide their own this binding.


This keyword has some different values depending on its usage:

  • Within a method, this keyword refers to the owner object.
  • As Single, this keyword refers to the global object.
  • this keyword within a function refers to the global object.
  • Within a function, within strict mode, this keyword is undefined.
  • Creating an event, this keyword refers to the element that received the event.
  • Methods like call(), and apply() can refer this to any object.

In an object method, this refers to the “owner” of the method.

In the example on the top of this page, this refers to the person object.

The person object is the owner of the fullName method.



This in Event Handlers

In HTML event handlers, this refers to the HTML element that received the event:

This in a Function (Default)

The owner of the function is the default binding for this.

Within function, this keyword refers to the Global object.


Global Scope

If a function uses ‘this’ keyword, is called from the global scope then this will point to the window object


Example: this keyword inside inner function


Strict Mode in JavaScript

JAVACRIPT’s strict mode, introduced in ECMAScript 5, is a way to opt in to a restricted variant of JAVACRIPT.

Strict mode is not just a subset: it intentionally has different semantics from all other normal code.

Some browsers does not support strict mode.

To run strict mode code with different behavior from browsers need to test for support for the relevant aspects of strict mode.

Strict mode code and non-strict mode code can be co existing, so scripts can opt into strict mode incrementally

Strict mode makes many changes to normal JavaScript semantics:

  1. Eliminates some JavaScript silent errors by changing them to throw errors.
  2. Fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that’s not strict mode.

The “use strict”; Syntax

For declaring strict mode the syntax was designed to be compatible with of JS.

Compiling a numeric literal (10 + 15;) or a string literal (“Ram Das”;) in a JS program has no side effects.

It will simply compiles to a non existing variable and it will dies.

Keywords reserved for future JavaScript versions can NOT be used as variable names in strict mode

These are:

  • implements
  • interface
  • let
  • package
  • private
  • protected
  • public
  • static
  • yield

Simplifying variable uses

Strict mode simplifies how variable names map to particular variable definitions in code.

This is critical to fully optimizing JS code.

JS makes this basic mapping of name to variable definition in the code impossible to perform until runtime.

Strict mode will removes most cases where it will happens, so the compiler can better optimize strict mode code.

First, strict mode prohibits with.

The problem with with is that any name inside the block might map either to a property of the object passed to it, or to a variable in surrounding (or even global) scope, at run time, Strict mode makes with a syntax error, so there’s no chance for a name in a with to refer to an unknown location at run time.


JavaScript allows strictness of code using “use strict”. Write “use strict” at the top of JavaScript code or in a function to run strict mode.



Defines that JavaScript code should be executed in “strict mode”.

“use strict” is to indicate, the code should be executed within “strict mode”.

Declaring Strict Mode

Strict mode is declared by adding “use strict”; to the beginning of a script or a function.


Declared inside a function

Hoisting in JavaScript

What is Hoisting?

Hoisting is when the JavaScript interpreter moves all variable and function declarations to the top of the current scope.

Hoisting is done during the interpreter’s first run through the code.

The important thing is that the actual declarations are hoisted, and that assignments will be left where they are.

Hoisting is a JS mechanism where variables and functions are declarations are moved to the top before code execution.

All functions and variables that are declared are moved to the top of their scope regardless of whether their scope is global or local.

Of note however, is the fact that the hoisting mechanism only moves the declaration. The assignments are left in place.

Variable declarations are one of the most common aspects of any programming language.

However, JavaScript has a little quirk, known as hoisting, which can turn an innocent declaration into a subtle bug.

The variable and function declarations are put into memory during the compile phase ,  and a hoisting suggests that variable and function declarations are moved to the top of code..

Always Declare Variables At the Top !Hoisting is (to many developers) an unknown or overlooked behavior of JavaScript.

To avoid bugs, always declare all variables at the beginning of every scope.


Variable Declarations

This is a basic example:

Function Declarations

Hoisting also applies to function declarations.

This is a basic example:

Function Hoisting

Function declarations are also be hoisted. But that functions, what assigned to variables, that’s are not hoisted.

For example, the following code will work due to function declaration hoisting.

The variable declaration for foo is hoisted before the function call.

However, since the assignment to bar is not hoisted, an exception is thrown for trying to call a non-function variable.


Hoisting is an easy to understand, but often overlooked nuance.

To help avoid these bugs, many developers advocate for a single variable declaration statement at the very beginning of every scope.

Hoisting is JS’s default behavior of moving declarations to the top.

JavaScript Declarations are Hoisted

In JS, a variable can be declared after it has been used.

A variable can be used before it has been declared.

Example 1 does not give the same result as Example 2:

Example 1


Example 2

Data Object in JavaScript

The Date object is a datatype, Date objects are created with the new Date( ), Most of “Date” methods simply allow you to get and set the year, month, day, hour, minute, second.

If no arguments are provided, the constructor creates a JavaScript Date object for the current date and time according to system settings for timezone offset.

JavaScript can represent date and time till the year 275755.


Date Properties will allows the addition of properties to a Date object.

Date.length– This property will find the length of date and display the value of Date.length. This is the number of arguments which is handled by the constructor.

Date Methods

Sr NoMathodDescription
1Date()It will return today’s date and time
2getDate()It will return the day of the month for the specified date as per local time.
3getDay()It will return the day of the week for the specified date as per local time.
4getFullYear()It will return the year of the specified date as per local time
5getHours()It will return the hour in the specified date as per local time.
6getMilliseconds()It will return the milliseconds in the specified date as per local time.
7getMinutes()It will return the minutes in the specified date as per local time
8getMonth()It will return the month in the specified date as per local time.
9getSeconds()It will return the seconds in the specified date as per local time.
10getTime()It will return the numeric value of the specified date as the number of milliseconds
11getTimezoneOffset()It will return the time-zone offset in minutes for the current locale
12getYear()It will returns the year in the specified date of local time
13setDate()It will sets the day of the month for a specified date of local time.
14setFullYear()It will set the full year for a specified date of local time.
15setHours()It will set the hours for a specified date of local time
16setMilliseconds()This method is forsets the milliseconds for a specified date of local time.
17setMinutes()This method is used to set the minutes for a specified date of local time
18setMonth()This method is used to set the month for a specified date of local time.
19setSeconds()This method is used to set the seconds for a specified date of local time.
20setTime()This method is used to set the Date object to the time represented by a number of milliseconds.

Math Object in JavaScript

The JavaScript Math object used to perform mathematical tasks with numbers.Math is an object that has properties and methods.

Math has no constructor. All Math’s properties and methods are static.

To refer methods and properties use Math.propertName  and functions as Math.funcationName().

For example to access the constant pi use Math.PI

To call the sine function use Math.sin(valuex), where valuex is a argument. Constants are defined with the full precision of real numbers.

The math object provide properties and methods of constants and functions for mathematical.

Math’s properties and methods can be called by using Math as an object without creating it.



Math Properties (Constants)

EIt will return Euler’s number (approx. 2.718).
LN2It will return tde natural logaritdm of 2 (approx. 0.693)
LN10It will return tde natural logaritdm of 10 (approx. 2.302)
LOG2EIt will return tde base-2 logaritdm of E (approx. 1.442)
LOG10EIt will return tde base 10 logaritdm of E (approx. 0.434)
PIIt will return constant value of PI (approx. 3.14)
SQRT1_2It will return tde square root of 1/2 (approx. 0.707)
SQRT2It will returnstde square root of 2 (approx. 1.414)

Math Object Methods

abs(valuex)It will return the absolute value of valuex
acos(valuex)It will return the arccosine of valuex, in radians
asin(valuex)It will return the arcsine of valuex, in radians
atan(valuex)It will return the arctangent of valuex as a numeric value between -PI/2 and PI/2 radians
atan2(valuey, valuex)It will return the arctangent of the quotient of its arguments
ceil(valuex)It will return the value of valuex rounded up to its nearest integer
cos(valuex)It will return the cosine of valuex (valuex is in radians)
exp(valuex)It will return the value of Ex
floor(valuex)It will return the value of valuex rounded down to its nearest integer
log(valuex)It will return the natural logarithm (base E) of valuex
max(valuex,value y, valuez, …, valuen)It will return the number with the highest value
min(valuex,valuey, valuez, …, valuen)It will return the number with the lowest value
pow(valuex, valuey)It will return the value of valuex to the power of valuey
random()It will return a random number between 0 and 1
round(valuex)It will return the value of valuex rounded to its nearest integer
sin(valuex)It will return the sine of valuex (valuex is in radians)
sqrt(valuex)It will return the square root of valuex
tan(valuex)It will return the tangent of an angle

Read More

  1. Get multiple checkbox value in javascript
  2. Add active class onclick
  3. JavaScript Multiplication Table
  4. isPrime() Javascript : Prime number program
  5. Form Handling and Validation
  6. Try Catch and Finally in JavaScript

Global in JavaScript

Global scope is a JavaScript function Scope.Scope determines the accessibility (visibility) of variables.

Variables defined inside a function are not accessible (visible) from outside the function.

A global variable is declared outside the function or declared with an object. It can be accessed from any function.

Declaring global variable within function

To declare global variables within a function, we need to use window object. For example:

Now this value can declared with in any function and can be access and used from any function.

For example:



Internals of global variable

On outside a function,when a variable declare, that will add in window object. So it can be access through window object.

For example:

Global JavaScript Variables

If any variable declared outside a function, so that will becomes GLOBAL.

A global variable has global scope: All scripts and functions on a web page can access it. 


Automatically Global

If a value assign to a variable that has not been declared, it will automatically turn on GLOBAL variable.

This example will declare a global variable myName, the value is assigned inside a function.


Global Variables in HTML

With JavaScript, the global scope is the complete
JavaScript environment.

In HTML, the global scope is the window object. All global variables belong to the window object.


Global Properties

InfinityA numeric value that represents positive/negative infinity
NaN“Not-a-Number” value, It means there is nothing like value.
undefinedThis property indicates that a variable will not assigned a value.

Global Functions

decodeURI()It will decodes a URI
decodeURIComponent()It will decodes a URI component
encodeURI()It will encode a URI
encodeURIComponent()It will encode a URI component
escape()It will use encodeURI() or encodeURIComponent() instead
eval()It willevaluates a string and executes it as if it was script code.
isFinite()It will determine whether a value is a finite, normal number
Number()It will convert an object’s value to a number
parseFloat()It will parse a string and returns a floating point number
parseInt()It will parse a string and returns an integer
String()It will convert an object’s value to a string
unescape()It will use decodeURI() or decodeURIComponent() instead

Functions in JavaScript

What is a Function?

  • A function is a block of code or a subprogram designed to perform a particular task.
  • Function is executed only when it is called. This is called invoking/calling a function. Thus it eliminates writing the same code again and again.
  • Values can be passed into functions and used within the function body.

Function always returns a value, if no return type is specified, the function will return undefined .

JavaScript Function Syntax

JavaScript supports 4 types of function invoking:

  1. Function having no arguments and no return value
  2. Function having arguments and no return value
  3. Function having return value and argument(s)
  4. Function having return value but no arguments

Function having no arguments and no return value

In JavaScript, if there’s no specified return type, the function will return undefined. Consider the following example:



Function having arguments and no return value

Consider the following example:


Here the ‘return’ statement is missing. But arguments are passed to the function and used in the block of code.

Function having return value and arguments


Function having return value but no arguments