Undefined vs. Undeclared
In JavaScript, understanding what happens when data is absent is just as important as managing data that is present. Two concepts that are often confused are undefined and undeclared.
Undefined
The primitive value undefined represents the absence of a value. It means a variable has been officially created (declared) in the code, but it has not yet been assigned any actual data.
let currentCustomer; // The variable exists, but holds no value
console.log(typeof currentCustomer); // "undefined"
Note: While you can technically assign undefined to a const variable, doing so makes the variable permanently empty since const cannot be reassigned later. It’s generally useless:
const invalidConfig; // SyntaxError: missing = in const declaration
const emptyConfig = undefined; // This is valid, but permanently undefined
Undeclared
An undeclared variable is one that has never been created at all. If you attempt to access a variable name that doesn’t exist anywhere in your script, JavaScript will throw a hard error and stop execution.
// We never declared 'futureCustomer' using let, const, or var
console.log(futureCustomer); // ReferenceError: futureCustomer is not defined
One of JavaScript’s confusing quirks is that the error message for an undeclared variable reads “is not defined,” which sounds suspiciously like undefined, even though the two scenarios are fundamentally different.
Practical Example
In a reporting script, you might need to declare variables at the top to hold aggregated data that will be calculated later. By declaring them up front, you avoid ReferenceError crashes, even if they start off as undefined.
// Declare the variables so they exist in memory
let sentMessages;
let deliveredMessages;
let failedMessages;
// Later in the script, these will be populated with data.
// For now, they can safely be referenced without crashing.
console.log("Sent is:", sentMessages); // Sent is: undefined
console.log("Delivered is:", deliveredMessages); // Delivered is: undefined
console.log("Failed is:", failedMessages); // Failed is: undefined