Day 6: Undefined vs Not Defined in JS Today I completed the next topic in my learning journey, focusing on a concept that confuses many beginners: the difference between undefined and not defined in JavaScript. While they sound identical, they mean very different things to the JavaScript engine. When you declare a variable but do not assign it a value, JavaScript allocates memory for it during the creation phase of the execution context and automatically assigns it a special placeholder called undefined. This means the variable definitely exists, but it just does not have a value yet. On the other hand, not defined means the variable has not even been declared in your code. If you try to access a variable that the JavaScript engine cannot find anywhere in the memory allocation phase, it will throw a ReferenceError telling you that the variable is not defined. This topic also highlights why JavaScript is known as a loosely typed or weakly typed language. You do not need to specify what kind of data a variable will hold. You can assign a number to a variable, and later change it to a string or a boolean without the engine throwing an error. One major mistake to avoid is manually assigning the value undefined to a variable to clear it or mark it as empty. While JavaScript will let you do this, it is highly discouraged by the developer community. The keyword undefined is meant to be used exclusively by the JavaScript engine as a default state. If you need to explicitly state that a variable is empty, you should use null instead. Understanding these small details makes a huge difference when debugging complex applications and tracing variable states in your code. What is your favorite method for handling empty or uninitialized variables in your projects? #JavaScript #WebDevelopment #NamasteJavaScript #JSFundamentals #CodingJourney #FrontendEngineer #UndefinedVsNotDefined #CleanCode
Undefined vs Not Defined in JavaScript Explained
More Relevant Posts
-
I’ve started learning scope in JavaScript, but before diving into it, I took an interesting detour into a very important question: Is JavaScript compiled or interpreted? Before getting into scope properly, I learned that JavaScript does not behave like a simple line-by-line interpreter. A good example is this: ```js console.log("Hello"); function foo() { console....log("world"); } console.log("hello world"); ``` If JavaScript was executed in a purely naive line-by-line way, we might expect "Hello" to be logged before the error appears. But that does not happen. The script fails before execution starts because the JavaScript engine first goes through an initial preparation phase. That phase includes things like: 1. parsing the code 2. checking whether the syntax is valid 3. building an internal representation 4. preparing the code for execution So a better mental model is: Source code -> Parse / syntax check -> Internal representation / compilation steps -> Execution This helped me understand that calling JS simply “interpreted” is not the full picture. Modern JavaScript engines like V8 are much more advanced. They can parse code, create internal representations, interpret some code, compile parts into bytecode or internal instructions, and even JIT-compile frequently used parts for better performance. So JavaScript is commonly called an interpreted language, but in modern engines, the reality is more nuanced. This also connects nicely with scope. Scope is about the visibility of variables and functions in code, but before JavaScript can execute code, the engine first needs to understand the structure of that code. That means scope is not just a runtime topic. It is closely connected to how the engine reads, parses, and prepares the program. My main takeaway: JavaScript is not random, and it is not just “reading one line at a time”. There is a preparation phase before execution, and understanding that makes topics like scope, hoisting, and errors much easier to reason about. #JavaScript #TypeScript #WebDevelopment #SoftwareEngineering #V8 #LearningInPublic
To view or add a comment, sign in
-
-
I’ve now wrapped up my current deep dive into JavaScript coercion, ending with one of the most misunderstood parts of the language: "==" vs "===" My biggest takeaway is that the right way to understand equality in JavaScript is not by memorising strange examples like: - 5 == "5" - false == 0 - "" == 0 - null == undefined Instead, it is by understanding the actual rules behind them. What I learned is that === and == are backed by different abstract operations in the ECMAScript spec: 1. === → IsStrictlyEqual(x, y) 2. == → IsLooselyEqual(x, y) For ===, the mental model is simple: - if the types differ, the result is false - no cross-type coercion happens But == is not just “convert both sides to numbers”. It follows a case-by-case algorithm. Depending on the values involved, JavaScript may: 1. convert strings to numbers 2. convert booleans to numbers 3. convert objects to primitives 4. apply the special null / undefined rule 5. compare BigInt and Number in a specific way That is why: - 5 == "5" is true - false == 0 is true - null == undefined is true - but null == 0 is false The best part of learning this topic is that JavaScript now feels much less random. I also feel more confident reading the ECMAScript spec now. I do not need to learn every abstract operation in depth, but I know how to navigate the spec when I want to understand why JavaScript produced a certain result. I’ve been maintaining detailed notes on everything I learned here: GitHub repo: https://lnkd.in/ephuZ-w6 #JavaScript #TypeScript #WebDevelopment #SoftwareEngineering #ECMAScript
To view or add a comment, sign in
-
-
Understood Hoisting in a much deeper way — not just definition, but what actually happens inside the JavaScript engine 👇 🧸 Imagine JavaScript like a teacher in a classroom Before teaching, the teacher prepares a register (memory) and writes all names first. 👉 JavaScript does the same thing before running code. 🧠 Behind the scenes (Real Concept): JavaScript runs in 2 phases: 1️⃣ Memory Creation Phase 2️⃣ Execution Phase ⚙️ During Memory Creation Phase: JavaScript creates something called an Execution Context (inside the Call Stack) Inside it, memory is allocated: 1- var → stored as undefined 2- let & const → stored but not initialized (Temporal Dead Zone) 3- functions → stored with full definition 💡 Example: console.log(a); var a = 10; 👉 Memory phase: a = undefined 👉 Execution phase: prints undefined 💡 Another example: console.log(b); let b = 20; 👉 Memory phase: b exists but is not initialized 👉 Execution phase: ❌ ReferenceError (because of Temporal Dead Zone) 💡 Functions: sayHi(); function sayHi() { console.log("Hi"); } 👉 Works because functions are fully stored in memory before execution 🎯 So what is Hoisting REALLY? It’s NOT “moving code to the top” ❌ It’s the result of how JavaScript allocates memory inside the Execution Context before execution begins ✅ 💼 Interview Insight: Most people say: 👉 “JS moves variables to top” ❌ Better answer: 👉 “Hoisting is a JavaScript behavior that occurs during the creation phase of the execution context, where memory is allocated for variables and functions before code execution. Variables declared with var are initialized as undefined, while let and const remain uninitialized in the Temporal Dead Zone, and function declarations are stored with their full definition.” #JavaScript #FrontendDeveloper #WebDevelopment #CodingJourney
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗗𝗮𝘆 𝗜 𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗼𝗼𝗱 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 You build something in JavaScript, and it looks fine. But then it breaks. I was building a task manager. I had a class with methods and API calls. It looked clean. But then I had a problem. I had an object with methods: - this.getAllTasks - this.getTaskByPriority - this.createTask I called one of these methods, and "this" was undefined. I was confused. I thought "this" referred to the object. But in JavaScript, "this" depends on how a function is called, not where it is written. The issue was not with classes or syntax. It was with how I was calling the function. When you extract a method from an object, it becomes a raw function reference. It loses its context. To fix this, you can use "bind(this)". It creates a new function and locks its context to the current instance. You can also use an arrow function, which inherits the context from where it is defined. I learned that functions in JavaScript are flexible, but they don't carry context automatically. You need to decide when to lock the context. This changed how I look at JavaScript. I'm still learning, but now I understand "this" and "bind" better. Source: https://lnkd.in/gqxDAYsJ
To view or add a comment, sign in
-
𝗦𝗽𝗿𝗲𝗮𝗱 𝗩𝗦 𝗥𝗲𝘀𝘁 𝗢𝗽𝗲𝗿𝗮𝘁𝗼𝗿𝘀 𝗜𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 You've seen ... in JavaScript and wondered what it does. The same syntax is used for two purposes: - Spread operator expands values - Rest operator collects values Understanding this difference is crucial for writing clean JavaScript. The spread operator expands elements from arrays or objects. It's like opening a box and taking everything out. It spreads elements individually and creates a shallow copy, avoiding mutation. The rest operator collects multiple values into one. It's like gathering everything into a box. All arguments are collected into an array. Here are the key differences: - Spread operator expands values - Rest operator collects values - Spread operator is used on the right side, rest operator on the left side - Spread operator outputs individual elements, rest operator outputs an array You can use spread and rest operators to merge arrays, remove properties from objects, and more. Mastering spread and rest operators helps you write cleaner code, handle data efficiently, and solve interview problems confidently. Source: https://lnkd.in/gmFfBhXX
To view or add a comment, sign in
-
🚀 Day 3/30 – JavaScript Challenge (LeetCode #2704: To Be Or Not To Be) Today’s problem was all about building a custom testing utility function using JavaScript — something developers actually use in real-world scenarios! 💡 🔍 What I Learned: How to create a function that returns an object with methods Deep understanding of closures and how values persist Implementing conditional checks with proper error handling Writing clean and reusable code for validation 🧠 Key Concept: I created an expect function that helps compare values using: ✔️ toBe() → checks strict equality (===) ✔️ notToBe() → checks inequality (!==) ⚡ Why it matters? This is similar to how testing frameworks (like Jest) work internally. Understanding this builds strong fundamentals in writing robust and testable code. 💻 Code Highlight: Clean use of closures + returning methods = powerful pattern in JavaScript!
To view or add a comment, sign in
-
-
Over the Easter break, I started learning JavaScript coercion, and it has already made the language feel far less random. My biggest takeaway so far is that coercion is simply JavaScript converting a value from one type to another so an operation can continue. The key is that JavaScript does not convert values randomly, it follows rules defined in the ECMAScript specification. What helped me most was asking 3 questions whenever I see surprising behaviour: 1. What operation is being performed? 2. What type of value does that operation need? 3. Will JavaScript convert something to make that operation possible? I also started learning about: - primitive vs non-primitive values - abstract operations like ToBoolean - truthy and falsy values - why `if ("hello")` runs but `if ("")` does not - why `[]` and `{}` are truthy - why `"" == 0` is not boolean coercion, but part of loose equality rules So far, this topic has taught me that JavaScript becomes much easier to understand when you stop memorising weird examples and start understanding what the language actually expects in each context. Next, I’ll be diving deeper into ToNumber, ToString, ToPrimitive, and loose equality. #JavaScript #TypeScript #WebDevelopment #SoftwareEngineering #ECMAScript
To view or add a comment, sign in
-
-
The JavaScript Temporal API will soon be Baseline Newly Available. Here's a cheatsheet that I built for developers who already know Date. https://lnkd.in/emvWBw-v Enjoy!
To view or add a comment, sign in
-
🧠 𝗪𝗿𝗶𝘁𝗶𝗻𝗴 𝗰𝗹𝗲𝗮𝗻𝗲𝗿, 𝘀𝗺𝗮𝗿𝘁𝗲𝗿 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝘄𝗶𝘁𝗵 𝗗𝗲𝘀𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗶𝗻𝗴 Destructuring is one of those features in JavaScript that can significantly improve code readability and enhances Developers Experience—yet it’s often underutilized or misunderstood. So I decided to break it down in a structured way. New Blog Published: “Mastering Destructuring in JavaScript” https://lnkd.in/gHAWq_sP 🔍 What’s covered in the blog: 🔹 Array & object destructuring fundamentals 🔹 Nested destructuring patterns 🔹 Default values cases 🔹 Practical use cases for writing cleaner, maintainable code Hitesh Choudhary Piyush Garg Akash Kadlag Suraj Kumar Jha Chai Aur Code Nikhil Rathore Jay Kadlag DEV Community #JavaScript #WebDevelopment #TechnicalWriting #CleanCode #LearningInPublic #Chaicode #Cohort
To view or add a comment, sign in
-
Something small but nice I recently came across in JavaScript 👨💻✨ : String.trimEnd(). Earlier, whenever I needed to remove only the trailing spaces from a string, I used to write a small regex for it or sometimes even used .trim(). But .trim() removes both leading and trailing spaces, which isn’t always what we want — especially when the leading indentation actually matters. For example, I used to do something like this: const message = " Action Required: Clear Cache "; // Earlier approach const cleaned = message.replace(/\s+$/, ""); It works, but the regex isn’t exactly the most readable thing 🤯. Recently I noticed there’s a much cleaner native way 👇 const message = " Action Required: Clear Cache "; const result = message.trimEnd(); Now it clearly expresses the intent: remove only the trailing whitespace while keeping the start intact ✅. Result: " Action Required: Clear Cache" Small things like this make code more readable and intentional ✨, and since it’s part of modern JavaScript (along with trimStart()), there’s no need for regex hacks anymore. Sometimes the language already has the cleaner solution, we just discover it a bit later 😄🚀 #JavaScript #CodingTips #CleanCode #WebDev #WebDevelopment
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development