Variables & Data Types: Storing Information
Variables and data types are the fundamental tools you will use to store, manipulate, and manage information within your programs. This chapter provides a deep dive into how JavaScript handles data in memory, the nuances of modern variable declarations, and the essential differences between primitive and reference types.
Why This Topic Matters
Mastering variables and data types is essential because they form the basis of almost every operation in JavaScript. Whether you are building a simple calculator or a complex data-driven dashboard, you need to understand how to store values and ensure they are treated correctly by the language.
When you understand these concepts clearly, more advanced topics like object-oriented programming or complex data transformations become much easier to navigate. This knowledge directly translates into better debugging skills, as you will be able to pinpoint why a variable might be undefined or why two seemingly identical objects are not considered equal. It also enables you to write cleaner, more efficient code by choosing the appropriate data structures for your tasks.
What Variables Are
At its core, a variable is a named reference to a specific value stored in the computer's memory. You can think of a variable as a labeled container that holds a piece of information. By assigning a name to this container, you can easily retrieve, use, and update that information throughout your code without having to remember its exact location in memory.
let age = 16;
const courseName = "JavaScript";
The Evolution of Declarations: let, const, and var
Modern JavaScript provides three keywords for declaring variables, each with its own specific behavior and use case. Understanding when to use let versus const is a key part of writing high-quality code.
The Standard: let and const
You should use let when you expect the value of a variable to change over time. This is common for counters in loops or status flags. On the other hand, const (short for constant) should be your default choice. Use it for values that should not be reassigned after their initial creation. Using const makes your intent clear to other developers and prevents accidental overwrites that could lead to bugs.
The Legacy: var
The var keyword is an older way of declaring variables that was standard before the introduction of ES6 in 2015. Unlike let and const, which are block-scoped, var is function-scoped and has some behaviors (like hoisting) that can be confusing for beginners. While you should avoid using var in new projects, it is important to recognize it when working with older codebases.
Naming Rules and Conventions
To ensure your code remains readable and functional, you must follow JavaScript's naming rules. Variable names can include letters, digits, underscores (_), and dollar signs ($). However, they cannot start with a digit, and they cannot be reserved keywords like if, while, or function.
Beyond the strict rules, JavaScript developers follow a widely accepted convention called camelCase. In this style, the first word is lowercase, and each subsequent word starts with a capital letter (e.g., userProfileImageUrl). Using descriptive, clear names like totalScore instead of vague ones like ts is a hallmark of a professional developer.
Primitive Data Types
JavaScript has seven primitive data types. Primitives are simple, immutable values that are copied by value rather than by reference.
Strings, Numbers, and Booleans
Strings are used to represent text and can be enclosed in single quotes, double quotes, or backticks. Numbers handle all numeric values, including integers and decimals, as 64-bit floating-point values. Booleans represent a simple logical state: either true or false.
Null and Undefined
These two types often confuse beginners because they both represent "nothingness," but they have different meanings. undefined typically means a variable has been declared but has not yet been assigned a value. null is an intentional assignment that represents the deliberate absence of any object value.
BigInt and Symbol
For specialized scenarios, JavaScript provides BigInt for working with integers larger than the standard Number limit, and Symbol for creating unique, hidden identifiers that won't conflict with other property names.
Reference Types: Objects and Arrays
Unlike primitives, Reference Types (such as Objects, Arrays, and Functions) can store collections of data and more complex logic. When you assign a reference type to a variable, you aren't storing the data itself; you are storing a "pointer" or address to where that data lives in memory.
const user = { name: "Leo" };
const scores = [90, 88, 95];
An important consequence of this is that even if a variable is declared with const, you can still modify (mutate) the contents of the object or array it points to. You only prevent the variable from pointing to a different object entirely.
Type Inspection and the null Quirk
You can check the type of any value using the typeof operator. This is an invaluable tool for debugging unexpected data from APIs. However, JavaScript has a famous historical quirk: typeof null returns "object". While this is technically a bug in the language's original design, it has been preserved for decades to avoid breaking existing websites.
console.log(typeof "hello"); // string
console.log(typeof 42); // number
console.log(typeof null); // object (historical quirk)
Primitive vs Reference Comparison
Understanding memory also explains why different types compare differently. When you compare two primitives, JavaScript checks if their values are the same. When you compare two reference types (like arrays), JavaScript checks if they point to the same location in memory. Even if two arrays have the exact same contents, they are different "boxes" in memory and will not be considered equal by the === operator.
const a = 5;
const b = 5;
console.log(a === b); // true (same value)
const arr1 = [1, 2];
const arr2 = [1, 2];
console.log(arr1 === arr2); // false (different addresses)
Common Mistakes and Debugging
The most frequent error for beginners is attempting to reassign a const variable, which will result in a TypeError. You must also be careful not to treat undefined and null as identical; while they are both "falsy," they serve different logical purposes in a program.
When your variables don't behave as expected, the best approach is to log their values and types immediately. Verify that your data hasn't been transformed unexpectedly—for example, by adding a number to a string and accidentally creating a new string. By reducing your code to a minimal reproduction and comparing the expected output with the actual state of your variables, you can quickly resolve even the most elusive bugs.