JavaScript - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

JavaScript Objects

JavaScript Objects

shape Introduction

Normally, JavaScript Objects are involved in every object-oriented programming language. JavaScript is no exception to objects.

shape Description

JavaScript is a Object Oriented Programming Language and object is a special kind of data. If a language is said to be Object-oriented language, it should satisfy four basic conditions, such as:
  • Inheritance: Inheritance is the process of creating a new class with the properties and characteristics of an existing class.
  • Polymorphism: Polymorphism is defined as the capability of different object types responding to the functions with the same name.
  • Encapsulation: Encapsulation is used to hide the internal representation of an object from the end user.
  • Abstraction: Abstraction is the process of showing the essential features and hiding the implementation details to the end user.

shape Examples

Consider an example,
var car = { volor:”blue”, height: 5, weight: 150 };
In the above example, all the details about the car are wrapped by giving var keyword only once. But while using standalone variables, var has to be mentioned when describing each specification of car.

JavaScript Objects Properties

shape Description

Variables inside an object are called as properties. Objects in real-life have multiple properties and all the properties will be stored inside an object. JavaScript Objects properties can be of primitive or abstract data types.

shape Syntax

object_name.property_name;
In the above syntax, dot( . ) symbol is used to access the object properties. While declaring a object, each property is separated by a comma( , ).
car.height;

shape Examples

[html] <script type="text/javascript"> var txt="Hello World!"; document.write(txt.length); //object.property_name </script> [/html] Output: 12 The spaces and symbols are included while counting the length.

Object Methods

shape Description

Methods are the actions that are performed by an object. Methods and Functions are not the same. A Function is a group of statements and a method combines with JavaScript Objects. This can be done by placing the dot separator( . ) between the object name and method name. The method action will be enclosed within parenthesis.

shape Syntax

object_name.method_name("statement");

shape Examples

The basic example is given below.
Document.write(“Splessons JavaScript Tutorial”);
In the above example, document is the object i.e. a web page has properties like square shape, blue color, four sides, etc. and write is the method that writes the text onto the web page object. Another example is as shown below. [html] <script type="text/javascript"> var txt="HEllo World!"; document.write(txt.toUpperCase()); </script> [/html] Output: HELLO WORLD! All the letters are changed to upper case.

Creating own objects

shape Description

JavaScript Objects can be created in two ways. By using constructor function and new operator: new operator creates an instance of object and uses constructor function that contains the blue-print of an object. For example, [c] //constructor function person function person(name,age) { //blue-print of objects this.name = name; this.age = age; } //Object creation using new var john = new person("John",25); var taylor = new person("Taylor",27); [/c] By using Object Initializers: When compared to constructor function, objects can be created faster with Object initializers. It pushes the object creation in one line, for example: [html] <!Doctype html> <html> <head> <title>JavaScript Tutorials</title> <script type="text/javascript"> john = { name: "John Swift", age: 25}; serena = {name:"Serena", age: 20}; </script> </head> <body> <script type="text/javascript"> document.write(john.name + " and " + serena.name + " are friends.Even if " + john.name + " has age " + john.age); </script> </body> </html> [/html] Output: John Swift and Serena are friends, even if John Swift has 25 years.

Object Types

Number Object

shape Description

Primitive data types are also treated as JavaScript Objects. A number object can be used while working with numerical values. There is only single type of number in JavaScript. It does not define types like short, long, integers, etc. These numbers use IEEE 754 standard and stores all numbers as double precision floating point format. JavaScript stores numbers in 64 bits. The numbers will be stored from 0 to 51, exponents from 52 to 62 and sign bit will be stored in 63. The precision of number without a period or exponent notation are stored up to 15 digits. To create a number, a variable with var keyword has to be created and a value has to be stored in it.
  • Decimal value: A number with a normal value can be as follows.
    Var b=25;
  • Octal number: JavaScript can convert the octal value to decimal value. A number with octal value(a number with 8 digits from 0-7) can be as follows.
    var b=012; //contains the decimal value 10
  • Hexadecimal number: Hexadecimal value can be created using 0x and can be as follows.
    var myHex1=0xF; //contains decimal value 15
  • Floating point numbers: These are indictaed by placing the numbers after decimal point. 
    var d=2.6; var e=.6; // valid but not recommended var f=3.; // considered as 3 only var g=5.0; //considered as 5 only var f=6e5; // the output will be 60000.Large/small numbers can use e to represent. var h=2e-4; // the output will be 0.0002
  • IsFinite(): IsFinite() function will give the result in the form of boolean. If the number is finite, the result will be  true, else the result will be false.
    var num1=2*Number.MAX_VALUE; //inifinite number var test=isFinite(num1); //false
  • NaN: The full form of NaN is Not a Number and will be resulted if the result is not a number.
    var num2="Orange"/5;

