💡 JavaScript Concept Every Developer Should Understand — this One concept that often confuses beginners in JavaScript is the this keyword. A simple way to understand it is by remembering 4 basic rules. 🚀 The 4 Rules of this in JavaScript 1️⃣ Global Context Rule If this is used outside any function, it refers to the global object. In browsers, the global object is window. console.log(this); Output: Window {. . .} So here: this → window 2️⃣ Object Method Rule When a function is called using an object, this refers to that object. const person = { name: "Rahul", greet: function() { console.log(this.name); } }; person.greet(); Execution: person.greet() So: this → person Output: Rahul 3️⃣ Normal Function Rule If a function is called normally (not through an object), this refers to the global object (window) in browsers. function show() { console.log(this); } show(); Execution: show() So: this → window 4️⃣ Arrow Function Rule Arrow functions do not create their own this. They inherit this from the surrounding scope. const obj = { value: 10, show: function() { const arrow = () => { console.log(this.value); }; arrow(); } }; obj.show(); Here: this → obj Output: 10 🧠 Simple way to remember GLOBAL SCOPE │ ├── Normal function → this = window │ OBJECT METHOD │ ├── this = object │ ARROW FUNCTION │ └── this = inherited from parent #JavaScript #WebDevelopment #CodingConcepts #FrontendDevelopment #LearnToCode
Understanding JavaScript's 'this' Keyword
More Relevant Posts
-
🔥 Regular Function vs Arrow Function in JavaScript — what's the real difference? This confused me when I started. Here's everything you need to know 👇 ━━━━━━━━━━━━━━━━━━━━━━━━━━ 1. The syntax is different Regular functions use the function keyword. Arrow functions use a shorter ( ) => syntax — less typing, cleaner code. 2. The "this" keyword behaves differently This is the BIG one. 📌 Regular function → has its own this. It changes depending on HOW the function is called. 📌 Arrow function → does NOT have its own this. It borrows this from the surrounding code. That's why arrow functions are great inside classes and callbacks — they don't lose track of this. 3. Arrow functions can't be used as constructors You can do new regularFunction() — works fine. You can NOT do new arrowFunction() — it throws an error. 4. Arguments object Regular functions have a built-in arguments object to access all passed values. Arrow functions don't — use rest parameters (...args) instead. ━━━━━━━━━━━━━━━━━━━━━━━━━━ ✅ When to use which? → Use arrow functions for short callbacks, array methods (.map, .filter), and when you need to keep this from the outer scope. → Use regular functions when you need your own this, use as a constructor, or need the arguments object. Understanding this = leveling up as a JavaScript developer 🚀 #JavaScript #WebDevelopment #100DaysOfCode #Frontend #CodingTips #Programming
To view or add a comment, sign in
-
This article provides a comprehensive step-by-step guide on creating a barcode generator using JavaScript, which is essential for developers working on inventory systems and internal tools. I found it interesting that the author breaks down the process so clearly, making it accessible even for those new to JavaScript. What barcode-related projects are you currently working on, or have you found similar tools useful in your past experiences?
To view or add a comment, sign in
-
🤯 Why does JavaScript sometimes feel so confusing? Honestly, this doesn’t just happen to beginners. Even experienced developers get surprised by JavaScript from time to time 👨💻 Take this simple example 👇 "11" + 1 // "111" "11" - 1 // 10 At first glance, both lines look almost the same. But JavaScript treats them differently. 👉 In the first line, it joins the values as text, so the result becomes ""111"". 👉 In the second line, it converts the value into a number, so the result becomes "10". Same input. Different result. And that’s exactly where the confusion starts 😅 Here’s another common one 👇 0 == "0" // true 0 === "0" // false 👉 "==" checks only the value 👉 "===" checks both the value and the type That’s why most developers prefer "===" ✅ And this one surprises a lot of people 👇 Boolean("0") // true Boolean([]) // true Boolean(0) // false 👉 The string ""0"" is true 👉 An empty array is also true 👉 But the number "0" is false JavaScript is incredibly powerful 💻 But sometimes it’s so flexible that it creates bugs in places you least expect 🐛 A simple rule I follow: ✔ Always use "===" ✔ Convert types explicitly ✔ Don’t rely too much on automatic conversions ✔ Use entity["software","TypeScript"] in larger projects for safer code JavaScript isn’t broken. Sometimes it just tries to be a little too smart 😄 💬 What’s the most confusing JavaScript behavior you’ve ever come across? Drop it in the comments 👇 🔖 Save this post for your next debugging session 🤝 Share it with a developer friend who needs this #JavaScript #WebDevelopment #Programming #Frontend #Developer #CodingLife
To view or add a comment, sign in
-
-
*🚀 JavaScript Hoisting* Hoisting is one of the most confusing but important concepts in JavaScript. 👉 Hoisting is JavaScript's behavior of moving declarations to top of their scope during execution. React Virtual Dom vs Real Dom Tutorial: i found this Video on Youtube may be this can help you!! https://lnkd.in/d-nGsVTE *🔹 1. What Gets Hoisted?* - var: Hoisted, initialized as undefined - let: Hoisted, not initialized (TDZ) - const: Hoisted, not initialized (TDZ) - function: Fully hoisted *🔹 2. Variable Hoisting (var)* console.log(x); var x = 5; 👉 Output: undefined 👉 Behind the scenes: var x; console.log(x); // undefined x = 5; *🔹 3. let & const Hoisting (TDZ)* console.log(a); let a = 10; 👉 Output: ReferenceError 👉 Why? Because of Temporal Dead Zone (TDZ) 👉 Variable exists but cannot be accessed before declaration *🔹 4. Function Hoisting* ✅ Function Declaration (Fully Hoisted) greet(); function greet(){ console.log("Hello"); } 👉 Works perfectly ❌ Function Expression (Not Fully Hoisted) greet(); var greet = function(){ console.log("Hello"); } 👉 Output: TypeError: greet is not a function *🔹 5. Temporal Dead Zone (TDZ)* 👉 Time between: Variable hoisted Variable declared During this time → ❌ cannot access variable { console.log(x); // ❌ Error let x = 5; } *🔹 6. Common Mistakes* ❌ Using variables before declaration ❌ Confusing var with let ❌ Assuming all functions behave the same *⭐ Most Important Points* ✅ var → hoisted with undefined ✅ let/const → hoisted but in TDZ ✅ Function declarations → fully hoisted ✅ Function expressions → not fully hoisted *🎯 Quick Summary* - JavaScript moves declarations up, not values - var → usable before declaration (but undefined) - let/const → cannot use before declaration - Functions → behave differently based on type *Double Tap ❤️ For More*
To view or add a comment, sign in
-
🌟 Understanding Callback Functions in JavaScript 🌟 Callback functions are functions passed as arguments to another function to be executed later. They are essential for handling asynchronous operations like fetching data or handling events in JavaScript. For developers, mastering callback functions is crucial for writing efficient, responsive, and scalable code in modern web development. Here's a basic breakdown: 1️⃣ Define the main function and include parameters for the callback function. 2️⃣ Inside the main function, call the callback function at the appropriate time. 3️⃣ Write the callback function outside the main function with necessary logic. ```javascript function mainFunction(callback) { // Main function logic here callback(); // Callback function call } function callbackFunction() { // Callback function logic here } mainFunction(callbackFunction); // Calling the main function ``` Pro Tip: Use arrow functions for cleaner syntax when defining callback functions. Common Mistake Alert: Forgetting to invoke the callback function within the main function will result in the callback not being executed. 🤔 What's your favorite use case for callback functions in your projects? 🌐 View my full portfolio and more dev resources at tharindunipun.lk #JavaScript #WebDevelopment #CallbackFunctions #AsynchronousProgramming #JSProTips #DeveloperCommunity #CodingBeginners #TechSkills
To view or add a comment, sign in
-
-
🧠 Day 13 — Class vs Prototype in JavaScript (Simplified) JavaScript has both Classes and Prototypes — but are they different? 🤔 --- 🔍 The Truth 👉 JavaScript is prototype-based 👉 class is just syntactic sugar over prototypes --- 📌 Using Class (Modern JS) class Person { constructor(name) { this.name = name; } greet() { console.log(`Hello ${this.name}`); } } const user = new Person("John"); user.greet(); // Hello John --- 📌 Using Prototype (Core JS) function Person(name) { this.name = name; } Person.prototype.greet = function () { console.log(`Hello ${this.name}`); }; const user = new Person("John"); user.greet(); // Hello John --- 🧠 What’s happening? 👉 Both approaches: Create objects Share methods via prototype Work almost the same under the hood --- ⚖️ Key Difference ✔ Class → Cleaner, easier syntax ✔ Prototype → Core JavaScript mechanism --- 🚀 Why it matters ✔ Helps you understand how JS works internally ✔ Useful in interviews ✔ Makes debugging easier --- 💡 One-line takeaway: 👉 “Classes are just a cleaner way to work with prototypes.” --- #JavaScript #Prototypes #Classes #WebDevelopment #Frontend #100DaysOfCode
To view or add a comment, sign in
-
🚀 Understanding Global Execution Context in JavaScript Have you ever wondered what happens behind the scenes when a JavaScript program starts running? Behind the scenes, JavaScript doesn’t just run your code directly… it first creates a special environment responsible for managing memory and executing code. That is called Execution context. There are 3 types of Execution Contexts: 1) Global Execution Context: 2) Function Execution Context: 👉 Created every time a function is called. Each function gets its own separate execution context It contains: >> Local variables >>Function arguments >>Scope information 👉 Important: If you call a function 5 times → ✔️ 5 different execution contexts are created. 3) Eval Execution Context (Rare ⚠️) 👉 Created when using eval() eval("console.log('Hello')"); >> Rarely used in real projects >> Not recommended (security + performance issues. What is the Global Execution Context? The Global Execution Context is the default environment where JavaScript code begins execution. Whenever a JavaScript program runs, the engine first creates the Global Execution Context. What does the Global Execution Context contain? 1️⃣ Global Object: ->In browsers, the global object is window. 2️⃣ this keyword: ->At the global level, this refers to the global object. 3️⃣ Memory for variables and functions: ->JavaScript allocates memory for variables and functions before executing the code. JavaScript runs code in two phases 1️⃣ Memory Creation Phase: ->Variables are stored with the value undefined ->Functions are stored entirely in memory 2️⃣ Code Execution Phase: ->JavaScript executes the code line by line ->Variables receive their actual values Example: var name = "JavaScript"; function greet() { console.log("Hello")} greet(); Before execution, JavaScript stores: name → undefined greet → function Then the code runs line by line. 💬 Question: How many Execution Contexts can exist at the same time in JavaScript? #JavaScript #WebDevelopment #Programming #FrontendDevelopment
To view or add a comment, sign in
-
addEventListener in JavaScript – Complete Guide Handling user interactions is a core part of modern web development. The addEventListener() method allows developers to attach event handlers to HTML elements in a clean and flexible way. In this tutorial, you will learn: • What addEventListener() is • How it works with different events • Real examples with click and keyboard events • Removing event listeners properly • Best practices developers should know If you're learning JavaScript or preparing for frontend interviews, this guide will be helpful. 🔗 Read the article: https://lnkd.in/gwYibxEz #JavaScript #FrontendDevelopment #WebDevelopment #Programming #Coding #SoftwareDevelopment
To view or add a comment, sign in
-
🚀 Higher-Order Functions in JavaScript — A Must-Know Concept! 💡 What is a Higher-Order Function? A function is called a Higher-Order Function if it: ✔️ Takes another function as an argument ✔️ Returns a function as its result 🔍 Simple Example: function greet(name) { return `Hello, ${name}`; } function processUserInput(callback) { const name = "Jake"; return callback(name); } console.log(processUserInput(greet)); 👉 Here, processUserInput is a Higher-Order Function because it accepts greet as a callback. ⚡ Why are Higher-Order Functions powerful? ✅ Code reusability ✅ Cleaner and more readable code ✅ Helps in functional programming ✅ Widely used in JavaScript methods like: array.map(), array.filter(), array.reduce() 🔥 Interview Twist: function multiplier(factor) { return function (number) { return number * factor; }; } const double = multiplier(2); console.log(double(5)); // ? 🧠 Output: 10 👉 Because multiplier returns another function — classic Higher-Order Function! 🔥 The Important Concept: Closure Even though multiplier execution is finished, the inner function still remembers factor. This is called a closure: "A function remembers variables from its outer scope even after that outer function has finished executing." #JavaScript #WebDevelopment #Frontend #CodingInterview #Developers
To view or add a comment, sign in
-
🚀 JavaScript Developers: Understanding the Difference Between `map()`, `forEach()`, and `for` Loops When working with arrays in JavaScript, there are several ways to iterate over data. The most common ones are `map()`, `forEach()`, and the traditional `for` loop. Although they may look similar, they serve different purposes. --- 📌 for Loop The traditional `for` loop gives you full control over the iteration. • You define the start and end of the loop • You can use `break` or `continue` • Useful for complex logic or performance-sensitive operations Example: const numbers = [1, 2, 3, 4]; for (let i = 0; i < numbers.length; i++) { console.log(numbers[i]); } --- 📌 forEach() `forEach()` is used when you want to execute an action for each element in an array. • Runs a function for every element • Does not return a new array • Commonly used for side effects like logging or triggering functions Example: const numbers = [1, 2, 3, 4]; numbers.forEach(num => { console.log(num); }); --- 📌 map() `map()` is used when you want to transform data and return a new array. • Applies a transformation to every element • Returns a new array Example: const numbers = [1, 2, 3, 4]; const doubled = numbers.map(num => num * 2); console.log(doubled); // [2, 4, 6, 8] --- 💡 Simple rule to remember • Use map() when you want a new transformed array • Use forEach() when you want to execute something for each item • Use for loops when you need more control over the loop Understanding these differences helps you write cleaner and more readable JavaScript code. 👨💻 Which one do you use the most in your projects? #JavaScript #WebDevelopment #Frontend #Programming #Developers #ReactJS
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