Java Script Intermediate
What is Array?
An array is a special type of variable, which allow to store and manipulate more than one value at a time. If you have a list of items (a list of numbers , for example), storing the number in single variables could look like this:
var n1= 233; var n2 = 455; var n3= 566;
What if you want to store 30 numbers , it is difficult to create and manage 30 variables. The solution is an array! An array can hold many values under a single name, and you can access the values by referring to an index number.
In case of JavaScript array index starts with zero and goes up to no of elements -1.
Creating Array in JavaScript?
To create array in JavaScript we use following syntax –
Syntax:
var array_name = [item1, item2, ...];
Example
var fruits = ["Mango","Apple","Orange"];
Access the Elements of an Array
You access an array element by referring to the index number. In JavaScript array index starts with 0. This statement accesses the value of the first element in fruits:
var name = fruits[0]; - get you mango.
var name1=fruits[1]; - get you apple.
e.g. input 10 integer numbers in array and display maximum number from it.
<html>
<head>
<title> even odd </title>
<script type="text/javascript">
var num =[];
//input data
for(var i=0;i<10;i++)
{
num[i]=parseInt(prompt("Enter No:"));
}
//max
var max=num[0];
for(var i=1;i<10;i++)
{
if(max<num[i])
max =num[i];
}
alert("Maximum is:"+ max);
</script>
</head>
<body>
</body>
</html>
Array Methods
pop() :- method is used to remove the last element from the array.
push(element) :- will add the element at the end of array.
shift() :- will remove the first element form the array and shift other elements to it’s lower index no.
length :- no of elements from the array.
splice : – can be used to add the multiple elements in array at specified index no by removing some elements.
fruits.splice(index,no of elements to remove, list of elements to add separated by ,)
fruits.splice(2, 0, "Lemon", "Kiwi");
will add lemon and kiwi to array from index position 2 and remove 0 elements.
You can also use the splice to remove the element from the array.
fruits.splice(0, 1);
It will remove one element at 0th index no.
concat() :- used to concat two or more arrays.
sort() :- will sort the array data in ascending order.
reverse() :- will reverse the array elements
e.g. array method example.
<html>
<head>
<title> select in javascript </title>
<script type="text/javascript">
var str =["apple","mango","banna","grapes"];
// document.write("Length:"+ str.length +"<br>");
// document.write("pop:"+ str.pop() +"<br>");
// document.write("pop:"+ str.pop() +"<br>");
// document.write("Push:"+ str.push("PineApple") +"<br>");
// document.write("Push:"+ str.push("Watermelon") +"<br>");
// str.shift();
// str.splice(2,0,"first","second","third");
str.splice(2,1);
for(var i=0;i<str.length;i++)
{
document.write(str[i] +"<br>");
}
var str1=["cricket","football","batmentan","games"];
var r =str.concat(str1);
document.write("<br>");
for(var i=0;i<r.length;i++)
{
document.write(r [i]+"<br>");
}
document.write(r.sort() +"<br>");
document.write(r.reverse());
</script>
</head>
<body>
</body>
</html>
Objects in JavaScript (Java script Object Notation – J SON)
JavaScript is object based programming language which whelp you to create object and the syntax used to create the object is called JSON. Object in JavaScript can contain the properties can be created as follows –
var objectname={"propertyname":value,propertyname:value,propertyname:value;}
To access the property we use
objectname.propertyname =value;
e.g. input empid, empname, salary , dept name from the user and store it in object and display it.
<html>
<head>
<title> Java Script </title>
<script type="text/javascript">
var e ={};
var eid =parseInt(prompt("Enter Emp ID:"));
var ename=prompt("Enter Emp Name:");
var dn=prompt("Enter Dept Name:");
var sal =prompt("Enter Salary :");
e ={"EmpID":eid,"EmpName":ename,"DeptName":dn,"Salary":sal};
alert(e.EmpID);
alert(e.EmpName);
alert(e.DeptName);
alert(e.Salary);
</script>
</head>
<body>
</body>
</html>
This keyword: – this keyword in JavaScript is used to refer or access the current object of the class.
Array of objects
You can also create array of object just like normal variable using following syntax.
var object=[{}];
It will create blank array
<html>
<head>
<title> Java Script </title>
<script type="text/javascript">
var prod=[
{"ProductID":121,"ProductName":"Mouse","Price":450,"MfgName":"Intex"},
{"ProductID":122,"ProductName":"Keyboard","Price":850,"MfgName":"Iball"},
{"ProductID":123,"ProductName":"HardDisk","Price":14450,"MfgName":"Segate"},
{"ProductID":124,"ProductName":"Printer","Price":45450,"MfgName":"Canon"},
{"ProductID":125,"ProductName":"Cabinate","Price":1450,"MfgName":"Circle"},
{"ProductID":126,"ProductName":"Monitor","Price":56450,"MfgName":"Monitor"},
{"ProductID":127,"ProductName":"Laptop","Price":51450,"MfgName":"IBM"},
];
for(var i=0;i<prod.length;i++)
{
alert(prod[i].ProductID);
alert(prod[i].ProductName);
alert(prod[i].Price);
alert(prod[i].MfgName);
}
</script>
</head>
<body>
</body>
</html>
Functions in JavaScript
A JavaScript function is a block of code to perform a particular task. A JavaScript function is executed when “something” invokes it (calls it). Java script support following two types of functions –
Named Functions
A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, …)
The code to be executed, by the function, is placed inside curly brackets: {}
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
You can also use return keyword to return some value from the function.You can call the function as follows –
functionname([parameters]);
e.g. function to just display hello.
<html>
<head>
<title> function </title>
<script type="text/javascript">
function SayHello()
{
alert("this is say hello used to demo!");
}
SayHello();
SayHello();
</script>
</head>
<body>
</body>
</html>
e.g. function to perform addition of two numbers –
<html>
<head>
<title> function </title>
<script type="text/JavaScript">
function addition(a,b)
{
// alert("Addition is:"+ (a+b));
return a+b;
}
var c=addition(20,30);
alert("Addition:"+ c);
c= addition(56,78);
alert("Addition is:"+ c);
</script>
</head>
<body>
</body>
</html>
Anonymous Functions
functions defined without name, stored in some variable and using that variable we can call that function –
<html>
<head>
<title> function </title>
<script type="text/javascript">
var doCube=function(a)
{
return a*a*a;
}
var r = doCube(10);
alert("Result is:"+ r);
r =doCube(20);
alert("Result is:" +r);
</script>
</head>
<body>
</body>
</html>
Event Handling
HTML events are “things” that happen to HTML elements.we can write JavaScript in response to these events.
An HTML event can be something the browser does, or something a user does like click , mouse move, finished loading , input changed etc. Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected.
HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.
With single quotes:
<element event='some JavaScript'>
With double quotes:
<element event="some JavaScript">
Here is a list of some common HTML events:
Event | Description |
---|---|
onchange | An HTML element has been changed |
onclick | The user clicks an HTML element |
onmouseover | The user moves the mouse over an HTML element |
onmouseout | The user moves the mouse away from an HTML element |
onkeydown | The user pushes a keyboard key |
onload | The browser has finished loading the page |
e.g. display hello alert on the click of button.
<html>
<head>
<title> function </title>
<script type="text/javascript">
function SayHello()
{
alert("Say Hello!");
}
</script>
</head>
<body>
<input type="button" value="click" onclick="SayHello()" />
<input type="text" onfocus="SayHello()" />
</body>
</html>