What is the difference between
typeof operator simply returns the type of value. The basic primitive type of the value. So, you can use the
instanceof operator matches the constructor of the provided object. So, when your value is of complex type consider using
On a side note. It is believed that
typeof operator performs better than
instanceof operator where both are applicable.
How to delete an element from an array while iterating over it?
Everyone knows to delete an element from an array you have to use
delete operator. Easy!
HA! tricked you.
Never do that.
delete just sets your deleted position to
undefined. If you want to delete an item from an array always use
But now, try doing it while you are iterating over an array. You are bound to hit an error at some point saying the position is
undefined. In case of a simple array, you will just get wrong answers. See below.
I want to remove all 2’s from the array.
Logically the above code is perfect. But, do you think it will give me my expected result? No!
This is because every time the item is spliced from the array the array is re-indexed. Simply put, your original value of
myarray.length does not match the new one. So, the loop does not even get a chance to check some of the elements.
To fix this, simply iterate in from the top. In reverse order.
0.1 + 0.2 === 0.3?
Sorry to burst the bubble, but the answer is
If you try this.
Which is a little greater than
0.3 in our problem.
Do you know what is
If you try to Google for this
!! operator you will get all sorts of results. But not one correct result. So, if you are trying to search for this expression, you have to be smart. Search for
This little experiment itself tells us that it not a very widely used expression. But, that does on do justice to its usefulness.
It basically forces to return the true boolean value of the provided expression.
So, you know
0 is a
It will return
false. But now, try this.
!! returns a true boolean representation of the expression provided.
You might ask why would I even do this if simple
0 == false works for me. Well, this comes handy when dealing with custom types.
To check if the object is present we simply do:
But, this restrains garbage collector from collecting that object even when it is no more needed. Because a reference to it is held in your code.
On the other hand, if you do:
Your code is not holding a reference to the
myobject. It just evaluates the true boolean value of it and it is not available for the garbage collector for the cleanup.
Please let me know what do you think of these questions and how many of them you already knew?