Intro To JavaScript Ojects
Intro To JavaScript Ojects
Intro To JavaScript Ojects
JavaScript Objects
• JS Object
• JS Array
• JS String
• JS Date
• JS Math
• JS Number
• JS Boolean
JavaScript Objects
• A javaScript object is an entity having state and behavior
(properties and method).
• For example: car, pen, bike, chair, glass, keyboard, monitor etc.
<html>
<body>
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
</body>
</html>
3) By using an Object constructor
• Here, you need to create function with arguments.
• Each argument value can be assigned in the current object by using this
keyword.
• The this keyword refers to the current object.
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>
JAVASCRIPT ARRAY
JavaScript Array
• An array is a special variable, which can hold more than
one value, at a time.
• If you have a list of items (a list of car names, for example),
storing the cars in single variables could look like this:
• cars1=“Honda";
cars2=“Suzuki";
cars3="BMW";
• An array can hold all your variable values under a single
name.
• Can access the values by referring to the array name.
• Each element in the array has its own ID so that it can be
easily accessed.
JavaScript Array
• JavaScript array is an object that represents a collection of
similar type of elements.
• There are 3 ways to construct array in JavaScript
• By array literal
• By creating instance of Array directly (using new keyword)
• By using an Array constructor (using new keyword)
1) JavaScript array literal
• The syntax of creating array using array literal is given below:
• var arrayname=[value1,value2.....valueN];
• As you can see, values are contained inside [ ] and separated by ,
(comma).
• Let's see the simple example of creating and using array in
JavaScript.
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
2) JavaScript Array directly (new keyword)
• The syntax of creating array directly is given below:
• var arrayname=new Array();
• Here, new keyword is used to create instance of array.
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
3) JavaScript array constructor (new keyword)
document.write(myCars[0]);
will result in the following output:
Honda
JavaScript Array Methods
Methods Description
Output:
Dad,Mom,Son,Daughter
Array Functions (Continue..)
Output:
Output:
Banana,Orange,Apple,Mango
Banana+Orange+Apple+Mango
Banana and Orange and Apple and Mango
Array Functions (Continue..)
Output:
Mango
Banana,Orange,Apple
Apple
Banana,Orange
Array Functions (Continue..)
Output:
5
7
Banana,Orange,Apple,Mango,Kiwi,Lemon,Pineapple
Reverse the order of the elements in an array - reverse()
Output:
Mango,Apple,Orange,Banana
Remove the first element of an array - shift()
Output:
Banana
Orange,Apple,Mango
Orange
Apple,Mango
Add new elements to the beginning of an array - unshift()
Output:
undefined
undefined
Lemon,Pineapple,Grapes,Banana,Orange,Apple,Mango
Output:
Apple,Banana,Mango,Orange
Convert an array to a string - toString()
Output:
Banana,Orange,Apple,Mango
<!DOCTYPE html>
<html>
<body>
<script>
var arr=["Monday","Tuesday","Saturday","Sunday","Thursday","Friday"];
var result=arr.splice(2,4);
document.writeln("Updated array: "+arr+"<br>");
document.writeln("Removed element: "+result);
</script>
</body>
</html>
The For/In Loop
• The JavaScript for/in statement loops through the properties
of an Object:
• Syntax
• for (key in object) {
// code block to be executed
}
• Example
• var person = {fname:"John", lname:"Doe", age:25};
var text = "";
var x;
for (x in person) {
text += person[x];
}
Example Explained
• The for in loop iterates over a person object
• Each iteration returns a key (x)
• The key is used to access the value of the key
• The value of the key is person[x]
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var txt = "";
var person = {fname:"John", lname:"Doe", age:25};
var x;
for (x in person) {
txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For In</h2>
<p id="demo"></p>
<script>
var txt = "";
var numbers = [45, 4, 9, 16, 25];
var x;
for (x in numbers) {
txt += numbers[x] + "<br>";
}
document.getElementById("demo").innerHTML = txt;
</script>
</body>
</html>
Array Properties
Property Description
• Syntax:
MAX_VALUE
The largest possible value a number in JavaScript can have
1.7976931348623157E+308
MIN_VALUE
The smallest possible value a number in JavaScript can have
5E-324
<p id="demo"></p>
<script>
var x = Number.MAX_VALUE;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
MAX_VALUE
<html>
<head>
<script type="text/javascript">
function showValue()
{ var val = Number.MAX_VALUE;
alert("Value of Number.MAX_VALUE : " + val );
}
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="showValue();" />
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Number Object Properties</h2>
<script>
document.write("Max value of number "+Number.MAX_VALUE+"<br>");
Method Description
toPrecision() Defines how many total digits (including digits to the left and right of the
decimal) to display of a number.
val = num.toExponential(4);
document.write("num.toExponential(4) is : " + val );
document.write("<br />");
val = num.toExponential(2);
document.write("num.toExponential(2) is : " + val);
document.write("<br />");
val = 77.1234.toExponential();
document.write("77.1234.toExponential()is : " + val );
document.write("<br />");
val = 77.1234.toExponential();
document.write("77 .toExponential() is : " + val);
</script></body></html>
<!DOCTYPE html> <html> <body> <script>
var a="50";
var b="51.25"
document.writeln(Number.isInteger(1)+"<BR>");
document.writeln(Number.isFinite(Infinity));
document.writeln("<BR>"+Number.parseFloat(a)+"<br>");
document.writeln(Number.parseFloat(b)+"<br>");
document.writeln(Number.parseInt(a)+"<br>");
document.writeln(Number.parseInt(b)+"<br>");
var c=989721;
document.writeln(c.toExponential(2)+"<br>");
document.writeln(c.toExponential(4)+"<br>");
var d=98.9721;
document.writeln(d.toFixed()+"<br>");
document.writeln(d.toFixed(2));
document.writeln(c.toString()+"<br>");
document.writeln(d.toString()+"<br>");
document.writeln(d.toPrecision());
document.writeln(d.toPrecision(2));
document.writeln(d.toPrecision(3));
</script> </body> </html>
JS STRING OBJECT
String Object
• The String object let's you work with a series of characters and wraps
Javascript's string primitive data type with a number of helper methods.
Property Description
constructor Returns a reference to the String function that created the object.
length Returns the length of the string.
The prototype property allows you to add properties and methods
prototype
to an object.
<html>
<head>
<title>JavaScript String constructor property</title>
</head>
<body>
<script type="text/javascript">
var str = new String( "This is string" );
document.write("str.constructor is:" + str.constructor);
</script>
</body>
</html>
<html>
<head>
<title>JavaScript String length Property</title>
</head>
<body>
<script type="text/javascript">
var str = new String( "This is string" );
document.write("str.length is:" + str.length);
</script>
</body>
</html>
String Methods
Method Description
concat() Combines the text of two strings and returns a new string.
Used to find a match between a regular expression and a string, and
replace()
to replace the matched substring with a new substring.
Executes the search for a match between a regular expression and a
search()
specified string.
split() Splits a String object into an array of strings by separating the string
into substrings.
var re = /apples/gi;
var str = "Apples are round, and apples are juicy.";
var newstr = str.replace(re, "oranges");
document.write(newstr );
</script>
</body>
</html>
<html>
<head>
<title>JavaScript String search() Method</title>
</head>
<body>
<script type="text/javascript">
var re = /apples/gi;
var str = "Apples are round, and apples are juicy.";
if ( str.search(re) == -1 ){
document.write("Does not contain Apples" );
}else{
document.write("Contains Apples" );
}
</script>
</body>
</html>
<html>
<head>
<title>JavaScript String toUpperCase() Method</title>
</head>
<body>
<script type="text/javascript">
document.write(str.toUpperCase( ));
</script>
</body>
</html>
<html>
<head>
<title>JavaScript String toString() Method</title>
</head>
<body>
<script type="text/javascript">
document.write(str.toString( ));
</script>
</body>
</html>
JAVASCRIPT MATH OBJECT
Math Object
• The math object provides you properties and methods for
mathematical constants and functions.
• All 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 Math.PI and you call the sine
function as Math.sin(x), where x is the method's argument.
• Syntax:
• Here is the simple syntax to call properties and methods of Math.
• var pi_val = Math.PI;
• var sine_val = Math.sin(30);
Math Properties:
Property Description
Euler's constant and the base of natural logarithms, approximately
E
2.718.
LN2 Natural logarithm of 2, approximately 0.693.
LN10 Natural logarithm of 10, approximately 2.302.
LOG2E Base 2 logarithm of E, approximately 1.442.
LOG10E Base 10 logarithm of E, approximately 0.434.
Ratio of the circumference of a circle to its diameter, approximately
PI
3.14159.
</script>
</body>
</html>
JavaScript Math Methods
Methods Description
abs() It returns the absolute value of the given number.
log() It returns natural logarithm of a number.
max() It returns maximum value of the given numbers.
min() It returns minimum value of the given numbers.
pow() It returns value of base to the power of exponent.
ceil() It returns a smallest integer value, greater than or equal to
the given number.
cos() It returns the cosine of the given number.
floor() It returns largest integer value, lower than or equal to the
given number.
exp() It returns the exponential form of the given number.
round() It returns closest integer value of the given number.
sin() It returns the sine of the given number.
<html> <head> <title>JavaScript Math exp() Method</title> </head> <body>
<script type="text/javascript">
var value = Math.exp(1);
document.write("First Test Value : " + value );
var value = Math.exp(30);
document.write("<br />Second Test Value : " + value );
var value = Math.floor(30.9);
document.write("<br />Second Test Value : " + value );
var value = Math.floor(-2.9);
document.write("<br />Third Test Value : " + value );
var value = Math.max(10, 20, -1, 100);
document.write("First Test Value : " + value );
var value = Math.min(10, 20, -1, 100);
document.write("First Test Value : " + value );
var value = Math.log(10); document.write("First Test Value : " + value );
var value = Math.random( );
document.write("First Test Value : " + value );
var value = Math.round( 20.7 );
document.write("<br />Second Test Value : " + value );
var value = Math.round( 20.3 );
document.write("<br />Third Test Value : " + value );
• Date objects are created with the new Date( ) as shown below.
• Syntax:
• Here are different variant of Date() constructor:
• new Date( )
• new Date(milliseconds)
• new Date(datestring)
• new Date(year,month,date[,hour,minute,second,millisecond ])
Date Methods:
Method Description
Date() Returns today's date and time
Returns the day of the month for the specified date according to
getDate()
local time.
Returns the day of the week for the specified date according to local
getDay()
time.
getFullYear() Returns the year of the specified date according to local time.
getHours() Returns the hour in the specified date according to local time.
Returns the milliseconds in the specified date according to local
getMilliseconds()
time.
getMinutes() Returns the minutes in the specified date according to local time.
getMonth() Returns the month in the specified date according to local time.
getSeconds() Returns the seconds in the specified date according to local time.
getTime() Returns the numeric value of the specified date as the number of
milliseconds since January 1, 1970, 00:00:00 UTC.
<html>
<head>
<title>JavaScript Date Method</title>
</head>
<body>
<script type="text/javascript">
var dt = Date();
document.write("Date and Time : " + dt );
</script>
</body>
</html>
<html>
<head>
<title>JavaScript getDate Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date("December 25, 1995 23:15:00");
document.write("getDate() : " + dt.getDate() );
</script>
</body>
</html>
<html>
<head>
<title>JavaScript getDay Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date("December 25, 1995
23:15:00");
document.write("getDay() : " + dt.getDay() );
</script>
</body>
</html>
<html>
<head>
<title>JavaScript getFullYear Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date("December 25, 1995 23:15:00");
document.write("getFullYear() : " + dt.getFullYear() );
document.write("getTime() : " + dt.getTime() );
document.write("getMilliseconds() : " + dt.getMilliseconds() );
document.write("getMinutes() : " + dt.getMinutes() );
document.write("getHours() : " + dt.getHours() );
</script>
</body>
</html>
JAVASCRIPT BOOLEAN OBJECT
The Boolean Object
• The Boolean object represents two values, either "true" or "false".
• If value parameter is omitted or is 0, -0, null, false, NaN, undefined, or the
empty string (""), the object has an initial value of false.
• Syntax:
• var val = new Boolean(value);
Boolean Properties
Property Description
constructor Returns a reference to the Boolean function that created the
object.
prototype The prototype property allows you to add properties and
methods to an object.
Constructor
<html>
<head>
<title>JavaScript constructor() Method</title>
</head>
<body>
<script type="text/javascript">
var bool = new Boolean( );
document.write("bool.constructor() is:"+bool.constructor);
</script>
</body>
</html>
Prototype
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
function book(title, author)
{ this.title = title; this.author = author; }
</script> </head> <body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
book.prototype.price = null;
myBook.price = 100;
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script> </body></html>
Boolean Methods
Method Description
Expression Description
Expression Description
p+ It matches any string containing one or more p's.
p* It matches any string containing zero or more p's.
p? It matches any string containing at most one p.
p{N} It matches any string containing a sequence of N p's
p{2,3} It matches any string containing a sequence of two or three p's.
p{2, } It matches any string containing a sequence of at least two p's.
p$ It matches any string with p at the end of it.
^p It matches any string with p at the beginning of it.
• Examples
Expression Description
[^a-zA-Z] It matches any string not containing any of the characters ranging
from a through z and A through Z.
Modifier Description
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
g Performs a global match that is, find all matches rather than stopping
after the first match.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Visit W3Schools";
var patt1 = /w3schools/i;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
}
</script></body></html>
<!DOCTYPE html>
<html>
<body>
<p>Click the button to do a multiline search for "is" at the beginning of each
line in a string.</p>
<p id="demo"></p>
<script>
function myFunction() {
var str = "\nIs th\nis it?";
var patt1 = /^is/m;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
}
</script></body></html>
<html>
<body>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Is this all there is?";
var patt1 = /is/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
RegExp Properties
Property Description