Saturday, August 21, 2021

JavaScript Objects

A JavaScript object is an entity having state and behaviour (properties and method). For example car, pen, bike, chair, glass, keyboard, monitor etc.

JavaScript is an object-based language. Everything is an object in JavaScript.

JavaScript is template based not class-based. Here, we don't create a class to get the object. But, we direct create objects.


Creating Objects in JavaScript

There are 3 ways to create objects.

  1. By object literal
  2. By creating an instance of Object directly (using the new keyword)
  3. By using an object constructor (using the new keyword)

1) JavaScript Object by object literal

The syntax of creating object using object literal is given below:

  1. object={property1:value1,property2:value2.....propertyN:valueN}  

As you can see, property and value is separated by : (colon).

Let’s see the simple example of creating object in JavaScript.

  1. <script>  
  2. emp={id:102,name:"Shyam Kumar",salary:40000}  
  3. document.write(emp.id+" "+emp.name+" "+emp.salary);  
  4. </script>  

Output of the above example

102 Shyam Kumar 40000

2) By creating instance of Object

The syntax of creating object directly is given below:

  1. var objectname=new Object();  

Here, a new keyword is used to create an object.

Let’s see the example of creating object directly.

  1. <script>  
  2. var emp=new Object();  
  3. emp.id=101;  
  4. emp.name="Ravi Malik";  
  5. emp.salary=50000;  
  6. document.write(emp.id+" "+emp.name+" "+emp.salary);  
  7. </script>  

Output of the above example

101 Ravi 50000

3) By using an Object constructor

Here, you need to create a function with arguments. Each argument value can be assigned to the current object by using this keyword.

This keyword refers to the current object.

The example of creating object by object constructor is given below.

  1. <script>  
  2. function emp(id,name,salary){  
  3. this.id=id;  
  4. this.name=name;  
  5. this.salary=salary;  
  6. }  
  7. e=new emp(103,"Vimal Jaiswal",30000);  
  8.   
  9. document.write(e.id+" "+e.name+" "+e.salary);  
  10. </script>  

Output of the above example

103 Vimal Jaiswal 30000

Defining method in JavaScript Object

We can define a method in the JavaScript object. But before defining the method, we need to add a property in the function with the same name as a method.

The example of defining method in object is given below.

  1. <script>  
  2. function emp(id,name,salary){  
  3. this.id=id;  
  4. this.name=name;  
  5. this.salary=salary;  
  6.   
  7. this.changeSalary=changeSalary;  
  8. function changeSalary(otherSalary){  
  9. this.salary=otherSalary;  
  10. }  
  11. }  
  12. e=new emp(103,"Sonoo Jaiswal",30000);  
  13. document.write(e.id+" "+e.name+" "+e.salary);  
  14. e.changeSalary(45000);  
  15. document.write("<br>"+e.id+" "+e.name+" "+e.salary);  
  16. </script>  

Output of the above example

103 Sonoo Jaiswal 30000
103 Sonoo Jaiswal 45000

JavaScript Array

JavaScript array is an object that represents a collection of similar types of elements.

There are 3 ways to construct an array in JavaScript

  1. By array literal
  2. By creating an instance of Array directly (using the new keyword)
  3. By using an Array constructor (using the new keyword)

1) JavaScript array literal

The syntax of creating array using array literal is given below:

  1. 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.

  1. <script>  
  2. var emp=["Sonoo","Vimal","Ratan"];  
  3. for (i=0;i<emp.length;i++){  
  4. document.write(emp[i] + "<br/>");  
  5. }  
  6. </script>  

The .length property returns the length of an array.

The output of the above example

Sonos
Vimal
Ratan

2) JavaScript Array directly (new keyword)

The syntax of creating an array directly is given below:

  1. var arrayname=new Array();  

Here, new keyword is used to create instance of array.

Let’s see the example of creating array directly.

  1. <script>  
  2. var i;  
  3. var emp = new Array();  
  4. emp[0] = "Arun";  
  5. emp[1] = "Varun";  
  6. emp[2] = "John";  
  7.   
  8. for (i=0;i<emp.length;i++){  
  9. document.write(emp[i] + "<br>");  
  10. }  
  11. </script>  

The output of the above example

Arun
Varun
John

3) JavaScript array constructor (new keyword)

Here, you need to create instances of the array by passing arguments in the constructor so that we don't have to provide value explicitly.

The example of creating object by array constructor is given below.

  1. <script>  
  2. var emp=new Array("Jai","Vijay","Smith");  
  3. for (i=0;i<emp.length;i++){  
  4. document.write(emp[i] + "<br>");  
  5. }  
  6. </script>  

The output of the above example

Jai
Vijay
Smith

JavaScript String

The JavaScript string is an object that represents a sequence of characters.

