Custom Search

Object Manipulation in Javascript

Object manipulation in JavaScript refers to accessing the objects properties and methods at runtime to perform certain functionality. JavaScript uses “for…in” and “With” statements to manipulate objects.



The for…in statement iterates a specified object for all the properties. For every properties the object has JavaScript executes the series of statements specified by the user.

Syntax:

for (variable in object)
{
  statements
}

Example:

<script type="text/javascript">
   var x;
   var employee = new Object();
   employee.name = "John";
   employee.designation = "Software Engineer";
   employee.gender = "Male";
   for (x in employee)
   {
      document.write(x + "---" + employee[x] + "<br />");
   }
</script>

Output
name—John
designation—Software Engineer
gender—Male

Example Explanation:
Here i am creating an custom object “employee”. It has 3 properties name, designation and gender. Now i am looping to the employee object and all the details of employee object gets stored in variable x. Now here it creates an Associative Array of the Properties and its values. To know more on Associative Array check out Associative Array in JavaScript.

The with statementt allows you to iterates to the default object for a set of statements.

Syntax:

with (object)
{
  statements
}

Example:

<script type="text/javascript">
   var a, x, y;
   var r=10
   with (Math)
   {
      a = PI * r * r;
      x = r * cos(PI);
      y = r * sin(PI/2);
   }
</script>

Explanation of the Example
Here i am loading the Math Object of JavaScript inside the With Statement. So now if i want to access the methods of the Math Object i can now directly access it with typing the method name.

Similar Posts

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.

Comments

No comments yet.

Leave a comment

(required)

(required)