So, let’s dive in.
Save yourself from using inbuilt functions like
parseInt() when you want to convert string to an integer. Simple append
+ in front of the string and you will get the value as a number type.
Of course, if the string is not a number it will return
But, you get point, right?!
If you want to check whether an object is any of the following: null, undefined, 0, NaN, false, or “”
This simple trick saves you from writing long paragraph on the conditions to satisfy to execute certain block of code. Above
if block simply checks whether the object has any falsy values or not.
3. Get max and min from an array
You can use the usual
Math.min even on the arrays to get the max and min values, respectively.
Here’s how its done:
4. Logical AND operator’s awesomeness
The logical operators you have are pretty neat tools if you know how to use them. Let’s see some cool tricks you can do with them.
Suppose you want to execute a function, if a certain condition is met:
Anyone can write the above code.
The above statement will execute
doSomething() only when
foo == "abc" condition is met.
Let’s see what is happening here.
To understand why above statement works, you need to understand that when you use the
logical AND operator it checks the second operand only if first operand returns
If the first operand returns
false the whole expression is going to be
false. Hence, the second operand is not evaluated at all.
Therefore in the above example, to execute
foo == "abc" condition should be met.
5. Logical OR operator’s awesomeness
Similar to the above example, we can check the inverse using
logical OR operator.
So, if you want to write something like this:
You can display your ninja skills by writing:
The reason why above statement works is because in
logical OR operator, to evaluate the second operand the first operand should return
Which means to execute
foo == "abc" should return
foo != "abc" should return
Till then, do let me know what you think about these tips. Also, please let me know if you have some better one’s.