Data Types in JavaScript
- JavaScript is a dynamically typed language, meaning the type of a variable is determined at runtime.
-
Number: Represents both integer and floating-point numbers.
- Examples:
42,-7.5,0.001 - Special values:
Infinity,-Infinity,NaN(Not a Number)
- Examples:
-
String: Represents a sequence of characters, enclosed in single (
'), double ("), or backticks (```) for template literals.- Examples:
"hello",'world',`Hi, ${name}`
- Examples:
-
Boolean: Represents a logical value, either
trueorfalse.- Used in conditional statements and logic operations.
-
Undefined: A variable that has been declared but not assigned a value.
- Example:
let x;(x isundefined)
- Example:
-
Null: Represents the intentional absence of any value.
- Example:
let y = null;
- Example:
-
Symbol: A unique and immutable value, often used as object property keys (introduced in ES6).
- Example:
const sym = Symbol('description');
- Example:
-
BigInt: Represents large integers with arbitrary precision (introduced in ES2020).
- Example:
12345678901234567890n(note thensuffix)
- Example:
- Object: A collection of key-value pairs.
- Example:
const obj = { name: "Alex", age: 30 }; - Includes special types like:
- Arrays: Ordered lists of values.
- Example:
const arr = [1, 2, 3];
- Example:
- Functions: Reusable blocks of code.
- Example:
function greet() { return "Hello"; }
- Example:
-
- Dates, RegExp, etc.
- Example:
const date = new Date();(Date object) - Example:
const regex = /abc/;(Regular expression object) - Example:
const regex = new RegExp('abc');(Regular expression object)
- Arrays: Ordered lists of values.
- Example:
To check the type of a variable, you can use the typeof operator or the instanceof operator.