Few tips on JavaScript – Part II

This blog is a continuation of my last posting.

Solve the pass by reference problem in JavaScript
Many of us has come across the pass by reference problem in JavaScript array. we have simply assign one array to another array and any modification in one array reflects both the arrays and we bang our head where it is got changed.

var myArray=["test","nice","great"];
var changedArray=myArray;
changedArray[1]="chnagedValue";
console.log(myArray);
console.log(changedArray);


Output
[ ‘test’, ‘chnagedValue’, ‘great’ ]
[ ‘test’, ‘chnagedValue’, ‘great’ ]

Description
The array element value has been changed in both the arrays. Because in JavaScript arrays are also objects. When we assign myArray to the changedArray both these arrays are referring to the same memory location. So any change in them will be reflected in both the arrays.

Solution
But if We do not want to change any element in the first array. We can solve this issue by using Pass by name, like we have to iterate every element in the array and assign it to a different array as follows.

changedArray[0]=myArray[0];
…….
changedArray[n]=myArray[n];

if the array containing lots of elements then it will take lot of time to assign each element value on by one.So we can avoid this by following line of code.

var changedArray=myArray.slice(0,myArray.length);
changedArray[1]="chnagedValue";
console.log(myArray);
console.log(changedArray);

Output
[ ‘test’, ‘nice’, ‘great’ ]
[ ‘test’, ‘chnagedValue’, ‘great’ ]

Object property can be blank and also it can be a random number

var myCar=new Object();
myCar["Model"]="test";
myCar[""]="BMW";
rand=Math.random();
myCar[rand]="Random number";
console.log(myCar);

Output
{ Model: ‘test’, ‘ ‘: ‘BMW’, ‘0.8432904118199855’: ‘Random number’ }

Description
An object property name can be a simple JavaScript string or anything that can be converted to string even if the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until run time).

we can access these properties as follows.

console.log(myCar[rand]);
console.log(myCar[“”]);

Output
Random number
BMW

Hope this helps !!

Written By: Debashrita Swain, Software Developer, Mindfire Solutions

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s