Data Types in JavaScript
What are Data Types?
Imagine you have boxes. You can put different things in them: apples, books, toys. Data types in JavaScript are like those boxes. They tell the computer what kind of information is stored inside.
Types of Data Types
Number:
- Purpose: Represents numerical values (like whole numbers and decimals).
- Examples: 10, 3.14, -5, Infinity, -Infinity, NaN (Not a Number).
String:
- Purpose: Represents text.
- Syntax: Enclosed in single quotes (‘) or double quotes (“).
- Examples: ‘Hello’, “JavaScript”, “123”, ” “(empty string).
Boolean:
- Purpose: Represents a true or false value.
- Value: true, false
Null:
- Purpose: Represents the intentional absence of a value.
- Value: null
Undefined:
- Purpose: Represents a variable that has been declared but hasn’t been assigned a value yet.
Object:
- Purpose: A collection of key-value pairs.
- Example:
let person = {
name:"Alice",
age: 30
};
Array:
- Purpose: An ordered list of values.
- Example: [1, 2, 3], [“apple”, “banana”, “orange”]
Why are Data Types Important?
- Correct Operations: JavaScript knows how to work with different types of data. For example, you can add numbers, but you can’t directly add a number to a string.
- Predictable Behavior: Understanding data types helps you write code that behaves as expected.
- Debugging: If your code isn’t working as you expect, checking the data types of your variables can help you find the problem.