JavaScript Oddities and Secrets you need to know

JavaScript Oddities and Secrets you need to know

·

2 min read

In this post, I will cover some things that are cool and most of you're unaware of. Let' see them.


Null is an Object

Null is an object. Despite this, null is not considered as an instance of an object. This brings us back to sanity, because if null is the absence of value, then it obviously can't be an instance of anything. Hence, the following evaluates to false:

alert(typeof null); // alerts 'object'
alert(null instanceof Object); // evaluates false

NaN is a Number

NaN is not equal to anything. The only way to confirm that something is NaN is through the function isNaN().

alert(typeof NaN); // alerts 'Number'
alert(NaN === NaN); // evaluated false

Replace() can accept callback function

This is one of JavaScript's object keep secrets and it arrived in v1.3 Most usages of replace() looks something like this:

alert('10 13 21 48 52'.replace(/\d/g, '*')); 
// replace all numbers with *

This is the simple replacement: a string, an asterisk. But what if we wanted more control over how and when our replacements take place? What if we wanted to replace only the number under 3? This can't be achieved with ReGex alone. We need to jump into the callback function to evaluate each match.

alert('10 13 21 48 52'.replace(/\d/g, function(match) {
    return parseInt(match) < 3 ? '*' : match; 
})); ** *3 ** 48  5*

For every match made, JavaScript calls our callback function, passing the match as an argument.

Undefined can be defined

Strange as it might sound, undefined is not a reserved word in JavaScript, even though it has special meaning and is the only way to determine whether a variable is undefined.

(function() {
    var undefined = 'foo'; 
    alert(undefined, typeof undefined); // foo string
})();

An array with no keys == false(about truthy and false)

alert(new Array() == false); // evaluates true

In JavaScript, every non-boolean value has a built-in boolean flag that is called on when the value is asked to behave like a boolean. False, zero, null, undefined, empty strings and NaN all end up becoming false - not permanently, just for the given expression.

--

Thanks for Reading, If you like this post please comment😎.

Did you find this article valuable?

Support Rahul by becoming a sponsor. Any amount is appreciated!