Understanding the behavior of `this` in JavaScript can be tricky. Here’s a breakdown of the output from the provided code: The output is: ``` undefined Jyoti ``` **Why this output occurs (Step-by-Step):** 1️⃣ **Method reference loses `this`:** When we reference the method like this: ```javascript const fn = user.getName; ``` `fn` becomes a regular function reference and is no longer associated with the `user` object. Thus, when we call: ```javascript fn(); ``` `this` refers to the global object (or `undefined` in strict mode). This is why the output is: ``` fn() → undefined ``` 2️⃣ **`bind` permanently fixes `this`:** When we use `bind`: ```javascript const boundFn = fn.bind(user); ``` It creates a new function where `this` is permanently set to `user`. Therefore, calling: ```javascript boundFn(); ``` results in: ``` boundFn() → "Jyoti" ``` 🔑 **Key Takeaways:** - The value of `this` depends on how a function is called, not where it is defined. - Extracting a method from its object breaks its original context. - `bind` creates a new function with a fixed `this`. - `call` and `apply` set `this` temporarily, while `bind` sets it permanently. Losing the `this` context is a common pitfall in JavaScript development. #JavaScript #InterviewQuestions #FrontendDeveloper #MERNStack #ReactJS #CallBindApply
Understanding JavaScript's `this` Context
More Relevant Posts
-
📌 Understanding JSON.parse() in JavaScript In JavaScript, data often travels between systems in JSON (JavaScript Object Notation) format — especially when working with APIs. To use that data inside your application, JavaScript provides the JSON.parse() method. 👉 What does JSON.parse() do? 🔹 JSON.parse() converts a JSON string into a JavaScript object. 👉 In simple terms: 🔹 It helps JavaScript understand and work with JSON data. 👉 Example Explanation: 🔹 The API response is a string 🔹 JSON.parse() converts it into an object 🔹 Now we can access properties using dot notation 👉 Why is JSON.parse() important? 🌐 Used when handling API responses 💾 Converts data from localStorage / sessionStorage 🔄 Helps transform string data into usable objects 🚀 Essential for backend–frontend communication 💠 Common Error to Watch Out For 🔹 JSON.parse() only works on valid JSON. 🔹 Invalid JSON will throw an error. 🔹 JSON.parse("{name: 'Hari'}"); // ❌ Error ✔ Correct JSON format: JSON.parse('{"name":"Hari"}'); // ✅ JSON.parse() is a fundamental JavaScript method that plays a key role in real-world applications, especially while working with APIs and stored data. #JavaScript #WebDevelopment #Frontend #JSON #CodingTips #LearnJavaScript
To view or add a comment, sign in
-
-
𝗧𝗶𝗽𝘀 𝗙𝗼𝗿 𝗨𝘀𝗶𝗻𝗴 𝗧𝘆𝗽𝗲𝗦𝗰𝗿𝗶𝗽𝘁 You're stuck with JavaScript errors. You see "Cannot read property" errors. This happens when you're not sure what properties an object has. TypeScript can help. It's like JavaScript with extra checks. Here's what TypeScript does: - Tells you when you're accessing properties that don't exist - Autocompletes your objects because it knows what's in them - Documents your code through types - Refactors fearlessly because the compiler yells before users do To get started with TypeScript: - Learn the syntax - Read the handbook - Understand tsconfig.json Start with a small project. Use strict mode. You'll learn more from one strict project than ten tutorials. Let's look at an example. We have a function that fetches a user: ```javascript async function getUser(id: number): Promise<User> { const res = await fetch(`/api/users/${id}`); return res.json(); } ``` We can add type safety by using an interface for the User: ```javascript interface User { id: number; name: string; email?: string; } ``` But we still need to handle cases where the API returns something unexpected. We can use a type guard to validate the response at runtime: ```javascript function isUser(obj: unknown): obj is User { return ( typeof obj === "object" && obj !== null && id in obj && typeof (obj as User).id ===number && "name" in obj && typeof (obj as User).name === "string" ); } ``` Use Zod for response validation. Return a discriminated union for state. Handle network errors and validation failures separately. Remember: - Never use `any` — use `unknown` and narrow with type guards - Treat all external data as `unknown`, validate with Zod - Use discriminated unions for state - Prefer Result pattern over thrown exceptions - `strict: true` always Source: https://lnkd.in/g3KQZXbV
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗧𝗿𝗮𝗽 𝗼𝗳 𝗝𝗮𝗩𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗦𝘁𝗿𝗶𝗻𝗴 𝗟𝗲𝗻𝗴𝗍𝗵 You may have encountered a problem when truncating strings in JavaScript. This happens because JavaScript strings do not work as you expect. When you truncate a string, you might get garbled characters or broken emoji. This is because JavaScript's string APIs operate on code units, not on what you see on screen. Here are some key concepts to understand: - Code points: These are unique numbers for each character, symbol, or control sequence. - Code units: These are the minimal bit combinations used to represent a single unit of encoded text. - Grapheme clusters: These are what you perceive as a single visual character. JavaScript strings are sequences of 16-bit values. The .length property returns the number of code units, not characters. This can lead to problems when truncating strings. To safely truncate strings, you can use the spread syntax to preserve code points: ```javascript function truncateCodePoints(str, maxCodePoints) { return [...str].slice(0, maxCodePoints).join(""); } ``` For proper grapheme cluster handling, use Intl.Segmenter: ```javascript function truncateGraphemes(str, maxGraphemes) { const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" }); const segments = [...segmenter.segment(str)]; return segments .slice(0, maxGraphemes) .map((s) => s.segment) .join(""); } ``` Remember to treat strings as opaque sequences when possible. Use [...str] iteration when you need code point access, and reach for Intl.Segmenter when you need to match user-perceived character boundaries. Source: https://lnkd.in/gpAeKEai
To view or add a comment, sign in
-
🚀 𝗙𝗶𝗿𝘀𝘁 - 𝗖𝗹𝗮𝘀𝘀 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝘀𝗰𝗿𝗶𝗽𝘁 In JavaScript, functions are first-class values. That means the language allows functions to be treated the same way as any other value. Practically, this gives us three abilities: • assign a function to a variable • pass a function as an argument • return a function from another function Example:- 1. when assigned as a value const sayHi = function () console.log("Hi"); } => 𝗧𝗵𝗶𝘀 𝗶𝘀 𝘄𝗵𝘆 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗲𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻𝘀, 𝗮𝗻𝗼𝗻𝘆𝗺𝗼𝘂𝘀 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀, 𝗮𝗻𝗱 𝗮𝗿𝗿𝗼𝘄 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 𝗮𝗿𝗲 𝗻𝗼𝘁 𝘀𝗽𝗲𝗰𝗶𝗮𝗹 𝗰𝗮𝘀𝗲𝘀 , 𝘁𝗵𝗲𝘆’𝗿𝗲 𝗷𝘂𝘀𝘁 𝘃𝗮𝗹𝘂𝗲𝘀. 2. function passed as an argument function executeFunc (callback) { callback(); } executeFunc(sayHi) => 𝗧𝗵𝗶𝘀 𝗶𝘀 𝘁𝗵𝗲 𝗳𝗼𝘂𝗻𝗱𝗮𝘁𝗶𝗼𝗻 𝗳𝗼𝗿 𝗰𝗮𝗹𝗹𝗯𝗮𝗰𝗸𝘀, 𝗲𝘃𝗲𝗻𝘁 𝗵𝗮𝗻𝗱𝗹𝗲𝗿𝘀, 𝗮𝗻𝗱 𝗮𝘀𝘆𝗻𝗰 𝗰𝗼𝗱𝗲. 𝗧𝗵𝗲 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗶𝘀 𝗷𝘂𝘀𝘁 𝗯𝗲𝗶𝗻𝗴 𝗽𝗮𝘀𝘀𝗲𝗱 𝗹𝗶𝗸𝗲 𝗱𝗮𝘁𝗮. 3. Returning from another function function outer() { return function inner() { console.log("Inner function executed"); }; } const fn = outer(); fn(); => 𝗧𝗵𝗶𝘀 𝗯𝗲𝗵𝗮𝘃𝗶𝗼𝗿 𝗲𝗻𝗮𝗯𝗹𝗲𝘀 𝗰𝗹𝗼𝘀𝘂𝗿𝗲𝘀 𝗮𝗻𝗱 𝗵𝗶𝗴𝗵𝗲𝗿-𝗼𝗿𝗱𝗲𝗿 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 (𝗺𝗮𝗽, 𝗳𝗶𝗹𝘁𝗲𝗿, 𝗿𝗲𝗱𝘂𝗰𝗲). Most JavaScript patterns work because functions can be passed around like data. First-class functions are the rule that makes that possible. #Javascript #Functions #WebDevelopment #Frontend
To view or add a comment, sign in
-
-
Did you know that when you use an array inside a JavaScript template literal, it doesn’t behave like an array at all? If you write something like: `Stack: ${['React', 'Node', 'TypeScript']}` you might expect JSON-style output or the array structure. But JavaScript actually produces: "Stack: React,Node,TypeScript" That’s because template literal interpolation triggers implicit coercion: .toString() → .join(',') This isn’t a quirk — it’s part of the language design, and arrays have always been stringified using commas. Where this is useful There are a few scenarios where this implicit join is convenient: 1 - quick logging or debugging 2 - passing arrays into string-based utilities 3 - small helper functions where formatting doesn’t matter, etc. Where it becomes risky In more sensitive areas — UI text, error messages, URLs, file paths, nested arrays — this implicit join can lead to subtle formatting bugs or unreadable output, especially if you didn’t intend commas. My recommendation For clarity and predictability in production code, being explicit is usually the better choice: `Technologies: ${tech.join(', ')}` Making the formatting intentional helps avoid surprises and keeps code easier to understand for everyone reading it. #JavaScript #React #WebDevelopment #FrontendEngineering
To view or add a comment, sign in
-
-
Day 64 – JavaScript String Methods Today I explored essential JavaScript String methods that help in manipulating and validating text data effectively. These methods are widely used in real-world applications such as form validation, data formatting, and UI handling. Topics Covered: length – Find the number of characters (including spaces) replace() – Replace the first occurrence of a specified value replaceAll() – Replace all matching values in a string split() – Convert a string into an array based on a separator indexOf() – Get the index position of a character or word slice() – Extract a portion of a string using index values trim() – Remove extra spaces from both ends trimStart() – Remove spaces from the beginning trimEnd() – Remove spaces from the end startsWith() – Check if a string starts with a specific value endsWith() – Check if a string ends with a specific value Understanding these methods makes string handling more efficient and improves code clarity and performance in JavaScript applications. #JavaScript #StringMethods #FrontendDevelopment #WebDevelopment #LearningJavaScript
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗞𝗲𝘆𝘄𝗼𝗿𝗱 "𝗧𝗵𝗶𝘀" 𝗜𝗻 𝗝𝗮 v𝗮𝗦𝗰𝗿𝗶𝗽𝘁 You need to understand how "this" works in JavaScript. It can change its value depending on how it is called. Here are 4 rules to simplify your understanding: - Inside a function,this refers to a global context (window for browser, global for nodejs) - Inside a method, "this" refers to an object - The value of "this" can be modified by call and apply functions and also when converting a method to a function and vice-versa - The value of "this" will never change if it is in an arrow function or a bind function For example, consider the code: ```javascript const a = [1,2,3].map(function(n){ return n*this; }, 2); const b = [1,2,3].map( n => { return n*this; }, 2); ``` The first example returns [2,4,6], while the second one returns [NaN, NaN, NaN]. This is because the value of "this" is different in the two cases. You can modify the value ofthis using call or apply functions. For example: ```javascript function showBalance(value){ console.log(this.balance); } const account1 = { balance: 100 } const account2 = { balance: 50 } showBalance.call(account1); //100 showBalance.apply(account2); //50 ``` The value of "this" will never change if it is in an arrow function or a bind function. For example: ```javascript function Account() { this.balance = 100; this.showBalance = () => { console.log(this.balance); }; } const account = new Account(); const showBalance = account.showBalance; account.showBalance(); //100 showBalance(); //100 showBalance.call(); //100 showBalance.apply(); //100 ``` Source: https://lnkd.in/dqM4g27R
To view or add a comment, sign in
-
𝗧𝗵𝗶𝘀 𝗜𝘀 𝗔 𝗛𝗲𝗮𝗱𝗹𝗶𝗻𝗲 Here is a JavaScript question. Look at this code: ```javascript const api = { baseURL: "https://api.example.com", fetchUser: (id) => { return `${this.baseURL}/users/${id}`; }, fetchPost(id) { return `${this.baseURL}/posts/${id}`; } }; console.log(api.fetchUser(1)); console.log(api.fetchPost(2)); ``` What will it print? Hint: Arrow functions get their 'this' from where they are written. Regular functions get their 'this' from how they are called. What is 'this' at the top of a script? The answer is: undefined/users/1 https://lnkd.in/gqjiZ4AY Why? - Arrow functions like `fetchUser` do not have their own `this`. They use the `this` from the place they are written. At the top of a script, `this` is usually `window` (in browsers) or `global` (in Node.js). Neither of these has a `baseURL`. So, `this.baseURL` is undefined. - Regular functions like `fetchPost` get their `this` from how they are called. When you call `api.fetchPost(2)`, the `this` inside `fetchPost` is `api`. So, `this.baseURL` is "https://api.example.com". Object literals like `{...}` do not create a new `this` context. Key Takeaways: - Use regular function syntax `method() { }` when you want `this` to be the object itself. - Arrow functions are good for callbacks inside methods. They correctly get `this` from the method. - This mistake is hard to spot because it does not crash the program. It just gives wrong results. - Tools like ESLint can help find these issues. Source: https://lnkd.in/gnsP22BH
To view or add a comment, sign in
-
𝗪𝗵𝘆 𝗢𝗯𝗷𝗲𝗰𝘁𝘀 𝗔𝗿𝗲 𝗡𝗼𝘁 𝗘𝗾𝘂𝗮𝗹 You compare objects in JavaScript. But do you know how it works? In JavaScript, you have different data types. You can compare them: -test === "test" // true - true === true // true - 1 === 1 // true But objects are different: - {} === {} // false - [] === [] // false Why does this happen? JavaScript is a dynamically typed language. It has two main types: - Primitive types are immutable. They are compared by value. - Reference types are mutable. They are compared by reference. Here are some types and how they are compared: - Number: by value - String: by value - Boolean: by value - Object: by reference - Array: by reference When you compare objects, you compare their addresses in memory. This is why {} === {} is always false. Each object is allocated a new place in memory. You can learn more about this topic. Source: https://lnkd.in/gue2Us4C
To view or add a comment, sign in
-
Stop fighting with new Date() in JavaScript! 🗓️ If you’ve ever spent hours debugging timezones or accidental date mutations, you know the native JS Date object is... well, tricky. The good news? The Temporal API is coming to fix it. 🚀 I just read a great breakdown via Wasp on why this is a game-changer. Here are the highlights: ✅ Immutable by default: No more accidental bugs when modifying dates. ✅ Built-in Timezone support: No more manual UTC conversions. ✅ Easy Arithmetic: Adding days or months is now a single method call away. Is it time to ditch date-fns and Moment.js? Check out the full breakdown here: https://lnkd.in/dfZC2qyb #JavaScript #WebDev #CodingTips #TemporalAPI #Frontend
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