✅ JavaScript Output — Understanding Object Properties Clearly This morning’s code was: let user = { name: "Veera" }; console.log(user.name); console.log(user.age); console.log("age" in user); console.log(user.hasOwnProperty("age")); 💡 Correct Output Veera undefined false false 🧠 Simple Explanation : 🔹 Line 1: console.log(user.name); The property name exists in the object. So JavaScript prints: Veera 🔹 Line 2: console.log(user.age); The property age does not exist in the object. When you access a missing property, JavaScript does not throw an error — it simply returns: undefined ✔ Missing property ≠ error. 🔹 Line 3: "age" in user The in operator checks: “Does this property exist in the object (or its prototype)?” Since age is not present anywhere, the result is: false 🔹 Line 4: user.hasOwnProperty("age") This checks: “Is this property defined directly on this object?” Again, age is not defined on user. So the result is: false 🎯 Key Takeaways : Accessing a missing property returns undefined "key" in object checks existence, not value hasOwnProperty() checks only direct properties undefined value ≠ property exists 📌 This distinction is very important when working with: APIs Forms Optional data 💬 Your Turn Did you know the difference between undefined, in, and hasOwnProperty? Comment “Clear now ✅” or “Learned today 🙌” #JavaScript #FrontendDevelopment #LearnJS #CodingInterview #Objects #TechWithVeera #WebDevelopment #100DaysOfCode
JavaScript Object Property Access and Existence
More Relevant Posts
-
JavaScript objects don’t behave the way many people expect. ✔ The output of the code in the picture will be: [ { id: 1, name: "Updated John" }, { id: 2, name: "Jane" } ] This surprises many people, but it is completely expected behavior in JavaScript. 🤔Why this happens? → Arrays in JavaScript store references to objects → Array.find() returns the actual object, not a copy → Objects are reference types, not value types So after this line: const foundUser = users.find(u => u.id === 1); 👉 Both of these point to the same object in memory: users[0] ────┐ ├──► { id: 1, name: "John" } foundUser ───┘ 👉 When you do: foundUser.name = "Updated John"; You are mutating that shared object. Since the array holds a reference to the same object, the array reflects the change. 💡 A safer approach is to update immutably (create a new array and a new object): const updatedUsers = []; const updatedUsers = users.map(user => user.id === 1 ? { ...user, name: "Updated John" } : user ); ▶ But remember: { ...user } is a shallow copy. If user contains nested objects, those nested references are still shared. In that case, you must copy the nested structure you modify, or use a deep clone. ▶ There is another option which is called structuredClone(). This function returns a deep copy of the object you are passing as an argument. const copy = structuredClone(user); Now mutating copy won’t affect the original object. #JavaScript #WebDevelopment #Coding
To view or add a comment, sign in
-
-
JavaScript Hoisting: The Concept That Separates “I use JS” from “I understand JS” Hoisting is one of those JavaScript behaviors that silently explains why some code works, and why some bugs are so hard to catch. In JavaScript, code runs in two phases: 1️⃣ Compilation (creation) phase 2️⃣ Execution phase During compilation, JavaScript sets up memory for variables and functions. This is where hoisting happens. 🔹 var hoisting Only the declaration is hoisted, not the initialization. ex: console.log(x); // undefined var x = 5; Behind the scenes, JavaScript treats it like: var x; console.log(x); x = 5; No error, but also no value yet. This behavior has caused countless subtle bugs in real-world apps. 🔹 Function declarations Function declarations are fully hoisted, name and body. sayHello(); // works function sayHello() { console.log("Hello"); } This is why function declarations behave differently from function expressions. 🔹 let & const (ES6) They are hoisted, but not initialized. Accessing them before declaration throws a ReferenceError. console.log(y); // ReferenceError let y = 10; This period is known as the Temporal Dead Zone (TDZ), a design choice to make code safer and more predictable. 💡 Why this matters in real projects - Explains unexpected undefined - Helps debug scope-related issues - Shows you understand how JS actually works under the hood 📌 Best practice Don’t rely on hoisting. Write code that’s clear, intentional, and predictable, your future self (and your team) will thank you. #JavaScript #Frontend #WebDevelopment #SoftwareEngineering #CleanCode
To view or add a comment, sign in
-
🔍 Null vs Undefined in JavaScript -> Understanding the difference between null and undefined and Let's break down. 🔹 undefined undefined means a variable has been declared but not assigned any value. It is the default value assigned by the JavaScript engine. Common cases where you get undefined: A variable declared but not initialized A function that does not return anything Accessing a non-existent object property Examples: let a; console.log(a); // undefined function test() {} console.log(test()); // undefined let obj = {}; console.log(obj.name); // undefined ✔ undefined is a falsy value ✔ Assigned automatically by JavaScript 🔹 null null is an intentional assignment that represents no value or an empty object reference. It is explicitly set by the developer. Example: let user = null; console.log(user); // null ✔ null is also a falsy value ✔ It must be assigned manually 🔹 Behavior in Arithmetic Operations JavaScript handles null and undefined differently in calculations: null + 20 // 20 → null is converted to 0 undefined + 20 // NaN 🔹 Equality Comparison null == undefined // true (loose equality) null === undefined // false (strict equality) 🧠 Key Takeaway Use undefined when a value is not yet assigned (default behavior) Use null when you want to explicitly indicate “no value” Ajay Suneja 🇮🇳 ( Technical Suneja ) #JavaScript #WebDevelopment #Frontend #Programming #JSBasics
To view or add a comment, sign in
-
✅ JavaScript Output — Functions vs Function Calls Explained This morning’s code was: function greet() { return "Hello"; } console.log(typeof greet); console.log(typeof greet()); console.log(greet instanceof Object); 💡 Correct Output function string true 🧠 Simple Explanation : 🔹 Line 1: typeof greet Here, we are not calling the function. We are just referring to it. In JavaScript: A function itself is a special type of object typeof a function returns "function" ✔ Output: function 🔹 Line 2: typeof greet() Now the function is called. greet() // returns "Hello" So this becomes: typeof "Hello" Since "Hello" is a string, ✔ Output: string 🔹 Line 3: greet instanceof Object This checks: “Is greet an object?” In JavaScript: Functions are objects They can have properties and methods So the answer is: ✔ Output: true 🎯 Key Takeaways : typeof functionName → "function" typeof functionName() → type of returned value Functions are objects in JavaScript That’s why functions can have properties like: greet.customProp = "test"; 📌 This is why JavaScript is called a first-class function language. 💬 Your Turn Did you already know functions are objects in JavaScript? Comment “Knew it 👍” or “Learned today 😮” #JavaScript #FrontendDevelopment #LearnJS #CodingInterview #Functions #TechWithVeera #WebDevelopment #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 JavaScript Maps (Key–Value Pairs) — A Cleaner Way to Store Data. Today I learned about Map in JavaScript, and it’s much more powerful than using plain objects in many cases. A Map stores data in key–value pairs, just like objects — but with important advantages. 🔹 Why use Map instead of an Object? ✅ Keys can be any data type (object, function, number, etc.) ✅ Maintains insertion order ✅ Built-in methods for easy operations ✅ Better performance for frequent additions/removals 🔹 Simple example: const userMap = new Map(); userMap.set("name", "Sourav"); userMap.set("role", "Developer"); userMap.set(1, "ID"); console.log(userMap.get("name")); // Sourav 🔹 Useful methods: set(key, value) → add/update get(key) → access value has(key) → check existence delete(key) → remove size → total entries 💡 Real-world use cases: Caching API responses Managing user sessions Handling complex keys in applications Learning these core JavaScript concepts deeply is helping me write more efficient and readable code. 📌 If you’re learning JS, don’t skip Map — it’s a small concept with big impact. 👉 Do you prefer Object or Map in your projects? Let’s discuss 👇 #JavaScript #WebDevelopment #LearningInPublic #FrontendDevelopment #MERN #CodingJourney #DeveloperLife
To view or add a comment, sign in
-
-
The JavaScript Feature That Simulates Private Variables 🔒 Let’s talk about one of JavaScript’s most powerful, yet often misunderstood features: Closures. Many developers struggle with the concept initially, but once it clicks, it changes how you architect your code. At its core, a closure gives you access to an outer function’s scope from an inner function. The magic happens because the inner function "remembers" the environment in which it was created, even after the outer function has finished executing. Why is this useful? JavaScript doesn't have native "private" variables in the traditional OOP sense (though class fields are changing this). Closures allow us to emulate data privacy. Look at this classic example: creates a counter where the count variable is completely inaccessible from the outside world except through the returned increment function. function createCounter() { let count = 0; // This variable is now "private" return function() { count++; return count; }; } const counter = createCounter(); console.log(counter()); // 1 console.log(counter()); // 2 // console.log(count); // ReferenceError: count is not defined You cannot accidentally modify count from the global scope. You have created a protected state. Are you using closures intentionally in your codebase today? #JavaScript #WebDevelopment #CodingTips #SoftwareEngineering #Closures
To view or add a comment, sign in
-
-
Mastering Set in JavaScript Set in JavaScript allows us to store unique values only. Arrays can do something similar but there are important differences we should know. In this post, we’ll explore how Set works and when to use it. For the full comparison with Array, please watch the video. A Set is an unordered collection that stores only unique values and is optimised for quick existence checks. 🔹 Create a Set const mySet = new Set([1,2,3]); 🔹 Add values mySet.add(4); If we try to add a duplicate value: mySet.add(3); it will be ignored, because a Set only stores unique values. We can also add strings, arrays, and objects in the same way. In the case of objects though, a Set treats values as duplicates if they share the same reference. const a = {id: 1}; mySet.add(a); mySet.add(a); 🔹 Finding values Unlike arrays, Sets don’t have indexes, so values can’t be accessed by position. Instead, values are accessed through iteration using forEach or for...of: mySet.forEach((value) => console.log(value)); or for (const value of mySet) { console.log(value); } There is no index available during iteration. 🔹 Remove or clear values: mySet.delete(2); mySet.clear(); 🔹 Check for value: mySet.has(2); 🔹 Get size: mySet.size; Use a Set when we need to track only unique values and want fast checks to see if something already exists. #frontend #javascript #set #array
To view or add a comment, sign in
-
Day 3: JavaScript Hoisting — Magic or Logic? Yesterday, we learned that JavaScript creates memory for variables before it executes the code. Today, let’s see the most famous (and sometimes confusing) result of that: Hoisting. What is Hoisting? Hoisting is a behavior where you can access variables and functions even before they are initialized in your code without getting an error. Wait... why didn't it crash? 🤔 If you try this in other languages, it might throw an error. But in JS: During Memory Phase: JS saw var x and gave it the value undefined. It saw the function getName and stored its entire code. During Execution Phase: When it hits console.log(x), it looks at memory and finds undefined. When it hits getName(), it finds the function and runs it! ⚠️ The "Let & Const" Trap Does hoisting work for let and const? Yes, but with a catch! They are hoisted, but they are kept in a "Temporal Dead Zone". If you try to access them before the line where they are defined, JS will throw a ReferenceError. Pro Tip: Always define your variables at the top of your scope to avoid "Hoisting bugs," even though JS "magically" handles them for you. Crucial Takeaway: Hoisting isn't code physically moving to the top; it’s just the JS Engine reading your "ingredients" before "cooking" (Phase 1 vs Phase 2). Did you know about the Temporal Dead Zone? Let me know in the comments! #JavaScript #WebDev #100DaysOfCode #Hoisting #CodingTips #FrontendDeveloper
To view or add a comment, sign in
-
-
📘 JavaScript Master Notes – Deep & Clear 7️⃣ bind, call, apply — খুব সহজ ব্যাখ্যা ✔ call() → ফাংশন call করে + this সেট করে function test(a, b) { console.log(this.name, a + b); } test.call({ name: "Farhana" }, 5, 10); ✔ apply() → call এর মতোই, কিন্তু আর্গুমেন্ট array test.apply({ name: "Farhana" }, [5, 10]); ✔ bind() → this permanently bind করে, কিন্তু ফাংশনকে সাথে সাথে কল করে না const newFunc = test.bind({ name: "Farhana" }, 5, 10); newFunc(); --- 8️⃣ this Behaviour (this এর আচরণ) ✔ 1. Global Scope console.log(this); // window (browser) ✔ 2. Simple Function → global object function test() { console.log(this); } test(); // window ✔ 3. Method inside object → object itself const obj = { name: "Farhana", show() { console.log(this.name); } }; obj.show(); // Farhana ✔ 4. Arrow Function → this নেই Arrow function-এর নিজস্ব this নেই। Parent scope থেকে this নেয়। const obj = { name: "Farhana", show: () => console.log(this.name) }; obj.show(); // undefined ✔ 5. Constructor Function → new object function Person(name) { this.name = name; } const p = new Person("Farhana");
To view or add a comment, sign in
-
In JavaScript what does it mean when something is both a function and has prototype as undefined? When a Function Has prototype === undefined In JavaScript, functions are objects, and most functions have a .prototype property because they can be used as constructors. someFunction.prototype === undefined What’s really happening? If a function’s .prototype is undefined, it means: - The function cannot be used as a constructor - You cannot call it with new - The function is not a “constructor-capable” function - This behavior exists because not all functions are designed to create objects. Example: console.log(Math.max.prototype); undefined -> built-in function, not a constructor console.log((() => {}).prototype); undefined -> arrow functions have no prototype console.log((async function () {}).prototype); {} -> async functions CAN be constructors console.log((function* () {}) .prototype); {} -> generator functions CAN be constructors Quick recap: Normal functions -> have .prototype Arrow functions -> no .prototype Built-in utility functions (like Math.max) -> no .prototype prototype === undefined -> function is callable, but not constructible How it can help you? Debugging TypeError: function is not a constructor. Writing cleaner APIs. Deepening your mental model of JavaScript’s object system. JavaScript isn’t inconsistent here — it’s intentional design.
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