There are 2 ways to create a string in JavaScript

  1. By string literal
  2. By string object (using the 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:

  1. var stringname="string value";  

Let’s see the simple example of creating string literal.

  1. <script>  
  2. var str="This is string literal";  
  3. document.write(str);  
  4. </script>  

Output:

This is string literal

2) By string object (using the new keyword)

The syntax of creating a string object using a new keyword is given below:

  1. var stringname=new String("string literal");  

Here, new keyword is used to create instance of string.

Let’s see the example of creating string in JavaScript by new keyword.

  1. <script>  
  2. var stringname=new String("hello javascript string");  
  3. document.write(stringname);  
  4. </script>  

Output:

hello javascript string

JavaScript String Methods

Let's see the list of JavaScript string methods with examples.

  • charAt(index)
  • concat(str)
  • indexOf(str)
  • lastIndexOf(str)
  • toLowerCase()
  • toUpperCase()
  • slice(beginIndex, endIndex)
  • trim()

1) JavaScript String charAt(index) Method

The JavaScript String charAt() method returns the character at the given index.

  1. <script>  
  2. var str="javascript";  
  3. document.write(str.charAt(2));  
  4. </script>  

Output:

v

2) JavaScript String concat(str) Method

The JavaScript String Concat(str) method concatenates or joins two strings.

  1. <script>  
  2. var s1="javascript ";  
  3. var s2="concat example";  
  4. var s3=s1.concat(s2);  
  5. document.write(s3);  
  6. </script>  

Output:

javascript concat example

3) JavaScript String indexOf(str) Method

The JavaScript String indexOf(str) method returns the index position of the given string.

  1. <script>  
  2. var s1="javascript from javatpoint indexof";  
  3. var n=s1.indexOf("from");  
  4. document.write(n);  
  5. </script>  

Output:

11

4) JavaScript String lastIndexOf(str) Method

The JavaScript String lastIndexOf(str) method returns the last index position of the given string.

  1. <script>  
  2. var s1="javascript from javatpoint indexof";  
  3. var n=s1.lastIndexOf("java");  
  4. document.write(n);  
  5. </script>  

Output:

16

5) JavaScript String toLowerCase() Method

The JavaScript String toLowerCase() method returns the given string in lowercase letters.

  1. <script>  
  2. var s1="JavaScript toLowerCase Example";  
  3. var s2=s1.toLowerCase();  
  4. document.write(s2);  
  5. </script>  

Output:

javascript tolowercase example

6) JavaScript String toUpperCase() Method

The JavaScript String toUpperCase() method returns the given string in uppercase letters.

  1. <script>  
  2. var s1="JavaScript toUpperCase Example";  
  3. var s2=s1.toUpperCase();  
  4. document.write(s2);  
  5. </script>  

Output:

JAVASCRIPT TOUPPERCASE EXAMPLE

7) JavaScript String slice(beginIndex, endIndex) Method

The JavaScript String slice(beginIndex, endIndex) method returns the parts of string from given beginIndex to endIndex. In slice() method, beginIndex is inclusive and endIndex is exclusive.

  1. <script>  
  2. var s1="abcdefgh";  
  3. var s2=s1.slice(2,5);  
  4. document.write(s2);  
  5. </script>  

Output:

cde

8) JavaScript String trim() Method

The JavaScript String trim() method removes leading and trailing whitespaces from the string.

  1. <script>  
  2. var s1="     javascript trim    ";  
  3. var s2=s1.trim();  
  4. document.write(s2);  
  5. </script>  

Output:

javascript trim

JavaScript Date Object

The JavaScript date object can be used to get year, month and day. You can display a timer on the webpage by the help of JavaScript date object.

You can use different Date constructors to create a date object. It provides methods to get and set day, month, year, hour, minute and seconds.


Constructor

You can use 4 variants of the Date constructor to create a date object.

  1. Date()  
  2. Date(milliseconds)  
  3. Date(dateString)  
  4. Date(year, month, day, hours, minutes, seconds, milliseconds)  

JavaScript Date Methods

The important methods of date object are as follows:


JavaScript Date Example

Let's see the simple example to print date object. It prints date and time both.

  1. Current Date and Time: <span id="txt"></span>  
  2. <script>  
  3. var today=new Date();  
  4. document.getElementById('txt').innerHTML=today;  
  5. </script>  

Output:

Current Date and Time: Tue Sep 21 2021 02:44:30 GMT+0530 (India Standard Time)

JavaScript Current Time Example

Let's see the simple example to print current time of system.

  1. Current Time: <span id="txt"></span>  
  2. <script>  
  3. var today=new Date();  
  4. var h=today.getHours();  
  5. var m=today.getMinutes();  
  6. var s=today.getSeconds();  
  7. document.getElementById('txt').innerHTML=h+":"+m+":"+s;  
  8. </script>  

Output:

Current Time: 2:44:30

JavaScript Digital Clock Example

Let's see the simple example to display digital clock using JavaScript date object.

