JavaScript — The dynamic weakly typed

A JavaScript variable can contain any type of data,

JavaScript is dynamically typed, this means that the type of a variable is defined by the type of its data, at runtime.

let a = 1; // a is a number

a = 'ok'; // a is now a string

Though, since it’s weakly typed, you can do “what ever you want” in your expression.

This means that you don’t need to inform the compiler how to convert your values, example :

let a = 1;

let b = "2";

let c = a + b; // "12" -> c is a string

c = a * b; // 2 -> c is a number

The ECMA specification describe how implementations should behave based on values types during an operation (additive, etc):

https://tc39.github.io/ecma262/#sec-additive-operators

This might look much simpler or cool than a * (int) b ,

however this weak typing can introduce some weird type conversion.

const sum = (a, b) => a + b;

sum(1, "2") // "12" -> ??!?!?!

That’s why sometimes you need to “force value type” to avoid runtime unexpected behaviours by using parseInt() or the + (unary operator) .

const sum = (a, b) => parseInt(a, 10) + parseInt(b, 10);

sum(1, "2") // 3 // Or

const sum = (a, b) => (+a) + (+b);

Then, how to evaluate a variable type in JavaScript ?