JavaScript Data Types
JavaScript Data Types Explained
Section titled “JavaScript Data Types Explained”Understanding data types is crucial in any programming language, including JavaScript. JavaScript is a dynamically typed language, which means you don’t have to declare the type of a variable before using it.
JavaScript Primitive Data Types
Section titled “JavaScript Primitive Data Types”JavaScript has seven primitive data types:
- String: Represents textual data (e.g., “Hello World”).
- Number: Represents numeric values, including integers and floating-point numbers (e.g.,
42,3.14). Special numeric values includeInfinity,-Infinity, andNaN(Not a Number). - Boolean: Represents a logical entity and can have two values:
trueorfalse. - Null: Represents the intentional absence of any object value. It is a primitive value, but
typeof nullparadoxically returns “object” (a long-standing quirk). - Undefined: Represents a variable that has been declared but not yet assigned a value, or a function argument not provided.
- Symbol (ES6): Represents a unique and immutable identifier. Often used as keys for object properties to avoid name collisions.
- BigInt (ES2020): Represents whole numbers larger than 253 - 1, which is the largest number JavaScript can reliably represent with the
Numbertype.
And one non-primitive (reference) type:
- Object: Represents a collection of key-value pairs. Arrays, Functions, Dates, RegExp, etc., are all specialized types of objects.
Example of variable declarations:
let age = 30; // Numberconst name = "Alice"; // Stringconst isActive = true; // Booleanconst userSettings = { theme: "dark" }; // Objectconst scores = [90, 85, 92]; // Array (a type of Object)let notAssigned; // Undefinedlet noValue = null; // Nullconst id = Symbol('uniqueId'); // Symbolconst veryLargeNumber = 9007199254740991n; // BigIntThe Concept of Data Types and Type Coercion
Section titled “The Concept of Data Types and Type Coercion”Knowing the data type of a variable is important because operations behave differently based on types.
Consider this:
let result = 16 + "Volvo"; // What happens here?JavaScript performs type coercion. If one operand is a string, JavaScript will try to convert the other operand to a string and concatenate them. So, result becomes "16Volvo".
JavaScript evaluates expressions from left to right. Different sequences can produce different results due to coercion:
let x = 16 + 4 + "Volvo"; // result: "20Volvo" (16+4 is 20, then 20 + "Volvo")let y = "Volvo" + 16 + 4; // result: "Volvo164" ("Volvo"+16 is "Volvo16", then "Volvo16"+4)To avoid unexpected behavior, it’s often best to be explicit about types or use strict equality operators (===, !==) which don’t perform type coercion. You can learn more in the comparisons chapter.
JavaScript Has Dynamic Types
Section titled “JavaScript Has Dynamic Types”JavaScript is dynamically typed. This means a variable can hold values of different types at different times:
let x; // x is undefinedx = 5; // Now x is a Numberx = "John"; // Now x is a Stringx = { type: "Car" }; // Now x is an ObjectJavaScript Strings
Section titled “JavaScript Strings”A string is a sequence of characters. Strings can be created using single quotes ('...'), double quotes ("..."), or backticks (template literals: `...`).
const carName1 = "Volvo XC60";const carName2 = 'Volvo XC60';
// Using quotes inside strings:const answer1 = "It's alright";const answer2 = 'He is called "Johnny"';
// Template Literals (ES6+) for embedded expressions and multi-line strings:const userName = "Bob";const greeting = `Hello, ${userName}!`; // "Hello, Bob!"const multiLine = `This isa multi-linestring.`;Strings have many built-in methods for manipulation (e.g., length, toUpperCase(), slice()).
JavaScript Numbers
Section titled “JavaScript Numbers”JavaScript uses a single Number type for both integers and floating-point numbers, based on the IEEE 754 standard. This means there can be precision issues with floating-point arithmetic.
const pi = 3.14; // With decimalsconst count = 100; // Without decimals
// Exponential notation:const largeNum = 1.23e6; // 1.23 * 10^6 = 1230000const smallNum = 1.23e-4; // 1.23 * 10^-4 = 0.000123
// Special numeric values:console.log(1 / 0); // Infinityconsole.log("text" / 2); // NaN (Not a Number)For numbers beyond the safe integer limit (±(253-1)), use BigInt.
JavaScript Booleans
Section titled “JavaScript Booleans”Booleans represent truth values and can only be true or false.
const isDataValid = true;const isLoggedIn = false;
if (isLoggedIn) { console.log("User is logged in.");} else { console.log("User is not logged in.");}Booleans are fundamental for conditional logic and control flow.
JavaScript Arrays
Section titled “JavaScript Arrays”Arrays are ordered collections of values. They are created using square brackets [].
const cars = ["Saab", "Volvo", "BMW"];const mixedArray = [1, "apple", true, { city: "New York" }];Array elements are accessed by their index (0-based): cars[0] is “Saab”. Arrays have many powerful built-in methods (e.g., push(), pop(), map(), filter(), reduce()).
JavaScript Objects
Section titled “JavaScript Objects”Objects are unordered collections of key-value pairs (properties). They are created using curly braces {}.
const person = { firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue", address: { street: "123 Main St", city: "Anytown" }};Properties are accessed using dot notation (person.firstName) or bracket notation (person["lastName"]). Objects are highly versatile and form the basis of complex data structures.
The typeof Operator
Section titled “The typeof Operator”The typeof operator returns a string indicating the type of its operand.
typeof "John" // Returns "string"typeof 3.14 // Returns "number"typeof NaN // Returns "number" (NaN is a special number)typeof false // Returns "boolean"typeof [1, 2, 3, 4] // Returns "object" (Arrays are objects)typeof { name: 'John', age: 34 } // Returns "object"typeof new Date() // Returns "object"typeof function() {} // Returns "function" (Functions are special objects)typeof myVariable // Returns "undefined" (if myVariable is not declared or unassigned)typeof null // Returns "object" (This is a historical bug)typeof Symbol('id') // Returns "symbol"typeof 9007199254740991n // Returns "bigint"Note: typeof null returning “object” is a long-standing quirk in JavaScript. To properly check for null, use strict equality: myVar === null. |
|---|
Undefined
Section titled “Undefined”undefined is a primitive value automatically assigned to variables that have just been declared, or to function arguments for which there are no actual arguments, or to missing object properties.
let personName; // Value is undefined, typeof personName is "undefined"
function greet(name) { console.log(name); // If called as greet(), name will be undefined}
const obj = {};console.log(obj.missingProperty); // undefinednull is a primitive value that represents the intentional absence of any object value. It must be explicitly assigned.
let user = null; // Value is null, typeof user is "object" (the quirk)
// To explicitly clear an object reference:let myObject = { data: "some data" };myObject = null; // The object is now eligible for garbage collectionDifference Between Undefined and Null
Section titled “Difference Between Undefined and Null”undefined typically means a variable has not been initialized or a value is missing. null is used to explicitly indicate that a variable should have no value or that an object reference points to nothing.
console.log(typeof undefined); // "undefined"console.log(typeof null); // "object"
console.log(null === undefined); // false (strict equality)console.log(null == undefined); // true (loose equality, due to type coercion - generally avoid)It’s generally recommended to use strict equality (=== and !==) to avoid confusion caused by type coercion when comparing null and undefined.