Data Types

JavaScript has 8 data-types, 7 primitives and Object

alt

the 7 primitive types are immutable values.

They are Null, Undefined, Boolean, Number, BigInt, String, and Symbol


JavaScript uses Object wrapper classes, that are automatically used when operating with these primitive values. They expose functions that are very helpful for development

JS

Copy

let someString = "lars";
let someNumber = 12;

someString = someString.toUpperCase();
someNumber = someNumber.toExponential();

console.log(someString); // LARS
console.log(someNumber); // 1.2e+1

JavaScript is dynamically typed, which means a variable is not attached to a certain type, and can be reassigned any value.

JS

Copy

let someString = "lars";

someString = 12

console.log(typeof someString); // number

Type Coercion

JavaScript is also weakly typed, which means it'll try and convert a type to make an operation happen.

This is called type coercion, and can for example happen when trying to add a Number with a String

JS

Copy

let someNumber = 10;
let someString = "Lars"
let combined =  someString + someNumber;

console.log(typeof combined) // string
console.log(combined)        // Lars10

here the Number variable is converted to a string (coerced)

It's often not a good idea to rely on implicit type coercion.


Therefore it's recommended to use explicit conversions, and use the triple '===' comparision operator

JS

Copy

if (2 == "2") {
    console.log("Works, because '==' uses type coercion")
}

if (2 === "2") {
    console.log("Does not work, because it does not coerce the type.")
}
// Works, because '==' uses type coercion

As one can see from the code snippet above, the first check actually fires, because it'll convert the number to a string

this can lead to unexpected behaviour.