JavaScript Basic Data Types: The Fundamental Building Blocks of Data
Open your toolbox and you'll find various tools—screwdrivers, wrenches, hammers, rulers. Each tool has specific purposes, and using the right tool makes work efficient. JavaScript's data types are like these tools, with different types of data having different uses and characteristics.
Data Types Overview
JavaScript has two main categories of data types:
- Primitive Types: Simple, immutable values
- Reference Types: Complex, mutable objects
This article focuses on basic data types. JavaScript has 7 basic data types:
- Number (Numbers)
- String (Text)
- Boolean (True/False values)
- Null (Empty values)
- Undefined (Undefined values)
- Symbol (Symbols, ES6)
- BigInt (Big integers, ES2020)
// Use typeof operator to check data types
console.log(typeof 42); // "number"
console.log(typeof "hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof Symbol()); // "symbol"
console.log(typeof 123n); // "bigint"
console.log(typeof null); // "object" (this is a historical bug!)Number Type—The World of Numbers
In JavaScript, all numbers are of type Number, without distinguishing between integers and floating-point numbers. This is like a universal calculator that can handle various numerical operations.
Number Representation Methods
// Integers
let age = 25;
let score = 100;
// Floating-point numbers (decimals)
let price = 19.99;
let temperature = -15.5;
// Scientific notation
let bigNumber = 1.5e6; // 1500000
let smallNumber = 2.5e-3; // 0.0025
// Different number systems
let decimal = 255; // Decimal
let binary = 0b11111111; // Binary (prefix 0b)
let octal = 0o377; // Octal (prefix 0o)
let hex = 0xff; // Hexadecimal (prefix 0x)
console.log(binary, octal, hex); // 255 255 255 (all converted to decimal)Special Numeric Values
JavaScript's Number type has several special values:
// Infinity: Infinity
console.log(1 / 0); // Infinity
console.log(-1 / 0); // -Infinity
console.log(Infinity > 1000000); // true
// NaN: Not a Number
console.log(0 / 0); // NaN
console.log("hello" * 2); // NaN
console.log(Math.sqrt(-1)); // NaN
// Check for NaN
console.log(isNaN(NaN)); // true
console.log(isNaN("hello")); // true
console.log(Number.isNaN(NaN)); // true (more strict)
console.log(Number.isNaN("hello")); // false (more strict)
// NaN's special property: it's not equal to any value, including itself!
console.log(NaN === NaN); // false
console.log(NaN == NaN); // falseNumber Precision Issues
Due to computers using binary storage, floating-point arithmetic may have precision issues. This is a common problem in all programming languages, not unique to JavaScript.
// Precision issue examples
console.log(0.1 + 0.2); // 0.30000000000000004 (not 0.3!)
console.log(0.1 + 0.2 === 0.3); // false
// Solution 1: Use toFixed()
let result = (0.1 + 0.2).toFixed(2);
console.log(result); // "0.30" (note: returns string)
console.log(+result); // 0.3 (convert back to number)
// Solution 2: Convert to integers first
let sum = (0.1 * 10 + 0.2 * 10) / 10;
console.log(sum); // 0.3
// Solution 3: Use Number.EPSILON for comparison
function almostEqual(a, b) {
return Math.abs(a - b) < Number.EPSILON;
}
console.log(almostEqual(0.1 + 0.2, 0.3)); // trueNumber Range
// Maximum and minimum safe integers
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
console.log(Number.MIN_SAFE_INTEGER); // -9007199254740991
// Check if it's a safe integer
console.log(Number.isSafeInteger(9007199254740991)); // true
console.log(Number.isSafeInteger(9007199254740992)); // false
// Maximum and minimum values (including floating-point)
console.log(Number.MAX_VALUE); // 1.7976931348623157e+308
console.log(Number.MIN_VALUE); // 5e-324String Type—The Art of Text
Strings are used to represent text data, like words written on paper. In JavaScript, strings can be enclosed in single quotes, double quotes, or backticks.
String Creation
// Single quotes
let name1 = "Alice";
// Double quotes
let name2 = "Bob";
// Backticks (template strings, ES6)
let name3 = `Charlie`;
// Three methods are completely equivalent (for simple strings)
console.log(name1, name2, name3); // Alice Bob CharlieSpecial String Characters
// Escape characters
let path = "C:\\Users\\Desktop\\file.txt"; // Backslashes need escaping
let quote = 'He said, "Hello!"'; // Quotes need escaping
let single = "It's a nice day."; // Single quotes within single quotes need escaping
// Common escape characters
let newline = "First line\nSecond line"; // \n newline
let tab = "Column1\tColumn2"; // \t tab
let backspace = "Hello\b"; // \b backspace
let unicode = "\u4F60\u597D"; // \uXXXX Unicode character
console.log(unicode); // "你好"
console.log(newline);
// First line
// Second lineTemplate Literals
Template literals are a powerful feature introduced in ES6, enclosed in backticks, allowing easy embedding of variables and expressions.
let userName = "Emma";
let age = 28;
// Traditional concatenation (cumbersome)
let greeting1 = "Hello, " + userName + "! You are " + age + " years old.";
// Template literals (concise)
let greeting2 = `Hello, ${userName}! You are ${age} years old.`;
console.log(greeting1);
console.log(greeting2);
// Both output: Hello, Emma! You are 28 years old.
// Can embed expressions
let price = 100;
let quantity = 3;
let message = `Total: $${price * quantity}`;
console.log(message); // Total: $300
// Can call functions
function getGreeting() {
return "Good morning";
}
let welcome = `${getGreeting()}, ${userName}!`;
console.log(welcome); // Good morning, Emma!
// Multi-line strings
let multiline = `
This is a
multi-line
string.
`;
console.log(multiline);String Properties and Methods
let text = "JavaScript";
// Length property
console.log(text.length); // 10
// Access characters
console.log(text[0]); // "J"
console.log(text.charAt(0)); // "J"
console.log(text.charAt(4)); // "S"
// Strings are immutable
text[0] = "j"; // Invalid! Strings cannot be modified
console.log(text); // Still "JavaScript"
// To change a string, you must create a new string
let newText = "j" + text.slice(1);
console.log(newText); // "javaScript"Boolean Type—The World of True and False
The Boolean type has only two values: true and false. It's like a switch with only "on" and "off" states.
let isActive = true;
let hasPermission = false;
console.log(typeof isActive); // "boolean"
// Comparison operators return Boolean values
console.log(5 > 3); // true
console.log(10 === 10); // true
console.log(7 < 2); // false
// Logical operators
let a = true;
let b = false;
console.log(a && b); // false (AND operation)
console.log(a || b); // true (OR operation)
console.log(!a); // false (NOT operation)Truthy and Falsy Values
In JavaScript, all values can be converted to Boolean. Certain values are considered false in Boolean contexts, called falsy values; other values are considered true, called truthy values.
// JavaScript has only 6 falsy values
Boolean(false); // false
Boolean(0); // false
Boolean(""); // false (empty string)
Boolean(null); // false
Boolean(undefined); // false
Boolean(NaN); // false
// All other values are truthy
Boolean(true); // true
Boolean(1); // true
Boolean("hello"); // true
Boolean(" "); // true (space is also a character)
Boolean([]); // true (empty array)
Boolean({}); // true (empty object)
Boolean(function () {}); // true
// Practical application
let username = "";
if (username) {
console.log("Welcome, " + username);
} else {
console.log("Please log in"); // This will execute because "" is falsy
}Null Type—Intentional Empty
null represents "intentionally set to empty," like an empty box that you know is intentionally left empty.
let result = null; // Explicitly means "no value"
console.log(typeof null); // "object" (this is a JavaScript historical bug!)
// Practical use cases
let selectedUser = null; // Currently no user selected
function findUser(id) {
// Search for user...
if (notFound) {
return null; // Explicitly return "not found"
}
return user;
}
// Check for null
if (selectedUser === null) {
console.log("No user selected");
}Undefined Type—The Undefined State
undefined means "not yet assigned," the default value when a variable is declared but not yet initialized.
let uninitializedVar;
console.log(uninitializedVar); // undefined
console.log(typeof uninitializedVar); // "undefined"
// Different scenarios for undefined
// 1. Declared but not assigned
let x;
console.log(x); // undefined
// 2. Accessing non-existent object properties
let person = { name: "Oliver" };
console.log(person.age); // undefined
// 3. Function has no return value
function noReturn() {
// No return statement
}
console.log(noReturn()); // undefined
// 4. Function parameter not provided
function greet(name) {
console.log(name);
}
greet(); // undefinedNull vs Undefined
These two are easily confused, but they have clear differences:
// undefined: variable declared but not assigned
let a;
console.log(a); // undefined
// null: explicitly assigned as "empty"
let b = null;
console.log(b); // null
// Type checking
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (historical bug)
// Comparison
console.log(undefined == null); // true (values are equal)
console.log(undefined === null); // false (types are different)
// Practical application principles
let config; // undefined: not initialized
let userProfile = null; // null: intentionally set to empty, meaning "no user yet"Symbol Type—Unique Identifiers
Symbol is a new type introduced in ES6, used to create unique identifiers. Each Symbol is unique, even if the description is the same.
// Create Symbol
let sym1 = Symbol();
let sym2 = Symbol();
console.log(sym1 === sym2); // false (each one is unique)
// Symbol with description
let id1 = Symbol("id");
let id2 = Symbol("id");
console.log(id1 === id2); // false (same description but still different Symbols)
console.log(id1.description); // "id"
// Use cases: unique property names for objects
let user = {
name: "Sophia",
age: 30,
};
let uniqueID = Symbol("id");
user[uniqueID] = 12345;
console.log(user[uniqueID]); // 12345
console.log(user); // { name: "Sophia", age: 30, Symbol(id): 12345 }
// Symbol properties don't appear in regular iterations
for (let key in user) {
console.log(key); // Only outputs "name" and "age"
}
// Need special methods to access
console.log(Object.getOwnPropertySymbols(user)); // [Symbol(id)]Global Symbol Registry
// Symbol.for() creates or retrieves global Symbols
let globalSym1 = Symbol.for("app.id");
let globalSym2 = Symbol.for("app.id");
console.log(globalSym1 === globalSym2); // true (same Symbol)
// Symbol.keyFor() gets the key of a global Symbol
console.log(Symbol.keyFor(globalSym1)); // "app.id"
// Regular Symbols are not in the global registry
let localSym = Symbol("local");
console.log(Symbol.keyFor(localSym)); // undefinedBigInt Type—Extra Large Integers
BigInt is a type introduced in ES2020 for representing arbitrary-precision integers, breaking the integer limits of the Number type.
// Create BigInt: add n after the number
let bigInt1 = 123456789012345678901234567890n;
let bigInt2 = BigInt("987654321098765432109876543210");
console.log(typeof bigInt1); // "bigint"
// Number type limitations
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
console.log(9007199254740992); // 9007199254740992 (already imprecise)
console.log(9007199254740993); // 9007199254740992 (wrong!)
// BigInt has no limitations
console.log(9007199254740993n); // 9007199254740993n (precise)
// Operations
let big1 = 100n;
let big2 = 200n;
console.log(big1 + big2); // 300n
console.log(big1 * big2); // 20000n
console.log(big2 / big1); // 2n (division result rounds down)
// BigInt and Number cannot be mixed in operations
let num = 10;
let big = 20n;
console.log(big + num); // TypeError: Cannot mix BigInt and other types
// Need explicit conversion
console.log(big + BigInt(num)); // 30n
console.log(Number(big) + num); // 30BigInt Limitations
// Cannot use Math object methods
let big = 25n;
console.log(Math.sqrt(big)); // TypeError
// Cannot compare with Numbers (works with ==, not with ===)
console.log(10n == 10); // true
console.log(10n === 10); // false
// Cannot be used with JSON.stringify
let data = { value: 100n };
console.log(JSON.stringify(data)); // TypeError: Do not know how to serialize a BigIntType Checking Methods
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 Symbol()); // "symbol"
console.log(typeof 123n); // "bigint"
console.log(typeof null); // "object" (bug!)
console.log(typeof {}); // "object"
console.log(typeof []); // "object"
console.log(typeof function () {}); // "function"More Accurate Type Checking
// Check for null
let value = null;
console.log(value === null); // true
// Check for arrays
console.log(Array.isArray([])); // true
console.log(Array.isArray({})); // false
// Object.prototype.toString.call()
function getType(value) {
return Object.prototype.toString.call(value).slice(8, -1);
}
console.log(getType(123)); // "Number"
console.log(getType("hello")); // "String"
console.log(getType(true)); // "Boolean"
console.log(getType(null)); // "Null"
console.log(getType(undefined)); // "Undefined"
console.log(getType([])); // "Array"
console.log(getType({})); // "Object"Summary
Basic data types are the foundation of JavaScript programming. Understanding their characteristics is crucial for writing correct code.
Key Points Review:
- JavaScript has 7 basic data types: Number, String, Boolean, Null, Undefined, Symbol, BigInt
- Number: All number types,注意precision issues and special values (NaN, Infinity)
- String: Text data, template strings are recommended
- Boolean: true/false, understand the concept of truthy and falsy values
- Null: Intentionally set empty value
- Undefined: Undefined or uninitialized state
- Symbol: Create unique identifiers (ES6)
- BigInt: Arbitrary-precision integers (ES2020)
- Use
typeofto check types, but pay attention to the special case oftypeof null - Values of basic types are immutable