All you need to know about Data Types in JavaScript

All you need to know about Data Types in JavaScript

In the world of programming, each language has its set of built-in data types. This article dives into the data structures that power JavaScript, and explains how you can use the typeof operator to check variable data types.

What is Dynamic and Weakly typed

In JavaScript dynamic type variables can be used to hold the different data types.

// Dynamic type example
let anything;
console.log(typeof(anything)); // Output: "undefined"
let anything = 23;
console.log(typeof(anything)); // Output: "number"
let anything = "JavaScript";
console.log(typeof(anything)); // Output: "string"

JavaScript is known for being a weakly-typed language, which means that it permits implicit type conversion in situations where different types are used in an operation, rather than generating type errors.

// Weakly typed example
let first = 1;
let second = first + "2";
console.log(second); // Output: 12
console.log(typeof(second)) // Output: "string"

When adding a number and a string, JavaScript will treat the number as a string.

Typetypeof return value
String"string"
Number"number"
Bigint"bigint"
Boolean"boolean"
Undefined"undefined"
Null"object"
Symbol"symbol"
Object"object"
const name = "John"; // typeof(name): "string"
const age = "23";    // typeof(age): "number"
const bigNumber = 999999999999999; // typeof(bigNumber): "bigint"
const isMarried = false; // typeof(isMarried): "boolean"
const init; // typeof(init): "null"
const symbol = Symbol(); // typeof(symbol): "symbol"
const obj = {name: name, age: age}; // typeof(obj): "object"

The object data type contains:

The typeof object, array and date returns "object" in JavaScript.

An Object

// Object
const obj = {name: "John", age: "23"};
console.log(typeof(obj)); // Output: "object"

An Array

// Array
const arr = ["John", "Doe"];
console.log(typeof(arr)); // Output: "object"

A Date

// Date
const myDate = new Date();
console.log(typeof(myDate)); // Output: "object"