Premium Javascript Course

JavaScript Data Types

JavaScript is a loosely-typed language, meaning variables can hold any type of data, and the type of data can change over time. Understanding JavaScript data types is essential for writing efficient and bug-free code.

Primitive Data Types

JavaScript has six primitive data types:

Example of Primitive Data Types


let name = "Alice"; // string
let age = 25; // number
let isActive = true; // boolean
let bigNumber = 12345678901234567890n; // bigint
let notAssigned; // undefined
let uniqueKey = Symbol("key"); // symbol
        

Reference Data Types

In addition to primitive types, JavaScript also supports reference data types, which are more complex data types:

Example of Reference Data Types


let person = { name: "Alice", age: 25 }; // object
let numbers = [1, 2, 3, 4, 5]; // array
let greet = function() { console.log("Hello, world!"); }; // function
        

Type Conversion

JavaScript provides several ways to convert between different data types. This process is called type casting or type conversion.

Implicit Type Conversion

JavaScript automatically converts data types when necessary, which is called implicit type conversion or coercion.


let result = "5" + 5; // string + number, implicit conversion to string
console.log(result); // Output: "55"

let sum = "5" - 2; // string - number, implicit conversion to number
console.log(sum); // Output: 3
        

Explicit Type Conversion

You can explicitly convert values to different types using various functions:

Examples of Explicit Type Conversion


let num = 123;
let str = String(num); // explicit conversion to string
console.log(str); // Output: "123"

let boolValue = Boolean(1); // explicit conversion to boolean
console.log(boolValue); // Output: true
        

Checking Data Types

You can check the type of a value using the typeof operator:


console.log(typeof "hello"); // Output: string
console.log(typeof 42); // Output: number
console.log(typeof true); // Output: boolean
console.log(typeof [1, 2, 3]); // Output: object
console.log(typeof { name: "Alice" }); // Output: object
console.log(typeof null); // Output: object (this is a known JavaScript quirk)
        

Best Practices for Working with Data Types

Conclusion

Understanding JavaScript's data types and how to manage them effectively is crucial for writing robust and error-free code. Whether you're working with primitive or reference data types, knowing how to perform type conversions and check types will help ensure that your code works as expected.