UNIT – III
Introduction to JavaScript: What is DHTML, JavaScript, basics, variables, string manipulations, mathematical functions, statements, operators, arrays, functions.
Dynamic HTML
Dynamic HTML, or DHTML, is a collection of technologies used together to make interactive and animated website by using a combination of JavaScript, HTML, DOM (Document object module) and CSS
Features of DHTML:
1. Simplest feature is making the page dynamic.
2. Can be used to create animations, games, applications, provide new ways of navigating through web sites.
3. DHTML use low-bandwidth effect which enhance web page functionality. 4. Dynamic building of web pages is simple as no plug-in is required.
5. Facilitates the usage of events, methods and properties and code reuse. Write About The Technology Components Of DHTML.
The major components of Dynamic HTML technology are:- 1. HTML
2. CSS 3. Scripting
4. Document Object Model(DOM)
****************************************************************************** What is a Script
A script is an executable list of commands like macro or batch file created by a scripting language. Scripts (like PHP, Perl) which are executed on a web server are called server-side scripts and scripts (like JavaScript) which are executed on user's computer, interpreted by the browser is called client-side scripts.
What is JavaScript?
Client Side Programming: JavaScript
JavaScript is a scripting language
A scripting language is a lightweight programming language
JavaScript is usually embedded directly into HTML pages
JavaScript is an interpreted language (means that scripts execute without preliminary compilation)
What can a JavaScript do?
JavaScript can put dynamic text into an HTML page
JavaScript can react to events - A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element
JavaScript can read and write HTML elements - A JavaScript can read and change the content of an HTML element
JavaScript can be used to validate data - A JavaScript can be used to validate form data before it is submitted to a server. This saves the server from extra processing
JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve information on the visitor's computer
The Real Name is ECMAScript. JavaScript is an implementation of the ECMAScript language standard. ECMAScript is developed and maintained by the ECMA organization. ECMA-262 is the official JavaScript standard.
The language was invented by Brendan Eich at Netscape (with Navigator 2.0), and has appeared in all Netscape and Microsoft browsers since 1996. The development of ECMA-262 started in 1996, and the first edition of was adopted by the ECMA General Assembly in June 1997. The standard was approved as an international ISO (ISO/IEC 16262) standard in 1998. The development of the standard is still in progress.
Are Java and JavaScript the Same?
• NO!
• Java and JavaScript are two completely different languages in both concept and design!
• Java (developed by Sun Microsystems) is a powerful and much more complex programming language - in the same category as C and C++.
Structure of Java Script <html>
<head>
<script language=”javascript” type="text/javascript">
---</script> </head>
<body>
---</body>
</html>
To insert a JavaScript into an HTML page, we use the <script> tag. Inside the <script> tag we use the type attribute to define the scripting language.
The script Tag
The script is an HTML element. Html script element is used to enclose client side scripts like JavaScript within an HTML document.
Syntax <script>
JavaScript statements... </script>
There are mainly three types of attributes in script element: 1. language
The language attribute is used to specify the scripting language and it's version for the enclosed code. In the following example, JavaScript version is 1.2. If you do not specify a language attribute, the default behavior depends on the browser version.
Example
2. src
This attribute specifies the location of an external script. This attribute is useful for sharing functions among many different pages. Note that external JavaScript files contain only JavaScript statements and files must have the extension .js.
Example
<script src = "common.js"> JavaScript statements... </script>
3. type
This attribute specifies the scripting language. The scripting language is specified as a content type (e.g., "text/javascript" ). The attribute is supported by all modern browsers.
Example
<script type="text/javascript"> JavaScript statements... </script>
The noscript tag
If any browser does not support the JavaScript code the alternate content placed within noscript tag is being executed.
Example <noscript>
... code .... </noscript>
****************************************************************************** Embedding JavaScript in HTML
We can put the JavaScript code in a html document in the following three places 1. Between the body tag of html
Javascript in <body> and <head> tags in a HTML document
There are two general areas in HTML document where JavaScript can be placed. First is between <head>...</head> section, another is specific location in <body>...</body> section. If you want to display a message 'Good Morning' (through the JavaScript alert command) at the time of page loading then you must place the script at the <head>...</head> section.
The following examples explain about how the <script> ….</script> tags can be placed in different locations in a HTML document.
Script in the Head <html>
<head>
<title> Script in head section </title> <script type = "text/javascript">
JavaScript statements... </script>
</head> <body> </body> </html>
Script in the Body <html>
<head>
<title> Script in the Body </title> </head>
<body>
<script type = "text/javascript"> JavaScript statements... </script>
</body> </html>
Scripts in the Head and Body <html>
<head>
<title> Script in head and body section </title> <script type = "text/javascript">
JavaScript statements... </script>
</head> <body>
<script type = "text/javascript"> JavaScript statements... </script>
</html>
External JavaScript file
We can create external JavaScript file and embed it in many html page.
It provides code re usability because single JavaScript file can be used in several html pages.
An external JavaScript file must be saved by .js extension. It is recommended to embed all JavaScript files into a single file. It increases the speed of the webpage.
Let’s create an external JavaScript file that prints Hello BVRICE in a alert dialog box. message.js
function msg() {
alert("Hello BVRICE"); }
Let’s include the JavaScript file into html page. It calls the JavaScript function on button click. index.html
<html>
<head>
<script type="text/javascript" src="message.js"></script> </head>
<body>
<p>Welcome to JavaScript</p> <form>
<input type="button" value="click" onclick="msg()"/> </form>
</body> </html>
****************************************************************************** Variables in Javascript
A JavaScript variable is simply a name of storage location. There are two types of variables in JavaScript : local variable and global variable.
There are some rules while declaring a JavaScript variable (also known as identifiers). 1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign. 2. After first letter we can use digits (0 to 9), for example value1.
Declaring (Creating) JavaScript Variables
Creating variables in JavaScript is most often referred to as "declaring" variables. You can declare JavaScript variables with the var keyword:
Syntax:
var variable_name; Example:
var x;
var carname;
After the declaration shown above, the variables are empty (they have no values yet). However, you can also assign values to the variables when you declare them:
var x=5;
var carname="Volvo";
After the execution of the statements above, the variable x will hold the value 5, and carname will hold the value Volvo.
Assigning Values to Undeclared JavaScript Variables
If you assign values to variables that have not yet been declared, the variables will automatically be declared. These statements:
x=5;
carname="Volvo"; They have the same effect as:
var x=5;
var carname="Volvo";
****************************************************************************** Local and Global Variables in Javascript
JavaScript local variable
A JavaScript local variable is declared inside block or function. It is accessible within the function or block only. For example:
<script>
{
var x=10;//local variable }
</script>
OR <script>
if(10<13) {
var y=20;//JavaScript local variable }
</script>
JavaScript global variable
A JavaScript global variable is accessible from any function. A variable i.e. declared outside the function or declared with window object is known as global variable.
For example: <html>
<body>
<script>
var data=200;//gloabal variable function a()
{
document.writeln(data); }
function b() {
document.writeln(data); }
a();//calling JavaScript function b();
</script> </body>
</html> Output 200 200
Differentiating Local and Global Variables in Javascript
The local and global variables are differentiated in javascript using “this” keyword. The following javascript program will differentiate the local and global variables.
<html> <head>
var x=10;//declaring global variable function f1()
{
var x=20;//declaring local variable
document.write("<br>The local value of x:" + x); document.write("<br>The global value of x:" + this.x);
var sum=x+this.x;
document.write("<br>The sum is:" + sum); }
</script> <body>
<h1>Example on local and global variable</h1> <hr>
<script language="javascript">
f1();//calling the function </script>
</body> </html>
Output
****************************************************************************** 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 we don't need to specify type of the variable because it is dynamically used by JavaScript engine. We need to use var here to specify the data type. It can hold any type of values such as numbers, strings etc. For example:
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
****************************************************************************** JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands. For example:
var sum=10+20;
Here, + is the arithmetic operator and = is the assignment operator. There are following types of operators in JavaScript.
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
String Operator
Miscellaneous Operators Arithmetic Operators
Arithmetic operators are used to perform arithmetic between variables and/or values. Given that y=5, the table below explains the arithmetic operators:
Operato r
Description Exampl
e
+ Addition x=y+2 x=7
- Subtraction x=y-2 x=3
* Multiplication x=y*2 x=10
/ Division x=y/2 x=2.5
% Modulus (division remainder) x=y%2 x=1
++ Increment x=++y x=6
-- Decrement x=--y x=4
Note − Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give "a10". Comparison Operators
Comparison operators are used in logical statements to determine equality or difference between variables or values.
Given that x=5, the table below explains the comparison operators: Operato
r Description Example
== is equal to x==8 is false
=== is exactly equal to (value and type) x===5 is true x==="5" is false
!= is not equal x!=8 is true
> is greater than x>8 is false
< is less than x<8 is true
>= is greater than or equal to x>=8 is false <= is less than or equal to x<=8 is true Logical Operators
Logical operators are used to determine the logic between variables or values. Given that x=6 and y=3, the table below explains the logical operators:
Operator Descriptio
n Example
&& and (x < 10 && y > 1) is true || or (x==5 || y==5) is false
! not !(x==y) is true
Assignment Operators
Assignment operators are used to assign values to JavaScript variables. Given that x=10 and y=5, the table below explains the assignment operators:
Operator Example Same As
= x=y x=5
+= x+=y x=x+y x=15
-= x-=y x=x-y x=5
*= x*=y x=x*y x=50
/= x/=y x=x/y x=2
%= x%=y x=x%y x=0
String Operator
A string is most often text, for example "Hello World!". To stick two or more string variables together, use the + operator.
txt1="III MPCs students" txt2=" are very good!" txt3=txt1+txt2
The variable txt3 now contains "III MPCs students are very good!".
To add a space between two string variables, insert a space into the expression, OR in one of the strings.
txt1="III MPCs students" txt2=" are very good!" txt3=txt1+" "+txt2 OR
txt1="III MPCs students" txt2=" are very good!" txt3=txt1+txt2
The variable txt3 now contains "III MPCs students are very good!". Miscellaneous Operator
We will discuss two operators here that are quite useful in JavaScript: the conditional operator (? :) and the typeof operator.
Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation.
The syntax is as follows ? : (Conditional ) Example:
If Condition (10>20) is true? Then value of big is 10 : Otherwise value big is 20. typeof Operator
The typeof operator is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand.
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number, string, or boolean value and returns true or false based on the evaluation.
Here is a list of the return values for the typeof Operator.
Type String Returned by typeof Number "number"
String "string" Boolean "boolean" Object "object" Function "function" Undefine
d
"undefined"
Null "object"
****************************************************************************** Control Structures in Javascript
Control Statements
Control statements are designed to allow you to create scripts that can decide which lines of code are evaluated, or how many times to evaluate them.
There are three different types of control statements: conditional statements
loop statements jumping statements
Conditional Statements
Conditional statements are used to make decisions. In real life, we make all sorts of decisions based on criteria such as "am I being offered enough money to take this job?" If the answer is "yes," then the result is "take the job." If the answer is "no," then "don't take the job." In JavaScript, you need to make decisions about which sections of code to evaluate.
Javascript control statement is used to control the flow of program based on the specified condition.
1. If Statement 2. If else statement 3. if else if statement JavaScript If Statement:
If statement is used to execute a block of statements if specified condition is true. Syntax:
if(condition) {
//Block of JavaScript statements. }
Example <html> <body>
<h1>Demo: if condition</h1>
<script>
if( 1 > 0) {
document.write("1 is greater than 0"); }
if( 1 < 0) {
document.write("1 is less than 0"); }
</script> </body> </html> Output
JavaScript If Else Statement:
If else statement is used to execute either of two block of statements depends upon the condition. If condition is true then if block will execute otherwise else block will execute.
Syntax:
if(condition) {
} else {
//Block of JavaScript statements2. }
Example <html> <body>
<h1>Demo: if-else condition</h1>
<script>
var mySal = 500; var yourSal = 1000;
if( mySal > yourSal) {
document.write("My Salary is greater than your salary"); }
else {
document.write("My Salary is less than or equal to your salary"); }
</script> </body> </html> Output
JavaScript If Else If Statement:
If else statement is used to execute one block of statements from many depends upon the condition. If condition1 is true then block of statements1 will be executed, else if condition2 is true block of statements2 is executed and so on. If no condition is true, then else block of statements will be executed.
Syntax:
if(condition1) {
else if(condition2) {
//Block of JavaScript statements2. }
. . .
else if(conditionn) {
//Block of JavaScript statementsn. }
else {
//Block of JavaScript statements. }
Example
<!DOCTYPE html> <html>
<body>
<h1>Demo: if-else-if condition</h1>
<script>
var mySal = 500; var yourSal = 1000;
if( mySal > yourSal) {
document.write("My Salary is greater than your salary"); }
else if(mySal < yourSal) {
document.write("My Salary is less than your salary"); }
else if(mySal == yourSal) {
document.write("My Salary is equal to your salary"); }
</script> </body> </html> Output
The switch is a conditional statement like if statement. Switch is useful when you want to execute one of the multiple code blocks based on the return value of a specified expression. Syntax:
switch(expression or literal value) {
case 1:
//code to be executed break;
case 2:
//code to be executed break;
case n:
//code to be executed break;
default:
//default code to be executed //if none of the above case executed
}
As per the above syntax, switch statement contains an expression or literal value. An expression will return a value when evaluated. The switch can includes multiple cases where each case represents a particular value.
Code under particular case will be executed when case value is equal to the return value of switch expression. If none of the cases match with switch expression value then the default case will be executed.
Points to remember :
1. The switch is a conditional statement like if statement.
2. A switch statement includes literal value or is expression based
3. A switch statement includes multiple cases that include code blocks to execute. 4. A break keyword is used to stop the execution of case block.
5. A switch case can be combined to execute same code block for multiple cases. Example: switch statement
<!DOCTYPE html> <html>
<body>
<h1>Demo: switch statement</h1> <script>
var a = 3;
document.write("case 1 executed"); break;
case 2:
document.write("case 2 executed"); break;
case 3:
document.write("case 3 executed"); break;
case 4:
document.write("case 4 executed"); break;
default:
document.write("default case executed"); }
</script> </body> </html> Output
****************************************************************************** Looping Control Statements
Sometimes you will need to repeat an operation multiple times until a certain condition is true.The types of statements used to accomplish repetitive loops are called loop statements. There are three types of loop statements:
for loop
while loop
do-while JavaScript For loop
for (var=startvalue; var<=endvalue; var=var+increment) {
code to be executed }
When a for loop executes, the following occurs:
The initializing expression initial-expression, if any, is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity.
The condition expression is evaluated. If the value of condition is true, the loop statements execute. If the value of condition is false, the for loop terminates.
The statements execute.
The update expression incrementExpression executes, and control returns to Step 2. Example
<!DOCTYPE html> <html>
<body>
<h2>Demo on for loop</h2> <hr>
<script>
document.write("<br>The numbers from 1 to 5 are....<br>"); for (i=1; i<=5; i++)
{
document.write(i + "<br/>") }
</script> </body>
while loop
When we are working with the while loop always pre-checking process will be occurred. Pre-checking process means before evolution of statement block condition part will be executed. The “while loop” will be repeats in clock wise direction.
Syntax
while (condition) {
code block to be executed }
Example of while loop <script>
var i=10; while (i<=13) {
document.write(i + "<br/>"); i++;
} </script> Result
In implementation when we need to repeat the statement block at-least 1 then go for do-while. In do-while loop post checking of the statement block condition part will be executed. syntax
do {
code to be executed increment/decrement }
while (condition);
Example of do-while loop <script>
var i=11; do{
document.write(i + "<br/>"); i++;
}while (i<=15); </script>
Result 11 12 13 14 15 for-in loop
A for-in loop iterates through the properties of an object and executes the loop's body once for each enumerable property of the object.
Here is an example: <html>
<body>
<h2>Example on for-in loop</h2> <hr>
<script>
var student = { name:"Bill", age: 25, degree: "Masters" }; for (var item in student)
{
document.write("<br>" + student[item]); // => "Bill", then 25, then "Masters"
</html> Output:
****************************************************************************** Break Statement
Break statement is used to jump out of a loop.
It is used to exit a loop early, breaking out of the enclosing curly braces. Syntax:
break;
Flow Diagram of Break Statement
Example <html> <body>
<p>A loop with a break.</p> <script>
var i;
for (i = 0; i < 10; i++) {
if (i === 3) {
break; }
document.write("<br>Value of i:" + i ); }
</body> </html> Output
Continue Statement
Continue statement causes the loop to continue with the next iteration.
It skips the remaining code block.
Syntax:
continue;
Flow Diagram of Continue Statement
Example: <html> <body>
<p>A loop with a break.</p> <script>
var i;
for (i = 0; i < 10; i++) {
if (i === 3) {
continue; }
} </script>
</body> </html> Output
JavaScript Labels
To label JavaScript statements you precede the statements with a label name and a colon: label:
statements
The break and the continue statements are the only JavaScript statements that can "jump out of" a code block.
Syntax:
break labelname;
continue labelname;
The continue statement (with or without a label reference) can only be used to skip one loop iteration.
The break statement, without a label reference, can only be used to jump out of a loop or a switch.
With a label reference, the break statement can be used to jump out of any code block: Example
<html > <head>
<title>JavaScript label with break and continue</title> </head>
<body>
<script>
outer: for(var i = 1; i <= 3; i++) {
{
if (j == 2)
{
document.writeln("<br>skipped"); continue inner;
}
else if(j == 4) {
document.writeln("<br>terminated"); break inner;
}
document.writeln("i : " + i + ", j :" + j + "<br>");
}
document.write("<br>"); }
</script> </body>
</html> Output
****************************************************************************** Strings in Javascript
In JavaScript, the textual data is stored as strings. There is no separate type for a single character. The internal format for strings is always UTF-16, it is not tied to the page encoding. Strings can be enclosed within either single quotes, double quotes or backticks:
Here is a list of the methods available in String object along with their description. charAt(index)
charCodeAt(index) concat(str)
indexOf(str) lastIndexOf(str) toLowerCase() toUpperCase()
substr(start_index, length) slice(beginIndex, endIndex) split(separator,limit)
trim() charAt(index)
charAt() is a method that returns the character from the specified index. Syntax
string.charAt(index); Example
<script>
var str="javascript";
document.write(str.charAt(2)); </script>
Output: v
charCodeAt(index)
This method returns a number indicating the Unicode value of the character at the given index. Syntax
string.charCodeAt(index); Example:
<script>
var str="ABCD";
document.write(str.charAt(2)); </script>
This method adds two or more strings and returns a new single string. Syntax
Its syntax is as follows −
string.concat(string2, string3[, ..., stringN]); Example:
<script>
var s1="BVRICE "; var s2=" IIIMPCS"; var s3=s1.concat(s2); document.write(s3); </script>
Output: BVRICE IIIMPCS indexOf(str)
This method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex or -1 if the value is not found.
Syntax
string.indexOf(searchValue, fromIndex]) Example:
<script>
var s1="B V Raju College"; var n=s1.indexOf("Raju"); document.write(n);
</script> Output: 4
lastIndexOf(str)
This method returns the index within the calling String object of the last occurrence of the specified value, starting the search at fromIndex or -1 if the value is not found.
Syntax
Its syntax is as follows −
string.lastIndexOf(searchValue, fromIndex]) Example:
<script>
var n=s1.lastIndexOf("Raju"); document.write(n);
</script> Output: 27
toLowerCase()
This method returns the calling string value converted to lowercase. Syntax
Its syntax is as follows − string.toLowerCase( ) Example:
<script>
var s1="B V Raju College"; var s2=s1.toLowerCase(); document.write(s2); </script>
Output: b v raju college toUpperCase()
This method returns the calling string value converted to uppercase. Syntax
Its syntax is as follows − string.toUpperCase( ) Example:
<script>
var s1="B V Raju College"; var s2=s1.toUpperCase(); document.write(s2); </script>
Output: B V RAJU COLLEGE substr(start_index, length)
This method returns the characters in a string beginning at the specified location through the specified number of characters.
Syntax
string.substr(start_index, length); Example:
<script>
var str = "B V Raju College";
document.write("(1,9): " + str.substr(1,9)); </script>
Output: (1,9): V Raju C
slice(beginIndex, endIndex)
This method returns the parts of string from given beginIndex to endIndex. In slice() method, beginIndex is inclusive and endIndex is exclusive.
Syntax
The syntax for slice() method is −
string.slice( beginslice [, endSlice] ); Example
<script>
var s1="B V Raju College"; var s2=s1.slice(2,10); document.write(s2); </script>
Output V Raju C
split(separator,limit)
This method splits a String object into an array of strings by separating the string into substrings.
Syntax
Its syntax is as follows −
string.split([separator][, limit]); Example
Output
B,V,Raju,College trim()
This method removes leading and trailing whitespaces from the string. Syntax:
string.trim(); Example:
<script>
var s1=" B V Raju College "; var s2=s1.trim();
document.write(s2); </script>
Output
B,V,Raju,College
****************************************************************************** Mathematical Functions in Javascript
The JavaScript math object provides several constants and methods to perform mathematical operation. Unlike date object, it doesn't have constructors.
Here is a list of the methods associated with Math object and their description Sr.No Method & Description
1 abs()
Returns the absolute value of a number. 2 ceil()
Returns the smallest integer greater than or equal to a number. 3 cos()
Returns the cosine of a number. 4 exp()
Returns EN, where N is the argument, and E is Euler's constant, the base of the natural
logarithm. 5 floor()
Returns the largest integer less than or equal to a number.
6 log()
7 max()
Returns the largest of zero or more numbers.
8 min()
Returns the smallest of zero or more numbers.
9 pow()
Returns base to the exponent power, that is, base exponent.
10 random()
Returns a pseudo-random number between 0 and 1.
11 round()
Returns the value of a number rounded to the nearest integer.
12 sin()
Returns the sine of a number.
13 sqrt()
Returns the square root of a number.
14 tan()
Returns the tangent of a number.
Example: <html> <head>
<title>JavaScript Math Object: Simple Computations and Constants</title> <script language=”javascript”>
var value = 25;
document.write("The log of the number is 25 <b>" + Math.log(value)+ "</b></br>"); document.write("The square root of the number 25 is <b>" + Math.sqrt(value)+ "</b></br>");
document.write("The value of Constant PI is <b>" + Math.PI+ "</b></br>");
document.write("The number 25 raised to the power of 2 is <b>" + Math.pow(value,2)+ "</b></br>");
var value1 = 25.67;
document.write("Rounding 25.6 using <b><i>Math.ceil(value)</i></b> results in : <b>" + Math.ceil(value1)+ "</b></br>");
document.write("Rounding 25.6 using <b><i>Math.round(value)</i></b> results in : <b>" + Math.round(value1)+ "</b></br>");
</script> </head> <body> </body> </html>
Output
****************************************************************************** Arrays in Javascript
An array is defined as a collection of like elements or values, eg a collection of names, images, audio files etc.
But according to JavaScript Specifications, arrays are ordered list of data, that can hold any type of data in each of the slots assigned, i.e a number in the first, string in the second, video file in third and so on and so forth.
Creating an Array
In JavaScript, arrays can be created using three basic ways: Constructor Method and array literal .
Creating Arrays Using Constructor Method
A new keyword is used to create an array object on the fly, by calling the Array's object constructor function Array()
If an array is created with a predefined length, but not values then the empty array elements are assigned the value undefined
Syntax:
var array_name = new array(10); // create an array of size 10; Example:
var cities = new Array(5); // create an array with 5 items. Creating Arrays using Literal Notation
Another easy and quick way to create an array is to use an array literal notation.
An array literal is specified by using square brackets and within them placing a comma-separated list of array items. Else everything remains the same.
Syntax:
var array_name = [item1, item2, item3, item4]; Example:
var cities = ["Dubai", "Mumbai", "Paris", "London"];
****************************************************************************** Javascript Array Object Methods
Like all other objects in JavaScript, the arrays too can be have a list of methods which can be used to manipulate it .
These methods can be used for various purposes like, adding new elements, removing elements, joining two arrays etc.
Methods of an Array are as follows Propertie
s
Description
push() To push(add) elements at the end of an array.
pop() To pop(remove) and return the last elements of an array
concact() To concat elements from one array to another array.
join() To join the elements of an array using a separator to form a string.
shift() To remove and return the first element of an array .
slice() To create a new array from elements of an existing array
sort() To sort an array either alphabetically or numerically.
splice() To remove or replace the elements of an array.
unShift() To add elements at the start of an array.
Concat()
The Javascript Array Method concat() is used to join two array objects and create a new array which is result of concatenation of two arrays.
Syntax:
array3 = array1.concat("array2"); Example:
<script type="text/javascript"> var alpha = ["a", "b", "c"]; var numeric = [1, 2, 3];
var alphaNumeric = alpha.concat(numeric);
document.write("alphaNumeric : " + alphaNumeric ); </script>
Output:
alphaNumeric : a,b,c,1,2,3 Join()
Javascript array join() method joins all the elements of an array into a string. Syntax:
Its syntax is as follows − array.join(separator); Example:
<script type="text/javascript">
var arr = new Array("First","Second","Third"); var str = arr.join(“&”);
document.write("str : " + str ); </script>
Output:
str : First & Second & Third pop()
Javascript array pop() method removes the last element from an array and returns that element.
Syntax:
Example:
<script type="text/javascript"> var numbers = [1, 4, 9]; var element = numbers.pop();
document.write("element is : " + element ); </script>
Output: element is: 9 push()
The Javascript Array Method push() is used to append the arguments at the end of the array, and returns the length of the array.
Syntax:
array.push(value,...); Example:
<script type="text/javascript">
var numbers = new Array(1, 4, 9); var length = numbers.push(10);
document.write("new numbers is : " + numbers ); </script>
Output: new numbers is : 1,4,9,10 Shift()
Javascript array shift()method removes the first element from an array and returns that element.
Syntax
Its syntax is as follows − array.shift(); Example:
<script type="text/javascript">
var element = [105, 1, 2, 3].shift();
document.write("Removed element is : " + element ); </script>
Unshift()
Javascript array unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
Syntax
Its syntax is as follows −
array.unshift( element1, ..., elementN ); Example:
<script type="text/javascript">
var arr = new Array(10,20,30,40); var length = arr.unshift(50);
document.write("Returned array is : " + arr );
document.write("<br /> Length of the array is : " + length ); </script>
Output:
Returned array is : 50,10,20,30,40 Length of the array is : 5
Sort()
Javascript array sort() method sorts the elements of an array. Syntax
Its syntax is as follows −
array.sort( compareFunction ); Example:
<script type="text/javascript">
var arr = new Array("orange", "mango", "banana", "sugar"); var sorted = arr.sort();
document.write("Returned string is : " + sorted ); </script>
Output: Returned array is : banana,mango,orange,sugar Reverse()
Javascript array reverse() mmethod reverses the element of an array. The first array element becomes the last and the last becomes the first.
Its syntax is as follows − array.reverse(); Example:
<script type="text/javascript"> var arr = [0, 1, 2, 3].reverse();
document.write("Reversed array is : " + arr ); </script>
Output: Reversed array is : 3,2,1,0 Slice()
Javascript array slice() method extracts a section of an array and returns a new array.
Syntax:
Its syntax is as follows −
array.slice( begin_index ,end_index ); Example:
<script type="text/javascript">
var arr = ["orange", "mango", "banana", "sugar", "tea"]; document.write("arr.slice( 1, 2) : " + arr.slice( 1, 2) ); document.write("<br />arr.slice( 1, 3) : " + arr.slice( 1, 3) ); </script>
Output
arr.slice( 1, 2) : mango
arr.slice( 1, 3) : mango,banana Splice()
Javascript array splice() method changes the content of an array, adding new elements while removing old elements.
Syntax:
Its syntax is as follows −
array.splice(start_index, howMany, [element1][, ..., elementN]); Example:
<script type="text/javascript">
document.write("After adding 1: " + arr ); </script>
Output: After adding 1: orange,mango,water,banana,sugar,tea
****************************************************************************** JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript function many times to reuse the code.
Advantage of JavaScript function
There are mainly two advantages of JavaScript functions.
1. Code reusability: We can call a function several times so it save coding.
2. Less coding: It makes our program compact. We don’t need to write many lines of code each time to perform a common task.
JavaScript Function Syntax
The syntax of declaring function is given below. function functionName([arg1, arg2, ...argN]) {
//code to be executed }
JavaScript Functions can have 0 or more arguments. JavaScript Function Example
Let’s see the simple example of function in JavaScript that does not has arguments. <html>
<body> <script>
function msg() {
alert("hello! this is message"); }
</script>
<input type="button" onclick="msg()" value="call function"/> </body>
******************************************************************************
Important Questions
1. Define Javascript and explain the structure of Javascript.
2. Explain the ways to place a javascript code in a HTML program. 3. Write about the data types in javascript.
4. Define Operator and explain different types of operators in javascript. 5. Explain about local and global variables in javascript.
6. Write about the branching control statements in javascript with example. 7. Explain about looping control statements in javascript with example. 8. Explain break and continue statements in javascript with example.
9. Define string and explain how to handle the strings in javascript with example. 10. Write about the Mathematical functions used in javascript with example. 11. Explain about arrays in javascript.