shape Example

Below example shows numbers and its types. [html] <!DOCTYPE html> <html> <head> <title> variables test</title>; <h2> Welcome to Splessons</h2>; </head> <body> <script type="text/javascript"> //decimal value var a=5; document.write("<br>Your number is ", a); //Octal value var b=012; document.write("<br><br>Octal number is", b); //Hexadecimal value var c=0xF; document.write("<br><br>Hexadecimal number is", c); //Floating point values var d=2.6; document.write("<br><br>Float point is",d); var e=.6; document.write("<br>Float point is",e); var f=3.; document.write("<br>Float point is",f); var g=5.0; document.write("<br>Float point is",g); var h=6e5; document.write("<br>Float point is",h); var i=2e-4; document.write("<br>Float point is",i); //calculating sum of two floating points var sum=d+g; document.write("<br><br>The sum is ",sum); //isInfinite() function and the range var num1=2*Number.MAX_VALUE; var res=isFinite(num1); document.write("<br><br>The number is infinite and hence result is ",res); //NaN var num2="Orange"/5; document.write("", num2); </script> </body> </html>[/html] Output : 

Boolean Object

shape Description

Boolean object is used to test the conditions and has only two values true and false. Any value in JavaScript can be converted to boolean using Boolean() function.
var a; var res=Boolean(a); //a doesn't have any value and hence undefined var a=null; var res=Boolean(a); //output is false since null coverts to false var a=""; var res=Boolean(a); //output is false since empty string converts to false var a=0; var res=Boolean(a); //output is false since 0 converts to false var a="splessons"; var res=Boolean(a); //output is true since a has meaning value

shape Example

Below is an example of boolean object. [html] <!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var b1 = Boolean(50); var b2 = Boolean(3.14); var b3 = Boolean(-10); var b4 = Boolean("Hi"); var b5 = Boolean('false'); var b6 = Boolean(1 + 7 + 3.14); document.getElementById("demo").innerHTML = "50 is " + b1 + "<br>" + "3.14 is " + b2 + "<br>" + "-10 is " + b3 + "<br>" + "Any (not empty) string is " + b4 + "<br>" + "Even the string 'false' is " + b5 + "<br>" + "Any expression (except zero) is " + b6; </script> </body> </html>[/html] Output:

Array Object

shape Description

An array is a variable that contains more values. Otherwise, array can be defined as a sequential group of variables containing the same data-type. All these variables are stored in continuous memory location. An array must be declared before using it in the program.

shape Syntax

Creating an array is similar to creating JavaScript Objects. It can be done in two ways. The syntax for Array Literal is as follows.
var array-name = [item1, item2, ...];
The syntax for new Array() is as follows.
var array_name = new Array(“element1,element2,element3,….elementX”);
Array elements can be strings or integers. Before specifying the array elements, it is better to specify the size of an array.

shape Example-1

Creating an Array using literal is easy.
var people = ["Tommy" , "Sammy" , "Murray" , "Andy" , "Mike"];
Array Literal allows you to create the number of required elements. To retrieve any value, one needs to follow the below syntax.
document.write(people[3]);
The output will be "Andy". Array Literal can insert any element whenever required. For Example,
people[7] = "John";

shape Example-2

By giving all the array elements at a time.
var people =  new Array(“Tommy”, ”Sammy” , “Murray” , “Andy” , “Mike”);
Five elements are created. The index of array starts from 0. In the above example, Tommy is the 0th element (or) people[0]=Tommy Sammy is the 1th element (or) people[1]=Sammy Murray is the 2th element (or) people[2]=Murray Andy is the 3th element (or) people[3]=Andy Mike is the 4th element (or) people[4]=Mike If a user wants to print the 4th element of "people" array,  the following syntax should be used.
document.write(people[3]);
The output will be "Andy".

shape Example-3

Giving the size of an array and later pushing the elements sequentially. For example,
var people = new Array(3); //3 is the size of the array people[0] = "Tommy"; people[1] = "Sammy"; people[2] = "Murray";
If a user wants to print the 2nd element of "people" array, the syntax is as follows.
document.write(people[1]);
The output will be "Sammy".

String Object

shape Description

