Here, I’m going to discuss few concepts of JavaScript which are well aware to everyone but there are some loop holes which users are not aware of. The main focus of this post is to discuss and write a better code.
First, we discuss about for in
problem.
Let’s take this code:
for (name in object) {
if(Object.hasOwnProperty(name)) {
--- (do something)
}
}
If you closely look at this code, this can fail if the object has a hasOwnProperty
property. And it has to be noted that hasOwnProperty
is a method but not an operator.
So, how to resolve this..?? Here is the fix:
for (name in object) {
if (Object.prototype.hasOwnProperty.call(object, name)) {
--- (do something)
}
}
Second, let’s discuss about another important topic. Arrays
* Arrays, unlike Objects, have a special length property and it is always 1 larger than the highest integer subscript. And it allows use of the traditional for
statement.
for (i = 0; i < a.length; i += 1) {
--- (do something)
}
And here is the key point. Do not use for in
with arrays and the reason is for in
doesn’t guarantee the value in correct sequence. And if we want to append one more item in the array, here is the general procedure:
var myArray = ['a', 'b', 'c', 'd'];
myArray[myArray.length] = 'e';
And here is the another key point.
** Do not use dot notation with arrays because it gets confused with the decimal points. So better use brackets.
Now, deleting elements from the array:
This is the general way of deleting array elements –
var myArray = ['a', 'b', 'c', 'd'];
delete myArray[1];
//and here is the output: ['a', undefined, 'c', 'd']
And here is the another key point to remember:
*** DO not use delete
for deleting elements of the array because, as you have seen in the above code, the output array has a hole in the numbering of the elements.
And what’s the fix..? Well, better use splice
method instead. And here is the code:
myArray.splice(1, 1);
//And here is the output: ['a', 'c', 'd']
In the coming posts, we will discuss more about the topics where generally there is a chance of committing mistakes with general approach.
-By
Uma Maheswar
Helical It Solution