🚀 A JavaScript this Behavior That Surprised Me Consider this code: const user = { name: "Inderpal", greet() { console.log(this.name); } }; const greetFn = user.greet; greetFn(); Expected: Inderpal Actual output: undefined Why? Because this in JavaScript is not determined where a function is written. It’s determined by how the function is called. When we did: user.greet() this referred to user. But when we did: const greetFn = user.greet; greetFn(); The function lost its object context. So this became undefined (in strict mode) or the global object. ✅ One way to fix this is using bind: const greetFn = user.greet.bind(user); greetFn(); Now this will always refer to user. In JavaScript, understanding how this works is more important than memorizing syntax. #javascript #frontenddeveloper #webdevelopment #coding #softwareengineering
JavaScript this Behavior Explained: Understanding Context
More Relevant Posts
-
💻 JavaScript Intermediate – Custom map() Function The map() method is widely used to transform arrays. Here’s how you can implement it manually. 📌 Problem: Apply a function to each element of an array and return a new array. function customMap(arr, callback) { let result = []; for (let i = 0; i < arr.length; i++) { result.push(callback(arr[i])); } return result; } let numbers = [1, 2, 3]; let doubled = customMap(numbers, function(num) { return num * 2; }); console.log(doubled); 📤 Output: [2, 4, 6] 📖 Explanation: • map() creates a new array by applying a function to each element. • Here, we manually implemented the same logic using a loop and callback. 💡 Tip: Understanding this helps you grasp how higher-order functions work in JavaScript. #JavaScript #Coding #WebDevelopment #FrontendDevelopment #LearnToCode #ProgrammingTips
To view or add a comment, sign in
-
-
JavaScript objects have a powerful feature called Prototype that enables inheritance. In JavaScript, if an object doesn’t have a specific property or method, the engine automatically looks for it in its prototype. This process continues up the prototype chain until the property is found or the chain ends. Example: function Person(name) { this.name = name; } Person.prototype.greet = function () { console.log("Hello, my name is " + this.name); }; const john = new Person("John"); john.greet(); Even though john doesn’t directly have the greet() method, it can still access it through Person.prototype. This mechanism allows JavaScript objects to share methods and inherit behavior efficiently. Understanding prototypes helps you better understand how inheritance and object behavior work behind the scenes in JavaScript. Follow for more JavaScript concepts explained visually. #javascript #webdevelopment #frontenddeveloper #coding #learninginpublic #100DaysOfCode
To view or add a comment, sign in
-
-
🔍 A small JavaScript detail that can cause unexpected bugs: Object key ordering Many developers assume object keys are always returned in insertion order, but JavaScript actually follows a specific ordering rule when you iterate over object properties (Object.keys, Object.entries, for...in). The order is: • Integer index keys → sorted in ascending order • String keys → insertion order • Symbol keys → insertion order (not included in Object.keys) This is one of the reasons why using Object as a map can sometimes lead to unexpected iteration behavior when numeric keys are involved. If key order matters, Map is usually the more predictable choice since it preserves insertion order for all key types. Small language details like this are easy to overlook, but they often explain those subtle bugs you run into during debugging. #JavaScript #SoftwareEngineering #Frontend
To view or add a comment, sign in
-
-
Most people think they understand JavaScript classes. They don’t. Because JavaScript doesn’t even have real classes. What it actually has is prototypes — and classes are just syntactic sugar on top of them. Today in my T9 class, this completely changed how I look at JS: → Prototype-based inheritance (the actual mechanism) → Traditional vs Modern prototype handling → Constructor Functions (how things worked before classes) Then we moved to what most people are comfortable with: → Classes in JavaScript → constructor, extends, super, static → The 4 pillars of OOP: Encapsulation Inheritance Polymorphism Abstraction But here’s the uncomfortable truth: If you don’t understand prototypes, you don’t actually understand inheritance in JavaScript. You’re just memorizing syntax. That’s why debugging feels random. That’s why “this” behaves weird. That’s why things break in unexpected ways. Now it makes sense. Still early in the journey — but this was one of those “everything clicks” moments. Do you think JS should have stayed purely prototype-based, or are classes a good abstraction? #JavaScript #OOPS #WebDevelopment #LearningInPublic Thankyou Chai Aur Code Suraj Kumar Jha Sir Hitesh Choudhary Sir Piyush Garg Sir
To view or add a comment, sign in
-
-
🚨 JavaScript Hoisting – Something Most Developers Still Misunderstand Most developers say: 👉 “JavaScript moves variables to the top of the scope.” But that’s not actually what happens. Let’s test this 👇 console.log(a); var a = 10; Output: undefined Now try this: console.log(b); let b = 20; Output: ReferenceError: Cannot access 'b' before initialization 💡 Why the difference? Both var and let are hoisted. But the real difference is initialization timing. ✔ var is hoisted and initialized with undefined during the creation phase. ✔ let and const are hoisted but stay inside the Temporal Dead Zone (TDZ) until the line where they are declared. That’s why accessing them before declaration throws an error. 👉 So technically: JavaScript doesn’t “move variables to the top”. Instead, the JavaScript engine allocates memory for declarations during the creation phase of the execution context. Small detail. But it explains a lot of confusing bugs. 🔥 Understanding this deeply helps when debugging closures, scope issues, and async code. #javascript #frontend #webdevelopment #reactjs #coding #softwareengineering
To view or add a comment, sign in
-
One of my favorite JavaScript one-liners: filter(Boolean). Filtering out falsy values from an array meant chaining conditions and hoping I hadn't missed an edge case. When you pass Boolean as a callback to .filter(), JavaScript calls Boolean(item) on every element. Anything falsy - null, undefined, 0, ", false, NaN - gets removed. What you're left with is a clean array of only meaningful values. It's not just about writing less code. It's about communicating intent clearly. This pattern shines especially in real-world scenarios: cleaning up APl responses, processing user input, or combining .map) and.filter) to transform and sanitize data in a single chain. #JavaScript #WebDevelopment #SoftwareEngineering #CleanCode #Frontend #Programming #JS #CodeQuality #TechTips #Developer
To view or add a comment, sign in
-
-
Day 1 of 30 days of javascript challenge. problem-2667 Problem - Write a function createHelloWorld that returns another function, that returns "Hello World" As this is my first code, I revised my notes on javascript scope. ☑️ Function scope - Any variables declared inside a function body cannot be accessed outside the function body, but global variables can be used inside function body ☑️ Block scope - Any variable declared inside { } cannot be used outside the { } block, although it supports only let and const keyword, var can be used ☑️ Lexical scope - A variable declared outside a function can be accessed inside another function defined after the variable declaration. (The opposite is not true ) This problem uses the concept of closures and higher order functions. Please feel free to discuss where can I improve the code or if you have a different perspective, comment below your views. #javascript #coding #development #motivation #goals #leetcode #webdevelopment
To view or add a comment, sign in
-
-
JavaScript Logic Practice Today I solved a JavaScript problem “Count Even Numbers in an Array.” The goal was to count how many numbers in the array are even (divisible by 2). Concepts & Methods Used: • Array.isArray() to validate input • for...of loop to iterate through the array • Modulus operator % to check even numbers • typeof and Number.isFinite() to validate numbers This practice helps improve JavaScript logic building and problem-solving skills step by step. I’m working on JavaScript logic every day to improve my coding skills. 💻 #JavaScript #CodingPractice #ProblemSolving #WebDevelopment #SoftwareDevelopment #FrontendDevelopment
To view or add a comment, sign in
-
-
JavaScript can be surprisingly logical… and surprisingly weird at the same time. 😄 Take a look at these three lines: console.log(true + true); console.log(null + 1); console.log(undefined + 1); Before running them, try guessing the outputs. Here’s what JavaScript actually returns: true + true → 2 null + 1 → 1 undefined + 1 → NaN At first, this felt a little strange to me. But it starts to make sense once you remember how type coercion works in JavaScript. true is treated as 1, so 1 + 1 = 2 null becomes 0, so 0 + 1 = 1 undefined turns into NaN, which leads to NaN Small examples like this are a good reminder that JavaScript quietly converts values behind the scenes. And if you’re not aware of it, the results can feel pretty surprising. The deeper I go into JavaScript, the more I realize that understanding these tiny behaviors makes a huge difference in writing reliable code. Which one caught you off guard the most? #javascript #webdevelopment #frontend #coding #learninginpublic
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