Javascript – The Weird Parts

javascript-the-weird-parts.jpeg

JavaScript is a powerful and versatile programming language that has been widely adopted by developers around the world. However, as with any programming language, javascript possesses certain quirks and weird parts that can cause confusion and frustration for developers. One such example is the behavior of the built-in JavaScript functions and operators when dealing with certain values.

One of the most common examples of this is the isNaN() function, which is used to determine if a given value is not a number. However, when used in combination with the parseFloat() function, the result can be quite unexpected. For example, the following code returns true:

!isNaN(parseFloat('Infinity')) // true
This is because parseFloat('Infinity') returns Infinity, which is a valid number in JavaScript, and isNaN(Infinity) returns false. This means that the ! operator negates the result, resulting in true.

Another example of unexpected behavior is the typeof operator, which is used to determine the type of a given value. However, when used with certain values, the results can be quite surprising. For example, the following code returns true:

typeof NaN === 'number' // true
This is because NaN is a special value in JavaScript that represents “Not-A-Number”. However, it is also considered a number type, which can cause confusion for developers.

Another example of unexpected behavior is the typeof operator when used with the null value, which returns “object”:

typeof null === 'object' // true
This is because null was initially considered as an object by developers and it was intended to represent no value. but later it is considered as a separate type.

Additionally, the typeof operator when used with Math, returns “object”

typeof Math === 'object' // true
Even though Math is not a typical object, it is considered as an object.

Finally, when used with a class, typeof returns “function”

typeof MyClass === 'function' // true
This is because, in javascript, classes are functions and the class syntax is just a shorthand for declaring a constructor function.

Lastly, the typeof operator when used with the new Date() returns “object”

typeof new Date() === 'object' // true
Even though new Date() returns a date object, it is considered as an object in javascript.

In conclusion, JavaScript is a powerful and versatile programming language, but it has its share of quirks and unexpected behaviors. The examples mentioned in this article are just a few examples of how the built-in functions and operators can produce unexpected results when dealing with certain values. It’s important for developers to understand these behaviors and take them into account when writing code to avoid confusion and unexpected bugs.

Leave a comment

Your email address will not be published. Required fields are marked *