There are two ways to set interval in JavaScript: by setTimeout() or setInterval() method.

  1. Current Time: <span id="txt"></span>  
  2. <script>  
  3. window.onload=function(){getTime();}  
  4. function getTime(){  
  5. var today=new Date();  
  6. var h=today.getHours();  
  7. var m=today.getMinutes();  
  8. var s=today.getSeconds();  
  9. // add a zero in front of numbers<10  
  10. m=checkTime(m);  
  11. s=checkTime(s);  
  12. document.getElementById('txt').innerHTML=h+":"+m+":"+s;  
  13. setTimeout(function(){getTime()},1000);  
  14. }  
  15. //setInterval("getTime()",1000);//another way  
  16. function checkTime(i){  
  17. if (i<10){  
  18.   i="0" + i;  
  19.  }  
  20. return I;  
  21. }  
  22. </script>  

Output:

Current Time:

JavaScript Math Object

The JavaScript math object provides several constants and methods to perform the mathematical operation. Unlike date objects, it doesn't have constructors.

Math.sqrt(n)

The JavaScript math.sqrt(n) method returns the square root of the given number.

  1. Square Root of 17 is: <span id="p1"></span>    
  2. <script>    
  3. document.getElementById('p1').innerHTML=Math.sqrt(17);    
  4. </script>    

Output:

Square Root of 17 is: 4.123105625617661

Math.random()

The JavaScript math.random() method returns the random number between 0 to 1.

  1. Random Number is: <span id="p2"></span>    
  2. <script>    
  3. document.getElementById('p2').innerHTML=Math.random();    
  4. </script>   

Output:

Random Number is: 0.8532444867314739

Math.pow(m,n)

The JavaScript math.pow(m,n) method returns the m to the power of n that is mn.

  1. 3 to the power of 4 is: <span id="p3"></span>    
  2. <script>    
  3. document.getElementById('p3').innerHTML=Math.pow(3,4);    
  4. </script>    

Output:

3 to the power of 4 is: 81

Math.floor(n)

The JavaScript math.floor(n) method returns the lowest integer for the given number. For example 3 for 3.7, 5 for 5.9 etc.

  1. Floor of 4.6 is: <span id="p4"></span>    
  2. <script>    
  3. document.getElementById('p4').innerHTML=Math.floor(4.6);    
  4. </script>    

Output:

Floor of 4.6 is: 4

Math.ceil(n)

The JavaScript math.ceil(n) method returns the largest integer for the given number. For example 4 for 3.7, 6 for 5.9 etc.

  1. Ceil of 4.6 is: <span id="p5"></span>    
  2. <script>    
  3. document.getElementById('p5').innerHTML=Math.ceil(4.6);    
  4. </script>    

Output:

Ceil of 4.6 is: 5

Math.round(n)

The JavaScript math.round(n) method returns the rounded integer nearest for the given number. If the fractional part is equal or greater than 0.5, it goes to upper value 1 otherwise lower value 0. For example 4 for 3.7, 3 for 3.3, 6 for 5.9 etc.

  1. Round of 4.3 is: <span id="p6"></span><br>    
  2. Round of 4.7 is: <span id="p7"></span>    
  3. <script>    
  4. document.getElementById('p6').innerHTML=Math.round(4.3);   
  5. document.getElementById('p7').innerHTML=Math.round(4.7);    
  6. </script>    

Output:

Round of 4.3 is: 4
Round of 4.7 is: 5

Math.abs(n)

The JavaScript math.abs(n) method returns the absolute value for the given number. For example 4 for -4, 6.6 for -6.6 etc.

  1. Absolute value of -4 is: <span id="p8"></span>      
  2. <script>      
  3. document.getElementById('p8').innerHTML=Math.abs(-4);      
  4. </script>   

Output:

Absolute value of -4 is: 4

JavaScript Number Object

The JavaScript number object enables you to represent a numeric value. It may be integer or floating-point. JavaScript number object follows IEEE standard to represent the floating-point numbers.

With the help of the Number() constructor, you can create a number object in JavaScript. For example:

  1. var n=new Number(value);  

If the value can't be converted to a number, it returns NaN(Not a Number) that can be checked by isNaN() method.

You can direct assign a number to a variable also. For example:

  1. var x=102;//integer value  
  2. var y=102.7;//floating point value  
  3. var z=13e4;//exponent value, output: 130000  
  4. var n=new Number(16);//integer value by number object  

Output:

102 102.7 130000 16

JavaScript Number Constants

Let's see the list of JavaScript number constants with descriptions.

JavaScript Number Methods

Let's see the list of JavaScript number methods with descriptions.

JavaScript Boolean

JavaScript Boolean is an object that represents value in two states: true or false. You can create the JavaScript Boolean object by Boolean() constructor as given below.

  1. Boolean b=new Boolean(value);  

The default value of the JavaScript Boolean object is false.

JavaScript Boolean object provides properties and methods also.

JavaScript Boolean Properties

JavaScript Boolean Methods




No comments:

Post a Comment