JavaScript Data Types
JavaScript data types define the kinds of values and the operations that can be performed on them. Understanding JavaScript data types is crucial for writing effective code. Data types in JavaScript can be divided into two main categories: Primitive Types and Reference Types.
Primitive Data Types
Primitive data types are the most basic data types. They are immutable and stored directly in stack memory. JavaScript has 7 primitive data types:
1. Number Type
The number type is used to represent both integers and floating-point numbers.
let integer = 42; // Integer
let float = 3.14159; // Floating-point number
let negative = -10; // Negative number
let scientific = 1.23e5; // Scientific notation
// Special number values
let infinity = Infinity; // Positive infinity
let negativeInfinity = -Infinity; // Negative infinity
let notANumber = NaN; // Not a Number
console.log(1 / 0); // Infinity
console.log("not a number" / 2); // NaN2. BigInt Type
BigInt is a numeric type that can represent arbitrarily large integers.
let bigNumber = 1234567890123456789012345678901234567890n;
let anotherBigNumber = BigInt("1234567890123456789012345678901234567890");
console.log(bigNumber + 1n); // Can perform operations3. String Type
The string type is used to represent text data, enclosed in single quotes, double quotes, or backticks.
let singleQuote = 'Single quote string';
let doubleQuote = "Double quote string";
let backtick = `Backtick string`;
// Strings can contain quotes
let message = "He said: 'Hello!'";
let anotherMessage = 'She said: "Goodbye!"';
// Template strings (using backticks)
let name = "John";
let greeting = `Hello, ${name}!`; // Insert variable using ${}
console.log(greeting); // Output: Hello, John!4. Boolean Type
The boolean type has only two values: true and false.
let isTrue = true;
let isFalse = false;
// Boolean values often come from comparison operations
let isGreater = 5 > 3; // true
let isEqual = 5 === 3; // false
// Used in conditional statements
if (isGreater) {
console.log("5 is greater than 3");
}5. Undefined Type
The undefined type has only one value: undefined. When a variable is declared but not assigned a value, its default value is undefined.
let emptyVariable;
console.log(emptyVariable); // undefined
let explicitUndefined = undefined;
console.log(explicitUndefined); // undefined6. Null Type
The null type also has only one value: null. It represents "no value" or "empty value".
let emptyValue = null;
console.log(emptyValue); // null
// null is often used to initialize variables, indicating that there's no value yet
let user = null; // Indicates no user data yet7. Symbol Type
Symbol is a unique, immutable data type, typically used as keys for object properties.
let sym1 = Symbol("description");
let sym2 = Symbol("description");
console.log(sym1 === sym2); // false, each Symbol is unique
// Symbols are often used as object property keys to avoid naming conflicts
let id = Symbol("id");
let user = {
name: "John",
[id]: 123
};Reference Data Types
Reference types are stored in heap memory, and variables store references (addresses) pointing to the actual data. The main reference type in JavaScript is Object.
Object Type
An object is a collection of key-value pairs that can contain multiple data types and functions.
let person = {
name: "John",
age: 25,
isStudent: true,
hobbies: ["reading", "swimming", "coding"],
address: {
city: "New York",
street: "Main Street"
},
greet: function() {
return "Hello, I'm " + this.name;
}
};
console.log(person.name); // Access property
console.log(person["age"]); // Another way to access property
console.log(person.greet()); // Call methodArray Type
An array is a special type of object used to store ordered collections of data.
let fruits = ["apple", "banana", "orange"];
let numbers = [1, 2, 3, 4, 5];
let mixed = [1, "string", true, {name: "John"}];
console.log(fruits[0]); // Access array element
console.log(fruits.length); // Get array length
// Array methods
fruits.push("grape"); // Add element
fruits.pop(); // Remove last elementFunction Type
Functions are also objects. In JavaScript, functions are first-class citizens.
// Function declaration
function add(a, b) {
return a + b;
}
// Function expression
let multiply = function(a, b) {
return a * b;
};
// Arrow function
let subtract = (a, b) => a - b;
console.log(add(5, 3)); // 8
console.log(multiply(4, 2)); // 8
console.log(subtract(10, 3)); // 7Date Type
The Date object is used to handle dates and times.
let now = new Date(); // Current date and time
let specificDate = new Date("2024-01-01"); // Specific date
let customDate = new Date(2024, 0, 1, 12, 0, 0); // Year, month, day, hour, minute, second
console.log(now.getFullYear()); // Get year
console.log(now.getMonth()); // Get month (0-11)
console.log(now.getDate()); // Get dayType Detection
JavaScript provides several methods to detect data types:
typeof Operator
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 historical bug in JavaScript)
console.log(typeof Symbol("id")); // "symbol"
console.log(typeof BigInt(123)); // "bigint"
console.log(typeof {}); // "object"
console.log(typeof []); // "object"
console.log(typeof function(){}); // "function"Array.isArray() Method
console.log(Array.isArray([])); // true
console.log(Array.isArray({})); // falseinstanceof Operator
let arr = [];
let obj = {};
console.log(arr instanceof Array); // true
console.log(obj instanceof Object); // true
console.log(arr instanceof Object); // true (arrays are also objects)Type Conversion
JavaScript automatically performs type conversion in certain situations:
Implicit Conversion
console.log("5" + 3); // "53" (string concatenation)
console.log("5" - 3); // 2 (numeric operation)
console.log(true + 1); // 2 (true converts to 1)
console.log(false + 1); // 1 (false converts to 0)Explicit Conversion
// Convert to string
let num = 123;
let str = String(num); // "123"
let str2 = num.toString(); // "123"
// Convert to number
let strNum = "123";
let num1 = Number(strNum); // 123
let num2 = parseInt("123.45"); // 123
let num3 = parseFloat("123.45"); // 123.45
// Convert to boolean
let truthy = Boolean("hello"); // true
let falsy = Boolean(""); // false
let falsy2 = Boolean(0); // false
let falsy3 = Boolean(null); // falseCharacteristics of Data Types
Immutability of Primitive Types
let str = "hello";
str[0] = "H"; // This won't change the string
console.log(str); // Still "hello"
// To change a string, you need to reassign it
str = "Hello";
console.log(str); // "Hello"Mutability of Reference Types
let arr = [1, 2, 3];
arr[0] = 10; // Can directly modify array elements
console.log(arr); // [10, 2, 3]
let obj = {name: "John"};
obj.name = "Jane"; // Can directly modify object properties
console.log(obj); // {name: "Jane"}Pass by Value vs Pass by Reference
// Primitive types are passed by value
let a = 10;
let b = a;
b = 20;
console.log(a); // 10 (a is unchanged)
// Reference types are passed by reference
let arr1 = [1, 2, 3];
let arr2 = arr1;
arr2[0] = 10;
console.log(arr1); // [10, 2, 3] (arr1 is also changed)Summary
JavaScript data types include:
Primitive Types (7 types):
- Number
- BigInt
- String
- Boolean
- Undefined
- Null
- Symbol
Reference Types (mainly Object):
- Object
- Array
- Function
- Date
- RegExp, etc.
Understanding these data types and their characteristics is very important for writing high-quality JavaScript code. In the next chapter, we will learn about JavaScript's basic structure.