Text in JavaScript is represented in String format, which is a sequence of characters. To store the string value in a variable, it must be enclosed within double quotes (" ") or single quotes(' '). But, the quotes should be consistent. If started with single quote, it should end with the single quote only.
var a="splessons"; //valid var b="splessons"; //valid var a='splessons"; //invalid var b="splessons'; //invalid
  • String Escape Sequences : To encode and include some special characters in Strings, escape sequences are used.
    Literal Function Example Output
    \n New line var msg="Hello\nWorld"; Hello World
    \t Tab space var msg="Hello\tWorld"; Hello World
    \b Backspace var msg="Hello\bWorld"; HelloWorld
    \r Carriage return var msg="Hello\rWorld"; Hello World
    \\ Backslash with string var msg="Hello\\World"; Hello\World
    \' Single quote on screen var msg="\'Hello\' World"; 'Hello' World
    \" Double quote on screen var msg="\"Hello\"World"; "Hello"World
    \x Hexadecimal value depending on ASCII value var msg="\x41 book"; A book
    \unnnn Unicode characters on screen var msg="\u03a3 World"; Σ World
  • String Conversion: The values of other data types can be converted to strings. A string can be concatenated with other string using +.
    var a="Hello"; a=a+"World"; // outputs is Hello World
    Conversion to string using toString().
    var a=15; var b=a.toString(); //b contains string 15 var c=a.tostring(2); //prints 1111(binary value)

shape Example

Below is an example for String object. [html] <!DOCTYPE html> <html> <body> <p>Never create strings as objects.</p> <p>JavaScript objects cannot be compared.</p> <p id="demo"></p> <script> var x = new String("MIKE"); // x is an object var y = new String("MIKE"); // y is an object document.getElementById("demo").innerHTML = (x==y); </script> </body> </html>[/html] Output:

Math Object

shape Description

Math Object is used to perform the mathematical operations using properties and methods. Math object's static methods and properties can be called without creating an object. For example,
var pi_value = Math.PI;

shape Examples

[html] <!Doctype html> <html> <head> <title>JavaScript Tutorials</title> <script type="text/javascript"> //Printing pi and e values using math object document.write("<br>",Math.PI); document.write("<br>",Math.E); //Finding square root of a number var n = prompt("</br>Enter a number", ""); var answer = Math.sqrt(n); document.write("The square root of " + n + " is " + answer); </script> </head> <body> <script type="text/javascript"> </script> </body> </html> [/html] Output [c]3.141592653589793 2.718281828459045 The square root of 144 is 12[/c]

Math Methods

shape Methods

Method Description
abs(x) Absolute value of x
acos(x) arccosine of x
asin(x) arcsine of x
atan(x) arctangent of x
ceil(x) Rounds upwards to nearest integer
cos() cosine of x
exp() exponent of x
floor() Rounds downward to nearest integer
sqrt(x) Finds square root of x
random() Random number between 0 and 1
exp() exponent of x
pow(x,y) Returns value of x to the power of y
max() Returns maximum value
min() Returns minimum value

Date Object

shape Introduction

Date object deals with JavaScript dates and times. To create Date Objects, Date() constructor should be used. There are many ways to initiate a date. Mostly used initiations are: All dates are calculated in milliseconds from Midnight, January 1,1970 and is called as Co-ordinated Universal Time(UTC) that is used by scientific community to keep the exact time. These dates can be represented as a string such as Wed Apr 21 2016 02:25:12 GMT-0700 or a number such as 651561618445615.

shape Example

The following example shows the current date and time using new Date() constructor. [html] <!DOCTYPE html> <html> <body> <p id="demo"></p> <script> //Creating a date object var d = new Date(); document.getElementById("demo").innerHTML = d; </script> </body> </html> [/html] Output: The below example shows specified time and date. [html] <!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var d = new Date("June 7, 2012 12:20:00"); document.getElementById("demo").innerHTML = d; </script> </body> </html> [/html] Output: The below example shows the usage of new Date(7 numbers) by creating a new date object with the specified date and time. [html] <!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var d = new Date(94,5,7,6,12,15,0); document.getElementById("demo").innerHTML = d; </script> </body> </html> [/html] Output:

Summary

shape Key Points

  • JavaScript is a Object-oriented language.
  • Properties refer to variables inside the objects.
  • JavaScript Objects actions are called as Methods.
  • JavaScript Objects creation can be done using constructor function and initializers.
  • Array Literal and new Array() are the two ways of array creation.
  • Math object performs mathematical operations

shape Programming Tips

  • JavaScript Objects can be used if the names of elements are strings.
  • Arrays can be used if the names of elements are numbers.
  • Avoid using new Array() constructor as it complicates the code while inserting any new value.