JavaScript Programming Fundamentals Guide
JavaScript Programming Fundamentals Guide
JavaScript is a text-based programming language used both on the client-side and server-
side that allows you to make web pages interactive. Where HTML and CSS are languages
that give structure and style to web pages, JavaScript gives web pages interactive elements
that engage a user. Common examples of JavaScript that you might use every day include
the search box on Amazon
JavaScript is mainly used for web-based applications and web browsers. But JavaScript is
also used beyond the Web in software, servers and embedded hardware controls.
JavaScript can calculate, manipulate and validate data.
<h2>JavaScript Variables</h2>
<p id="demo"></p>
<script>
var x = 5;
var y = 6;
var z = x + y;
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on the operands. The
following operators are known as JavaScript arithmetic operators.
Operator Description Example
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
* Multiplication 10*20 = 200
/ Division 20/10 = 2
% Modulus (Remainder) 10%3=1
++ Increment var a=10; a++; Now a = 11
-- Decrement var a=10; a--; Now a = 9
JavaScript Comparison Operators
The JavaScript comparison operator compares the two operands. The comparison
operators are as follows:
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 the expression is true. The signature of JavaScript if
statement is given below.
if(expression)
{
//content to be evaluated
}
Flowchart of JavaScript If statement
Let’s see the example of if-else statement in JavaScript to find out the even or odd
number.
<html>
<body>
<script>
var a=20;
if(a%2==0){
[Link]("a is even number");
}
else{
[Link]("a is odd number");
}
</script>
</body>
</html>
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.
if(expression1)
{
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else
{
//content to be evaluated if no expression is true
}
Let’s see the simple example of if else if statement in javascript.
<html>
<body>
<script>
var a=20;
if(a==10){
[Link]("a is equal to 10");
}
else if(a==15){
[Link]("a is equal to 15");
}
else if(a==20){
[Link]("a is equal to 20");
}
else{
[Link]("a is not equal to 10, 15 or 20");
}
</script>
</body>
</html>
default:
code to be executed if above values are not matched;
}
Let’s see the simple example of switch statement in javascript.
<!DOCTYPE html>
<html>
<body>
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
[Link](result);
</script>
</body>
</html>
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
<!DOCTYPE html>
<html>
<body>
<script>
for (i=1; i<=5; i++)
{
[Link](i + "<br/>")
}
</script>
</body>
</html>
while (condition)
{
//code to be executed
}
Let’s see the simple example of while loop in javascript.
<!DOCTYPE html>
<html>
<body>
<script>
var i=11;
while (i<=15)
{
[Link](i + "<br/>");
i++;
}
</script>
</body>
</html>
Popup Boxes
JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.
Alert Box
An alert box is often used if you want to make sure information comes through to
the user.
When an alert box pops up, the user will have to click "OK" to proceed.
Syntax
[Link]("sometext");
The [Link]() method can be written without the window prefix
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Alert</h2>
<script>
function myFunction() {
alert("I am an alert box!");
}
</script>
</body>
</html>
Confirm Box
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to
proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box
returns false.
Syntax
[Link]("sometext");
The [Link]() method can be written without the window prefix.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Confirm Box</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
if (confirm("Press a button!")) {
txt = "You pressed OK!";
} else { txt = "You pressed Cancel!";
}[Link]("demo").innerHTML = txt;
}</script>
</body>
</html>
Prompt Box
A prompt box is often used if you want the user to input a value before entering a
page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to
proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel"
the box returns null.
Syntax
[Link]("sometext","defaultText");
The [Link]() method can be written without the window prefix.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Prompt</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
var person = prompt("Please enter your name:", "Harry Potter");
if (person == null || person == "") {
txt = "User cancelled the prompt.";
} else {
txt = "Hello " + person + "! How are you today?";
}
[Link]("demo").innerHTML = txt;
}
</script>
</body>
</html>
Functions
Defining and Invoking a Function, Defining Function arguments, Defining a Return
Statement, Calling Functions with Timer
Defining and Invoking a Function:
JavaScript functions are defined with the function keyword.
functions are declared with the following syntax:
function functionName(parameters)
{
// code to be executed
}
Example
function myFunction(a, b)
{
return a * b;
}
Invoking a JavaScript Function
The code inside a function is not executed when the function is defined.
The code inside a function is executed when the function is invoked(call).
It is common to use the term "call a function" instead of "invoke a function".
It is also common to say "call upon a function", "start a function", or "execute a
function".
<html>
<head>
<script type = "text/javascript">
function sayHello() {
[Link] ("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello">
</form>
</body>
</html>
Defining Function arguments
Function Parameters are the names that are define in the function definition and real
values passed to the function in function definition are known as arguments.
Syntax:
function Name(parameter1, parameter2, paramet3,parameter4)
{
// Statements
}
Parameter Rules:
There is no need to specify the data type for parameters in JavaScript function
definitions.
It does not perform type checking based on passed in JavaScript function.
It does not check the number of received arguments.
Parameters:
Name: It is used to specify the name of the function.
Arguments: It is provided in the argument field of the function.
<html>
<head>
<script type = "text/javascript">
function sayHello(name, age) {
[Link] (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello('Zara', 7)" value = "Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
Function Return
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the
code after the invoking statement.
Functions often compute a return value. The return value is "returned" back to the
"caller":
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>This example calls a function which performs a calculation, and returns the
result:</p>
<p id="demo"></p>
<script>
function myFunction(p1, p2) {
return p1 * p2;
}
[Link]("demo").innerHTML = myFunction(4, 3);
</script>
</body>
</html>
<script>
function myFunction() {
setTimeout(function(){ alert("Hello"); }, 3000);
}
</script>
</body>
</html>
The clearTimeout() method stops the execution of the function specified in
setTimeout().
[Link](timeoutVariable)
<!DOCTYPE html>
<html>
<body>
<p>Click "Try it". Wait 3 seconds. The page will alert "Hello".</p>
<p>Click "Stop" to prevent the first function to execute.</p>
<p>(You must click "Stop" before the 3 seconds are up.)</p>
<script>
function myFunction() {
alert("Hello");
}
</script>
</body>
</html>
The setInterval() Method
The setInterval() method repeats a given function at every given time-interval.
[Link](function, milliseconds);
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var myVar = setInterval(myTimer, 3000);
function myTimer() {
var d = new Date();
[Link]("demo").innerHTML = [Link]();
}
</script>
</body>
</html>
The clearInterval() method stops the executions of the function specified in the
setInterval() method.
[Link](timerVariable)
JavaScript String
The JavaScript string is an object that represents a sequence of characters.
There are 2 ways to create string in JavaScript
By string literal
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:
var stringname="string value";
Let's see the simple example of creating string literal.
<script>
var str="This is string literal";
[Link](str);
</script>
Methods Description
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.
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.
Example1:
<!DOCTYPE html>
<html>
<body>
<script>
var str="javascript";
[Link]([Link](2));
</script>
</body>
</html>
Example 2:
<!DOCTYPE html>
<html>
<body>
<script>
var s1="JavaScript toLowerCase Example";
var s2=[Link]();
[Link](s2);
</script>
</body>
</html>
Regular expression
A regular expression is an object that describes a pattern of characters.
The JavaScript RegExp class represents regular expressions, and both String and
RegExp define methods that use regular expressions to perform powerful pattern-
matching and search-and-replace functions on text.
Syntax
var pattern = new RegExp(pattern, attributes);
or simply
var pattern = /pattern/attributes;
here/mumbai/i is a city
● pattern − A string that specifies the pattern of the regular expression or another
regular expression.
● attributes − An optional string containing any of the "g", "i", and "m"
attributes that specify global, case-insensitive, and multi-line matches,
respectively.
Brackets
Brackets ([ ]) have a special meaning when used in the context of regular
expressions. They are used to find a range of characters.
[Link]. Expression & Description
1 [...]
Any one character between the brackets.
3 [0-9]
It matches any decimal digit from 0 through 9.
4 [a-z]
It matches any character from lowercase a through lowercase z.
5 [A-Z]
It matches any character from uppercase A through uppercase Z.
6 [a-Z]
It matches any character from lowercase a through uppercase Z.
The ranges shown above are general; you could also use the range [0-3] to match
any decimal digit ranging from 0 through 3, or the range [b-v] to match any
lowercase character ranging from b through v.
Quantifiers
The frequency or position of bracketed character sequences and single characters
can be denoted by a special character. Each special character has a specific
connotation. The +, *, ?, and $ flags all follow a character sequence.
[Link]. Expression & Description
1 p+
It matches any string containing one or more p's.
2 p*
It matches any string containing zero or more p's.
3 p?
It matches any string containing at most one p.
4 p{N}
It matches any string containing a sequence of N p's
5 p{2,3}
It matches any string containing a sequence of two or three p's.
6 p{2, }
It matches any string containing a sequence of at least two p's.
7 p$
It matches any string with p at the end of it.
8 ^p
It matches any string with p at the beginning of it.
Examples
Following examples explain more about matching characters.
[Link] Expression & Description
.
1 [^a-z A-Z]
It matches any string not containing any of the characters ranging from a
through z and A through Z.
2 p.p
It matches any string containing p, followed by any character, in turn
followed by another p.
3 ^.{2}$
It matches any string containing exactly two characters.
4 <b>(.*)</b>
It matches any string enclosed within <b> and </b>.
5 p(hp)*
It matches any string containing a p followed by zero or more instances of
the sequence hp.
Literal characters
[Link] Character & Description
.
1 Alphanumeric
Itself- A to Z ,0-9
2 \0
The NUL character (\u0000)
3 \t
Tab (\u0009
4 \n
Newline (\u000A)
5 \v
Vertical tab (\u000B)
6 \f
Form feed (\u000C)
7 \r
Carriage return (\u000D)
8 \xnn
The Latin character specified by the hexadecimal number nn; for example,
\x0A is the same as \n
9 \uxxxx
The Unicode character specified by the hexadecimal number xxxx; for
example, \u0009 is the same as \t
10 \cX
The control character ^X; for example, \cJ is equivalent to the newline
character \n
Metacharacters
A metacharacter is simply an alphabetical character preceded by a backslash that
acts to give the combination a special meaning.
For instance, you can search for a large sum of money using the '\d' metacharacter:
/([\d]+)000/, Here \d will search for any string of numerical character.
The following table lists a set of metacharacters which can be used in PERL Style
Regular Expressions.
[Link] Character & Description
.
1 .
a single character
2 \s
a whitespace character (space, tab, newline)
3 \S
non-whitespace character
4 \d
a digit (0-9)
5 \D
a non-digit
6 \w
a word character (a-z, A-Z, 0-9, _)
7 \W
a non-word character
8 [\b]
a literal backspace (special case).
9 [aeiou]
matches a single character in the given set
10 [^aeiou]
matches a single character outside the given set
11 (foo|bar|baz)
matches any of the alternatives specified
Modifiers
Several modifiers are available that can simplify the way you work with regexps,
like case sensitivity, searching in multiple lines, etc.
[Link] Modifier & Description
.
1 i
Perform case-insensitive matching.
2 m
Specifies that if the string has newline or carriage return characters, the ^
and $ operators will now match against a newline boundary, instead of a
string boundary
3 g
Performs a global match that is, find all matches rather than stopping after
the first match.
RegExp Properties
Here is a list of the properties associated with RegExp and their description.
[Link]. Property & Description
1 constructor
Specifies the function that creates an object's prototype.
2 global
Specifies if the "g" modifier is set.
3 ignoreCase
Specifies if the "i" modifier is set.
4 lastIndex
The index at which to start the next match.
5 multiline
Specifies if the "m" modifier is set.
6 source
The text of the pattern.
In the following sections, we will have a few examples to demonstrate the usage of
RegExp properties.
RegExp Methods
Here is a list of the methods associated with RegExp along with their description.
[Link] Method & Description
.
1 exec()
Executes a search for a match in its string parameter.
2 test()
Tests for a match in its string parameter.
3 toSource()
Returns an object literal representing the specified object; you can use this
value to create a new object.
4 toString()
Returns a string representing the specified object.
The math object provides you properties and methods for mathematical constants
and functions. Unlike other global objects, Math is not a constructor. All the
properties and methods of Math are static and can be called by using Math as an
object without creating it.
Thus, you refer to the constant pi as [Link] and you call the sine function as
[Link](x), where x is the method's argument.
Syntax
The syntax to call the properties and methods of Math are as follows
var pi_val = [Link];
var sine_val = [Link](30);
Math Methods
Here is a list of the methods associated with Math object and their description
[Link] Method & Description
.
1 abs()
Returns the absolute value of a number.
2 acos()
Returns the arccosine (in radians) of a number.
3 asin()
Returns the arcsine (in radians) of a number.
4 atan()
Returns the arctangent (in radians) of a number.
5 atan2()
Returns the arctangent of the quotient of its arguments.
6 ceil()
Returns the smallest integer greater than or equal to a number.
7 cos()
Returns the cosine of a number.
8 exp()
Returns EN, where N is the argument, and E is Euler's constant, the base
of the natural logarithm.
9 floor()
Returns the largest integer less than or equal to a number.
10 log()
Returns the natural logarithm (base E) of a number.
11 max()
Returns the largest of zero or more numbers.
12 min()
Returns the smallest of zero or more numbers.
13 pow()
Returns base to the exponent power, that is, base exponent.
14 random()
Returns a pseudo-random number between 0 and 1.
15 round()
Returns the value of a number rounded to the nearest integer.
16 sin()
Returns the sine of a number.
17 sqrt()
Returns the square root of a number.
18 tan()
Returns the tangent of a number.
19 toSource()
Returns the string "Math".
getDay() It returns the integer value between 0 and 6 that represents the
day of the week on the basis of local time.
getFullYears() It returns the integer value that represents the year on the basis
of local time.
getMilliseconds() It returns the integer value between 0 and 999 that represents
the milliseconds on the basis of local time.
getUTCDay() It returns the integer value between 0 and 6 that represents the
day of the week on the basis of universal time.
getUTCFullYears It returns the integer value that represents the year on the basis
() of universal time.
setDate() It sets the day value for the specified date on the basis of local
time.
setDay() It sets the particular day of the week on the basis of local time.
setFullYears() It sets the year value for the specified date on the basis of local
time.
setHours() It sets the hour value for the specified date on the basis of local
time.
setMilliseconds() It sets the millisecond value for the specified date on the basis
of local time.
setMinutes() It sets the minute value for the specified date on the basis of
local time.
setMonth() It sets the month value for the specified date on the basis of
local time.
setSeconds() It sets the second value for the specified date on the basis of
local time.
setUTCDate() It sets the day value for the specified date on the basis of
universal time.
setUTCDay() It sets the particular day of the week on the basis of universal
time.
setUTCFullYears It sets the year value for the specified date on the basis of
() universal time.
setUTCHours() It sets the hour value for the specified date on the basis of
universal time.
setUTCMilliseco It sets the millisecond value for the specified date on the basis
nds() of universal time.
setUTCMinutes() It sets the minute value for the specified date on the basis of
universal time.
setUTCMonth() It sets the month value for the specified date on the basis of
universal time.
setUTCSeconds() It sets the second value for the specified date on the basis of
universal time.
toUTCString() It converts the specified date in the form of string using UTC
time zone.
Example:
<html>
<body>
Current Date and Time: <span id="txt"></span>
<script>
var today=new Date();
</script>
</body>
</html>
Window Object
The Browser Object Model (BOM) is used to interact with the browser.
The default object of browser is window means you can call all the functions
of window by specifying window or directly. For example:
[Link]("hello javatpoint");
Method Description
confirm() displays the confirm dialog box containing a message with ok and
cancel buttons.
setTimeou performs action after specified time like calling function, evaluating
t() expressions etc.
<script type="text/javascript">
function msg()
{
open("[Link]
}
</script>
<input type="button" value="javatpoint" onclick="msg()"/>
JavaScript Navigator Object
The JavaScript navigator object is used for browser detection. It can be used to
get browser information such as appName, appCodeName, userAgent etc.
[Link]
<html>
<body>
<script>
[Link]("<br/>[Link]: "+[Link]);
[Link]("<br/>[Link]: "+[Link]);
[Link]("<br/>[Link]: "+[Link]);
[Link]("<br/>[Link]: "+[Link]);
[Link]("<br/>[Link]: "+[Link]);
[Link]("<br/>[Link]: "+[Link]);
[Link]("<br/>[Link]: "+[Link]);
</script>
</body>
</html>
The JavaScript history object represents an array of URLs visited by the user. By
using this object, you can load previous, forward or any particular page.
[Link]
Location Object
The location object is part of the window object and is accessed through the
[Link] property.
Property Description
<!DOCTYPE html>
<html>
<body>
<p id="a"></p>
<script>
+ [Link]; </script>
</body></html>
JavaScript HTML DOM Document
If you want to access any element in an HTML page, you always start with accessing
the document object.
Below are some examples of how you can use the document object to access and
manipulate HTML.
Method Description
Method Description
Method Description
Method Description
[Link](id).onclick = Adding event handler code to an
function(){code} onclick event
The first HTML DOM Level 1 (1998), defined 11 HTML objects, object collections,
and properties. These are still valid in HTML5.
Later, in HTML DOM Level 3, more objects, collections, and properties were added.
When a user sends a request to the server, then each of that request is treated as a
new request sent by the different user.
So, to recognize the old user, we need to add the cookie with the response from the
server.
Now, whenever a user sends a request to the server, the cookie is added with that
request automatically. Due to the cookie, the server recognizes the users.
JavaScript Cookies
How to create a Cookie in JavaScript?
[Link]="name=value";
<!DOCTYPE html>
<html>
<head>
</head>
<body>
[Link]="username=Duke Martin";
}
function getCookie()
if([Link]!=0)
{
alert([Link]);
}
else
</script>
</body>
</html>
6. Form Control Elements:: Form can have many control elements such
as text fields, buttons, radio buttons, and checkboxes, etc.
It is important to validate the form submitted by the user because it can have
inappropriate values. So, validation is must to authenticate users.
JavaScript provides a facility to validate the form on the client-side so data
processing will be faster than server-side validation. Most of the web developers
prefer JavaScript form validation.
Through JavaScript, we can validate name, password, email, date, mobile numbers
and more fields.
JavaScript Form Validation Example
In this example, we are going to validate the name and password. The name can’t be
empty and the password can’t be less than 6 characters long.
Here, we are validating the form on form submit. The user will not be forwarded to
the next page until given values are correct.
<script>
function validateform(){
var name=[Link];
var
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if([Link]<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="[Link]" onsubmit="return
validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
<script>
function validate(){
var num=[Link];
if (isNaN(num)){
[Link]("numloc").innerHTML="Enter Numeric value only";
return false;
}else{
return true;
}
}
</script>
<form name="myform" onsubmit="return validate()" >
Number: <input type="text" name="num"><span id="numloc"></span><br/>
<input type="submit" value="submit">
</form>
There are many criteria that need to be follow to validate the email id such as:
<script>
function validateemail()
{
var x=[Link];
var atposition=[Link]("@");
var dotposition=[Link](".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=[Link]){
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n
dotposition:"+dotposition);
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="#" onsubmit="return
validateemail();">
Email: <input type="text" name="email"><br/>