JavaScript Data Types

JavaScript Data Types

JavaScript Data Types

In JavaScript, data types define the type of value a variable can hold. JavaScript is dynamically typed, meaning a variable can hold different types of values at different times.

1️⃣ Primitive Data Types (Immutable & Stored by Value)

JavaScript has 7 primitive data types:

Data TypeExampleDescription
Numberlet x = 10;Stores integers & floating-point numbers.
Stringlet name = "Alice";Text enclosed in quotes (" " or ' ' or ```````).
Booleanlet isReady = true;true or false values.
Undefinedlet y;A variable declared but not assigned a value.
Nulllet z = null;Represents "nothing" or an empty value.
BigIntlet bigNum = 12345678901234567890n;Used for very large numbers.
Symbollet sym = Symbol("id");Unique identifiers (mostly for objects).

🔹 Example

let age = 25; // Number let username = "John"; // String let isLoggedIn = false; // Boolean let notAssigned; // Undefined let emptyValue = null; // Null let bigNumber = 12345678901234567890n; // BigInt let uniqueId = Symbol("id"); // Symbol

2️⃣ Non-Primitive (Reference) Data Types

These types store references to objects in memory.

Data TypeExampleDescription
Objectlet person = {name: "John", age: 30};Key-value pairs.
Arraylet fruits = ["apple", "banana", "cherry"];Ordered list of values.
Functionfunction greet() { return "Hello"; }A block of code that can be executed later.

🔹 Example

let person = { name: "Alice", age: 25 }; // Object let numbers = [1, 2, 3, 4]; // Array function sayHello() { console.log("Hello!"); } // Function

3️⃣ typeof Operator (Checking Data Types)

You can check a variable's data type using typeof.

console.log(typeof 42); // "number" console.log(typeof "Hello"); // "string" console.log(typeof true); // "boolean" console.log(typeof undefined); // "undefined" console.log(typeof null); // "object" (This is a known JavaScript bug!) console.log(typeof Symbol("id")); // "symbol" console.log(typeof { key: "value" }); // "object" console.log(typeof [1, 2, 3]); // "object" (Arrays are objects) console.log(typeof function() {}); // "function"

4️⃣ Special Cases

null is an object (typeof null returns "object"). This is a long-standing JavaScript bug.
Arrays are also objects, but they have additional properties.
Functions are objects with executable code.

🎯 Summary

Primitive types: Number, String, Boolean, Undefined, Null, BigInt, Symbol
Non-primitive types: Object, Array, Function
✅ Use typeof to check a variable's type
Objects and arrays are stored as references in memory

🚀 Now you're ready to handle data types like a pro! Let me know if you need more details. 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close