Why does this act weird in JavaScript? 💭 Ever wondered why this in JavaScript sometimes feels possessed? Let’s break the magic (and madness) behind it 👇 this depends on how a function is called, not where it’s written. JavaScript doesn’t decide the value of this when you write the function, but only when you call it — and how you call it changes what this means. **Some definitions that are needed to understand the post ** what is Binding is the way JavaScript decides what this refers to when a function is called. 👉 In short: Binding = the connection between this and its value (object/global/undefined). 🧩 Types of Binding Dynamic binding → this depends on how the function is called. Lexical binding → this is inherited from where the function was written (arrow functions). Manual binding → you set this yourself using .call(), .apply(), or .bind(). 💡 How this Behaves in Every Case (JavaScript) 1️⃣ Global Scope console.log(this===window) In browsers: this = window In strict mode: still window (only inside functions it becomes undefined) this refers to the global object. 2️⃣ Inside a Normal Function Non-strict mode: this = window Strict mode: this = undefined Because the function isn’t called by any object — so this defaults to global (or undefined in strict mode). 3️⃣ Inside an Arrow Function Non-strict mode: this = window Strict mode: this = undefined Arrow functions don’t have their own this. Instead, they lexically inherit this from the surrounding scope (where they were created). 🧠 In simple words: Arrow functions use the this value of their outer function — they never create a new one. 4️⃣ Inside an Object Method this refers to the object that owns the method → user. That’s called dynamic binding (decided by how it’s called). 🔶 Normal function is automatic dynamicly binding by js which this inside it refers to the object . 🔶Arrow function dynamic is lexical binding which means only lexical scops like global ,function or block scoop that inherit it's this value from it so this will not refer to the object 🔶Nested functions When a function is declared inside another function, the inner normal function doesn’t automatically inherit this from the outer one. 🧠 In simple words: Each normal function has its own this — it doesn’t care about its parent. 📉 Result: In non-strict mode → this = window In strict mode → this = undefined because the inner function isn’t called by any object that means no dynamic binding for the inner One obj =>one normal fun So what are the solutions that we have ?? 🅰️ Arrow function as an inner function because of it's lexical binding to inherit this value from the outer() 🅱️ Manual binding to force the inner function in the normal form (Not arrow) to refer to the outer #JavaScript #CodingTips #Frontend #WebDevelopment #LearningJS #WomenInTech #SamiaLearnsJS
How 'this' behaves in JavaScript: A Deep Dive
More Relevant Posts
-
🔍 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴? Hoisting is JavaScript’s default behavior of 𝗺𝗼𝘃𝗶𝗻𝗴 𝗱𝗲𝗰𝗹𝗮𝗿𝗮𝘁𝗶𝗼𝗻𝘀 (𝗻𝗼𝘁 𝗶𝗻𝗶𝘁𝗶𝗮𝗹𝗶𝘇𝗮𝘁𝗶𝗼𝗻𝘀) 𝘁𝗼 𝘁𝗵𝗲 𝘁𝗼𝗽 𝗼𝗳 𝘁𝗵𝗲𝗶𝗿 𝘀𝗰𝗼𝗽𝗲 𝗯𝗲𝗳𝗼𝗿𝗲 𝗰𝗼𝗱𝗲 𝗲𝘅𝗲𝗰𝘂𝘁𝗶𝗼𝗻. In simpler terms — during the compilation phase, JavaScript "scans" your code and allocates memory for variables and function declarations before executing it. That’s why you can use certain functions or variables before they’re defined in your code! 📘 𝗘𝘅𝗮𝗺𝗽𝗹𝗲: 𝗩𝗮𝗿𝗶𝗮𝗯𝗹𝗲 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴 console.log(myVar); // Output: undefined var myVar = 10; Behind the scenes, JavaScript treats this like: var myVar; // Declaration hoisted console.log(myVar); // undefined myVar = 10; // Initialization happens here ➡️ var is hoisted and initialized with undefined. However, if you use let or const, they’re hoisted too — but not initialized, leading to a ReferenceError if accessed before declaration. console.log(myLet); // ❌ ReferenceError let myLet = 20; ⚙️ 𝗘𝘅𝗮𝗺𝗽𝗹𝗲: 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴 sayHello(); // ✅ Works! function sayHello() { console.log("Hello, World!"); } ➡️ Function declarations are hoisted completely (both the name and definition). But function expressions are not fully hoisted: sayHi(); // ❌ TypeError: sayHi is not a function var sayHi = function() { console.log("Hi!"); }; 💡 𝗪𝗵𝘆 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴 𝗠𝗮𝘁𝘁𝗲𝗿𝘀 𝟭. 𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 𝗘𝘅𝗲𝗰𝘂𝘁𝗶𝗼𝗻 𝗖𝗼𝗻𝘁𝗲𝘅𝘁: Helps you reason about how JS interprets and runs your code. 𝟮. 𝗔𝘃𝗼𝗶𝗱 𝗕𝘂𝗴𝘀: Prevents confusion around “undefined” or “ReferenceError”. 𝟯. 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗔𝗱𝘃𝗮𝗻𝘁𝗮𝗴𝗲: Hoisting is a frequent JS interview question — understanding it deeply gives you an edge. 🧠 𝗧𝗼𝗽 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 #𝟮 Q: What is Hoisting in JavaScript, and how does it affect variable and function declarations? A: Hoisting is JavaScript’s behavior of moving declarations to the top of their scope before execution. var is hoisted and initialized with undefined. let and const are hoisted but not initialized (Temporal Dead Zone). Function declarations are fully hoisted, while function expressions are not. 🎯 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆𝘀 1. JavaScript hoists declarations, not initializations. 2. var behaves differently from let and const. 3. Function declarations can be used before they’re defined — but function expressions cannot. #JavaScript #Hoisting #WebDevelopment #InterviewPreparation #TechTips #JavaScriptInterviewQuestions
To view or add a comment, sign in
-
⚙️✨ Mastering Hoisting in JavaScript — The Hidden Execution Magic! Ever wondered how JavaScript seems to “know” about your functions and variables even before they’re written in the code? 🤔 That secret superpower is called Hoisting 🚀 Let’s break it down in a way you’ll never forget 👇 💡 What is Hoisting? Hoisting is JavaScript’s default behavior of moving all declarations (variables and functions) to the top of their scope before the code executes. 👉 In simple words: You can use functions and variables before declaring them (but with rules!). 🧠 How It Works Before your code runs, JavaScript goes through two phases: 1️⃣ Creation Phase: It scans the code and allocates memory for variables and functions. Variables declared with var are set to undefined. let and const are placed in a Temporal Dead Zone (TDZ) until initialized. Function declarations are fully hoisted (you can call them before definition). 2️⃣ Execution Phase: Code runs line by line. Variables and functions are assigned actual values. 🧩 Example 1 – Variable Hoisting console.log(a); // undefined var a = 10; console.log(b); // ❌ ReferenceError let b = 20; ✅ var is hoisted and initialized as undefined. ❌ let is hoisted but not initialized — accessing it before declaration causes an error. ⚡ Example 2 – Function Hoisting greet(); // ✅ Works! function greet() { console.log("Hello, World!"); } sayHi(); // ❌ Error var sayHi = function() { console.log("Hi there!"); }; ✅ Function declarations are fully hoisted. ❌ Function expressions (including arrow functions) behave like variables — not hoisted with values. 🧩 Quick Explanation: Hoisting means the declaration is moved to the top of its scope (not the initialization). TDZ (Temporal Dead Zone) — the time between hoisting and actual declaration, where access causes an error. var gets hoisted and initialized with undefined. let and const get hoisted but stay uninitialized until the declaration line is executed. Functions declared using function keyword are fully hoisted (you can call them before they are defined). 🪄 Example 3 – The Complete Picture console.log(x); // undefined var x = 5; hello(); // ✅ Works function hello() { console.log("Hello JS!"); } sayHi(); // ❌ Error let sayHi = () => console.log("Hi JS!"); 💬 In Short: 🧩 Hoisting means declarations are processed first, execution happens later. 🚀 Functions are hoisted completely, variables only partially. ⚠️ let and const live in the Temporal Dead Zone until declared. 💭 Pro Tip: Understanding hoisting helps you avoid confusing bugs and makes you a more confident JavaScript developer 💪 💻 JavaScript reads your code twice — first to hoist, then to execute! Once you master this concept, debugging becomes much easier 😎 #JavaScript #WebDevelopment #ReactJS #Frontend #CodingTips #LearnCoding #Programming #DeveloperJourney
To view or add a comment, sign in
-
JavaScript’s hidden magic tricks Did you know JavaScript secretly helps your primitives behave like objects? Ever wondered how this works? 👇 "hello".toUpperCase(); // "HELLO" (42).toFixed(2); // "42.00" true.toString(); // "true" Wait a second… A string, a number, and a boolean — all have methods? But these are primitive values, not objects! So how can they call methods like .toUpperCase() or .toFixed()? 💡 The Secret: Temporary Wrapper Objects When you try to access a property or method on a primitive, JavaScript automatically creates a temporary object — a process called autoboxing. Here’s what happens behind the scenes const str = "hello"; // Step 1: JavaScript wraps it const temp = new String(str); // Step 2: Calls the method on that temporary object const result = temp.toUpperCase(); // Step 3: Discards the wrapper temp = null; console.log(result); // "HELLO" So, "hello" behaves like an object for a moment — but it’s still a primitive! ✅ typeof "hello" → "string" ❌ "hello" instanceof String → false Why this matters It keeps primitives lightweight and fast. You can safely call methods on them. But don’t confuse them with their object counterparts created using new: const s = new String("hello"); // actual object typeof s; // "object" s instanceof String → true #JavaScript #Tricks
To view or add a comment, sign in
-
Why Did 5 + "5" Give You 55 🤓? Let’s Talk About JS Type Coercion This explanation is going to make you understand why [ ] == ![ ] is equal to true If you’ve ever typed 5 + "5" in JavaScript and got "55" instead of 10, don’t worry, you didn’t break anything. You just bumped into something called Type Coercion. It’s one of those sneaky but important concepts in JavaScript that can either save you or confuse you if you don’t understand how it works. Let’s break it down together in the simplest way. So, What Is Type Coercion? JavaScript is what we call a “loosely typed” language. This means it lets you mix and match data types (like strings, numbers, booleans), and it tries to convert them automatically when needed. This automatic conversion is known as Type Coercion. It happens all the time behind the scenes, sometimes in helpful ways, sometimes in surprising ones. Two Types: Implicit and Explicit There are two main types of coercion: Implicit coercion happens when JavaScript does the converting for you (without asking). Explicit coercion happens when you do the converting on purpose using methods like String(), Number(), or Boolean(). Let’s Look at Some Real Examples ✅ Here are a few common cases where coercion shows up: ✅ 5 + "5" → "55" (number becomes a string, because + with a string means concatenate) ✅ "10" - 3 → 7 (string becomes a number, because - only works with numbers) ✅ true + 1 → 2 (boolean true becomes 1) ✅ false == 0 → true (loose equality == allows coercion) ✅ null == undefined → true (but they’re not strictly equal!) ✅ [] + 1 → "1" (array becomes an empty string, then it's concatenated) ✅ [1] + 1 → "11" (array [1] becomes "1", then string + number = string) Understand how JavaScript behaves with different value types is very crucial for building effective and bug free scalable applications. But nevertheless, you wehther you know type Coercion or not, it's always better you take precautions. How to Keep Your Code Clean and Safe To avoid surprises, always try to use strict equality (===) instead of ==, because it checks both value and type. Also, manually convert data to the correct type when needed using Number(), String(), or Boolean(). This gives you more control and fewer headaches down the line. I hope you have learnt something.
To view or add a comment, sign in
-
-
Announcing Attractive.js, a new JavaScript-free JavaScript library This article was originally published on Rails Designer After last week's introduction of Perron, I am now announcing another little “OSS present”: a JavaScript-free JavaScript library. 🎁 Say what? 👉 If you want to check out the repo and star ⭐ it, that would make my day! 😊 Attractive.js lets you add interactivity to your site using only HTML attributes (hence the name attribute active). No JavaScript code required. Just add data-action and, optionally, data-target attributes to your elements, and… done! Something like this: <button data-action="addClass#bg-black" data-target="#door"> Paint it black </button> <p id="door"> Paint me black </p> Or if you want to toggle a CSS class, you write: data-action="toggleClass#bg-black". Or toggle multiple CSS classes: data-action="toggleClass#bg-black,text-white". Other actions include addAttribute, form#submit and copy#my-api-key. Attractive, right? 😅 I designed Attractive.js to be a little sister of Stimulus, hence the similar data-* https://lnkd.in/gifb59x9
To view or add a comment, sign in
-
Day:19 1. History of JavaScript * JavaScript was created in 1995 by Brendan Eich. * It was initially called Mocha, then Live Script, and finally JavaScript. * Developed for use in web browsers to make websites interactive. * Became a standard (ECMAScript) for cross-browser compatibility. 2. Increment and Decrement Increment (++): increases a variable’s value by one. Example: x++; // adds 1 to x Decrement (--): decreases a variable’s value by one. Example: x--; // subtracts 1 from x Can be prefix (++x) or postfix (x++)—the difference is when the value changes in an expression. 3. Variable and Constant Variable: stores data that can change. Declared using let or var. Constant: stores data that doesn't change. Declared using const. Example: let age = 18; (can be changed), const pi = 3.14; (cannot change value after assignment) 4. Data Types JavaScript has several data types: Number (e.g., 12, 3.14) String (e.g., "hello world") Boolean (true, false) Undefined (variable declared but not assigned) Null (explicitly set to no value) Object (arrays, objects, functions) Symbol (unique identifiers, ES6) 5. Alert, Prompt, Confirm alert("message") — shows a popup with a message. prompt("message") — asks user to input a value, returns what they type. confirm("message") — asks for OK/Cancel, returns true for OK, false for Cancel. 6. Concatenation Combining strings using + operator. Example: "Hello " + "World" gives "Hello World" Can also join numbers and strings: 5 + " apples" gives "5 apples" Quick examples:
To view or add a comment, sign in
-
In a Javascript L1 & L2 round the following questions can be asked from interviewer. Learn all ques for free on interviewdepth.com 1. What is the difference between 'Pass by Value' and 'Pass by Reference'? 2. What is the difference between map and filter ? 3. What is the difference between map() and forEach() 4. What is the difference between Pure and Impure functions? 5. What is the difference between for-in and for-of ? 6. What are the differences between call(), apply() and bind() ? 7. List out some key features of ES6 ? 8. What’s the spread operator in javascript ? 9. What is rest operator in javascript ? 10. What are DRY, KISS, YAGNI, SOLID Principles ? 11. What is temporal dead zone ? 12. Different ways to create object in javascript ? 13. Whats the difference between Object.keys,values and entries 14. Whats the difference between Object.freeze() vs Object.seal() 15. What is a polyfill in javascript ? 16. What is generator function in javascript ? 17. What is prototype in javascript ? 18. What is IIFE ? 19. What is CORS ? 20. What are the different datatypes in javascript ? 21. What are the difference between typescript and javascript ? 22. What is authentication vs authorization ? 23. Difference between null and undefined ? 24. What is the output of 3+2+”7” ? 25. Slice vs Splice in javascript ? 26. What is destructuring ? 27. What is setTimeOut in javascript ? 28. What is setInterval in javascript ? 29. What are Promises in javascript ? 30. What is a callstack in javascript ? 31. What is a closure ? 32. What are callbacks in javascript ? 33. What are Higher Order Functions in javascript ? 34. What is the difference between == and === in javascript ? 35. Is javascript a dynamically typed language or a statically typed language 36. What is the difference between Indexeddb and sessionstorage ? 37. What are Interceptors ? 38. What is Hoisting ? 39. What are the differences let, var and const ? 41. Differences between Promise.all, allSettled, any, race ? 42. What are limitations of arrow functions? 43. What is difference between find vs findIndex ? 44. What is tree shaking in javascrip 45. What is the main difference between Local Storage and Session storage 46. What is eval() 47. What is the difference between Shallow copy and deep copy 48. What are the difference between undeclared and undefined variables 49. What is event bubbling 50. What is event capturing 51. What are cookies 52. typeOf operator 53. What is this in javascript and How it behaves in various scenarios 54. How do you optimize the performance of application 55. What is meant by debouncing and throttling #javascriptdeveloper #reactjs #reactnative #vuejsdeveloper #angular #angulardeveloper
To view or add a comment, sign in
-
Have you ever tried sorting numbers in JavaScript and it just gives you nonsense? 😒 Like, you do [200, 100, 5].sort() and it returns [100, 200, 5] That’s because JavaScript, by default, sorts everything as strings, not actual numbers. So it’s basically going, “Hmm, 100 starts with a 1, that must come first.” To fix that and sort numbers properly in ascending order (smallest to biggest), just add a compare function: array.sort((a, b) => a - b) This basically tells JavaScript to compare each pair of values in the array by subtracting one from the other. If the result is negative, it means a is smaller than b, so JavaScript keeps a before b. If the result is positive, b is smaller, so it gets placed before a. And if the result is zero, it means they’re equal, and the order stays the same. This allows the sort method to arrange the numbers from smallest to largest unlike the default .sort() which treats numbers like strings and messes up the order. Now if you want to sort in descending order (biggest to smallest), just flip it: array.sort((a, b) => b - a) Sorting in descending order is especially useful when you're dealing with scores, prices, rankings, or anytime the biggest number should be on top. Once you understand what a and b are doing in that function, sorting becomes super easy and honestly, kind of satisfying. You can even write your own custom sort function which you can call anytime you want to sort anything in your program. Checkout my custom sort function in the image below and tell me what you think. I made it to work in thesame way as the sort() method. The code snippet will give you an understanding of what happens under the hood when you use the sort() method. Make sure you check it out. I hope you have learnt something from this post😃
To view or add a comment, sign in
-
-
Today I learned about two very important concepts in JavaScript --string and arrays. 1. STRINGS A strong is a sequence of characters used to represent text. eg: let str = "Vineet Nagar"; we can store text, numbers, or any characters inside it. (I) str.length: gives the total number of characters. (II) We can access any character using its index (like str[1] or str charAt(1).) => Common String Methods: (I) /n: moves text to a new line (II)\t: adds extra space or tab. (III)toUpperCase()/toLowerCase(): converts text to upper or lower case. (IV)trim(): removes extra spaces from the start and end. (V)slice(start, end): extracts a part of the string. (VI)concat(): joins two strings. (VII)replace(old, new): replaces a specific part of string . (VIII)charAt(index): returns the character at a given position. NOTE: Strings are immutable, meaning we can't directly change a specific character in them. 2. ARRAYS An array is a collection of items(numbers, strings, etc). eg: let arr = [96, 75, 48, 83, 66]; Each item has an index starting from 0. Unlike strings, arrays are mutable, so we can add, remove, or modify elements. => Common Array Methods: (I)push(): adds an element at the end. (II)pop(): removes the last element. (III)toString(): converts the array into a string. (IV)concat(): joins two arrays. (V)unshift(): adds an element at the beginning. (VI)shift(): removes the first element. (VII)slice(): returns a portion of the array. (VIII)splice(start, deletecount, newitem): removes and/or adds elements in between. NOTE: Arrays are mutable.
To view or add a comment, sign in
-
-
🚀 JavaScript Lesson: Understanding Hoisting Ever wondered why you can use a variable before it’s declared in JavaScript? That’s because of Hoisting — one of the most misunderstood concepts in JS! 🧠 What is Hoisting? Hoisting means JavaScript moves declarations (not assignments) to the top of their scope during the compilation phase. In simple terms — JS reads your code twice: First pass: Sets up memory for variables and functions. Second pass: Executes line by line. 🧩 1️⃣ var Hoisting Example console.log(a); // 👉 undefined var a = 10; console.log(a); // 👉 10 📝 Explanation: var a is hoisted to the top, but only the declaration, not the assignment. So, before assigning, a exists but has the value undefined. 🧩 2️⃣ let Hoisting Example console.log(b); // ❌ ReferenceError let b = 20; 📝 Explanation: let is also hoisted, but it stays in a Temporal Dead Zone (TDZ) — meaning you can’t access it before it’s declared. This protects you from accidental use of uninitialized variables. 🧩 3️⃣ const Hoisting Example console.log(c); // ❌ ReferenceError const c = 30; 📝 Explanation: Like let, const is hoisted but locked in the TDZ until its declaration line. It also must be initialized at the time of declaration. 🧩 4️⃣ Function Hoisting greet(); // ✅ Works! function greet() { console.log("Hello, Cognothink Community!"); } 📝 Explanation: Function declarations are fully hoisted — both name and body. That’s why you can call them before they’re defined. ⚡ Function Expressions (with var, let, or const) sayHi(); // ❌ Error var sayHi = function() { console.log("Hi!"); }; 📝 Explanation: This behaves like variable hoisting — only the variable name is hoisted, not the function itself.
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