JavaScript Data Types
JavaScript has several data types that can be categorized into two groups: primitive and non-primitive.
Primitive Data Types
- String: Text data (e.g.,
"Hello",'World'). - Number: Numeric data (e.g.,
42,3.14). - Boolean: Logical values (
trueorfalse). - Undefined: A variable that has been declared but not assigned a value.
- Null: Represents an empty or non-existent value.
Non-Primitive Data Types
- Object: A collection of key-value pairs.
- Array: A list of values.
Example
let name = "Alice"; // String
let age = 30; // Number
let isStudent = true; // Boolean
let address; // Undefined
let emptyValue = null; // Null
Checking Data Types
You can check the type of a variable using the typeof operator:
let value = "Hello";
console.log(typeof value); // Output: string
Type Conversion
JavaScript allows you to convert data types:
let num = "42";
let convertedNum = Number(num); // Converts string to number
console.log(typeof convertedNum); // Output: number