Some Javascript Tips and Tricks

Hi all,

Please find some Javascript tricks and tips :

Get the max or the min in an array of numbers

I think it’s an efficient way to find out minimum and maximum value from numeric array

var  numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411]; 
var maxInNumbers = Math.max.apply(Math, numbers); 
var minInNumbers = Math.min.apply(Math, numbers);

Strange Floating point problems

0.1 + 0.2 === 0.3 // is false 
0.1 + 0.2 == 0.3 // is also false

I’m not aware about this strange floating point issue, even though I’m using javascript since last 5-6 years.
But why does this happen? 0.1 +0.2 is equal to 0.30000000000000004. What you need to know is that all JavaScript numbers are floating points represented internally in 64 bit binary according to the IEEE 754 standard. For more explanation, take a look to this blog post.

Different ways to Check the properties of an object

In JavaScript, we can check weather a property is present on an object, in different ways.

if ('undefined' !== typeof obj['prop']) { /* do something */ }

if ('prop' in obj) { /* do something */ }

if (obj.hasOwnProperty('prop')) { /* do something */ }

From among all ways, I think most efficient way is 1st one. Please find speed test here. This page will answer the burning question, “Which is faster?”

Avoid Negative arguments for splice Array Function

In below code, my from variable have value ‘-1’ and I’m passing it to splice function which is still return me [5]. So, make sure that the arguments passed to splice are not negative.

var numbersArray = [1,2,3,4,5]; 
var from = numbersArray.indexOf("foo") ;  // from is equal to -1 
numbersArray.splice(from,2);    // will return [5]
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