DEV Community

Cover image for Decoding Weird JavaScript Behaviour
Bhavy Ladani
Bhavy Ladani

Posted on

Decoding Weird JavaScript Behaviour

History

JavaScript was created by Brendan Eich in 1995 while he was working at Netscape.

The initial version of JavaScript was developed in just 10 days in May 1995.

Browsers primarily understand and interpret three core languages for web development: HTML, CSS & JavaScript (not even TypeScript πŸ™‚).

JavaScript is a versatile programming language used both on the client side and increasingly on the server side (Node JS).

He is also the founder of two famous browsers: Mozilla Firefox and Brave.

Type Coercion

One of the most common sources of weird behaviour in JavaScript is type coercion.

Coercion in simple terms is the process of automatically converting values from one type to another type.

This is one of the reasons why β€œtype” is important.

Type-Coercion

Floating Point Numbers

Floating-point numbers are used to represent decimal numbers in JavaScript.

They have limited precision due to their fixed bit-size (64 bits in JS).

Solutions:

  • Use a library like Decimal.js for precise calculations.
  • Use the toFixed() method to round floating-point numbers to a certain number of decimal places.

Floating-Point-Numbers

Equality

JavaScript has two equality operators right now: == and ===.

The == operator checks for equality regardless of type, while the === operator checks for equality and type.

To avoid these unexpected results, you should always use the === operator when comparing values.

Equality

undefined vs. null

Undefined: It represents a variable that has been declared but not assigned a value.

Null: It represents an intentional absence of any object value.

The == operator treats undefined and null as equal, but the === operator does not.

Undefined-null

NaN

NaN stands for "Not a Number"

It is a special value that represents an invalid numerical value.

The isNaN() function in JavaScript is used to check if a value is NaN

In PHP, you have the is_nan() function to check if a value is NaN.

nan

That's it for this article. I hope you must have learnt something new from this article or may be now you know the reason behind the weird behaviour of JavaScript. I will also make part 2 of this very soon. So stay tuned. Thank you.

Top comments (0)