Understanding JS Memory Allocation: Undefined vs Not Defined
Today, let's explore the complex world of JavaScript memory allocation today, with a particular emphasis on the concepts of undefined and Not Defined.
Trust me, it's not as daunting as it may sound.
The First Phase: Memory Allocation
When you declare a variable in JavaScript, the first phase is memory allocation. In this phase, JS assigns each variable a placeholder, and that placeholder is called undefined. It's like reserving a seat at the coding table but not assigning anyone to it yet.
Tip: Undefined is a special keyword and placeholder used to reserve memory for variables even before a single line of code is executed.
It's because JavaScript is a loosely typed language, in case you were wondering why. It does not immediately restrict variables into certain data types, in contrast to languages like C++ or Java.
Undefined
Undefined doesn't mean a variable is not declared; it means memory is allocated, but no value is assigned yet. It's like having a blank canvas waiting for an artist's touch.
var a;
console.log(a); // Output: undefined
a = 10;
console.log(a); // Output: 10
a = "hello JS";
console.log(a); // Output: hello JS
The snippet above shows how a variable evolves from being undefined to holding different values. It's like watching a story unfold!
Not Defined
Now, what if you try to access a variable that wasn't even declared or found during the memory allocation phase? You get the infamous Not Defined error. It's like trying to invite a guest to a party who wasn't even on the guest list!
Remember:
undefined
!==Not Defined
. Undefined means a variable is declared but has no value assigned, while Not Defined means the variable is not even declared.
Best Practices: Say No to Manual Undefined
While we're on the topic of good coding practices, let's make a pact: Never assign undefined to a variable manually. Let the magic happen on its own accord during the memory allocation phase.
But what if you want to initialize a variable with an empty value? Enter the null
keyword, a much cleaner and accepted practice.
// BAD code Practice
let x = undefined;
// Good Code Practice
let x = null;
In the world of coding, clarity is key, and using null
when you want to represent an empty value is just good manners.
So, the next time you encounter undefined or not defined in your JavaScript journey, remember, it's all about memory allocation and the art of letting variables find their purpose in the coding universe.
Thank you!
Subscribe to my newsletter
Read articles from Prerana Nawar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by