🌱 Going back to basics In the last post, we explored how "call()", "apply()", and "bind()" can manually control what this refers to in Javascript. But what if we didn’t have to worry about "this" at all? That’s exactly where arrow functions make things simpler. The key difference between a regular function and an arrow function is this : 1. Regular functions define their own "this" (based on how they are called). 2. Arrow functions do not have their own "this", they simply inherit it from their surrounding scope. A short example : 1. regularFunction creates its own "this", so it points to user. 2. arrowFunction doesn’t! It looks outward (global scope), where "this" is undefined in "strict mode". Arrow functions simplify how we handle context by removing the need for "bind()", "call()", or "apply()", specially in modern functional code. By inheriting "this" lexically, they make context handling almost invisible!! everything just works naturally within the same scope. #JavaScript #Frontend
Ravi Shankar Pratihast’s Post
More Relevant Posts
-
Going back to basics 🌱 In my last post, we saw how "this" can get lost when a method is called separately. So let’s take that one step deeper today. What if we could manually tell Javascript what "this" keyword should point to? That is exactly what "call()" , "apply()", and "bind()" help us do. Lets see a below code example to understand "this" : "call()" : Calls immediately, pass arguments directly. "apply()": Calls immediately, but takes arguments as an "array". "bind()": Does not call right away , returns a "new function" with fixed "this". We use these when we need to control , specially in "callbacks" and "event handlers". There is still more to uncover!!! So now my question is, do "arrow functions" also behave the same way as "regular functions" when it comes to "this"? #Javascript #Frontend
To view or add a comment, sign in
-
-
Going back to basics 🌱 When you copy an object or array in Javascript are you really creating a new copy, or just another reference to the same memory? That’s where "Shallow Copy" and "Deep Copy" come into play. A "Shallow Copy" creates a new object, but only copies the top level properties "nested objects" or "arrays" are still linked by reference. So, if you change a nested value in the copied object,it also affects the original one. On the other hand, a "Deep Copy" creates a completely independent clone all "nested values" are copied as well. This means both the original and the copy live their own separate lives. Below I have added a simple example to show what is happening in both cases - // Shallow Copy Here, we used the "spread operator (...)" to copy the object but since it’s a shallow copy, the nested details object still points to the same reference. // Deep Copy Here, we used "JSON.parse(JSON.stringify())" to create a true clone, this process "breaks the reference", making both objects completely independent. I also got to know there are a few other ways to deep copy like using "structuredClone(obj)" a newer built in method in modern JS or "lodash.cloneDeep(obj)" for more complex structures , will read about them. #JavaScript #Frontend
To view or add a comment, sign in
-
-
💡 Why this JavaScript code works even without let — but you shouldn’t do it! function greet(i) { console.log("hello " + i); } for (i = 0; i < 5; i++) { greet(i); } At first glance, it looks fine — and yes, it actually runs without any error! But here’s what’s really happening 👇 🧠 Explanation: If you don’t declare a variable using let, const, or var, JavaScript (in non-strict mode) automatically creates it as a global variable named i. That’s why your code works — but it’s not a good practice! ✅ Correct and recommended way: for (let i = 0; i < 5; i++) { greet(i); } ⚠️ Why it’s important: -Without let, i leaks into the global scope (can cause bugs later). -In 'use strict' mode, this will throw an error: i is not defined. -let keeps i limited to the loop block — safer and cleaner! 👉 In short: -It works because JavaScript is lenient. -But always use let — it’s safer, cleaner, and professional. 👩💻 Many beginners get confused when this code still works without using let! ........understand these small but important JavaScript concepts 💻✨ #JavaScript #Frontend #WebDevelopment #CodingTips #LearnToCode #Developers
To view or add a comment, sign in
-
🚨 Understanding JavaScript Errors — A Developer’s Everyday Companion As JavaScript developers, we’ve all seen that scary red text in the console 😅 However, understanding why an error occurs is the key to writing cleaner, more predictable code. Here are the main types of JavaScript errors every developer should know 👇 🧩 1️⃣ Syntax Error Occurs when the code violates JavaScript syntax rules. Example: console.log("Hello World" (Missing closing parenthesis) 🔍 2️⃣ Reference Error Happens when trying to use a variable that doesn’t exist. Example: console.log(userName); // userName is not defined ⚙️ 3️⃣ Type Error Thrown when a value is of the wrong type. Example: let num = 5; num.toUpperCase(); // ❌ num is not a string 🚫 4️⃣ Range Error Occurs when a number or value is outside its allowed range. Example: let arr = new Array(-5); // ❌ invalid array length ⚡ 5️⃣ Eval Error Related to the eval() function (rarely used today — and not recommended). 💡 Pro Tip: Always handle errors gracefully using try...catch blocks, and make logging your best friend during debugging. Errors are not enemies — they’re feedback from the JavaScript engine helping us write better code. 💪 #JavaScript #WebDevelopment #Frontend #Programming #ErrorHandling #Debugging #DeveloperCommunity
To view or add a comment, sign in
-
🚀 How Closures Work in JavaScript — Explained Simply A closure is one of those concepts that seems confusing until it clicks. Here’s how I like to explain it 👇 A closure is created when a function remembers its lexical scope even after it’s executed outside that scope. function outer() { let counter = 0; return function inner() { counter++; console.log(counter); }; } const count = outer(); count(); // 1 count(); // 2 count(); // 3 Even though outer() has finished running, the inner() function still remembers the counter variable. That’s closure in action — the inner function “closes over” the variables from its parent scope. 💡 Real-world use cases: Data privacy (hiding variables) Function factories Maintaining state without global variables Once you understand closures, async JS and callbacks become much easier! 💪 #JavaScript #WebDevelopment #Closures #Frontend #CodingTips #JSDeveloper #LearnToCode
To view or add a comment, sign in
-
-
Today I explored how JavaScript executes inside the browser, and it was truly fascinating to understand the step-by-step process behind the scenes! 💡 Here’s what I learned 👇 🔹 The browser starts by loading the HTML and identifying any <script> tags. 🔹 Once found, the code is sent to the JavaScript Engine (like Chrome’s V8). 🔹 The engine performs three key steps — ✨ Parsing: Reads and converts code into an Abstract Syntax Tree (AST). ⚙️ Compilation (JIT): Translates JS into optimized machine code for faster execution. 🧩 Execution: Runs the code in the Call Stack, while variables and objects are managed in the Memory Heap. 🔹 For asynchronous operations (set Timeout, fetch, etc.), the Web APIs, Callback Queue, and Event Loop coordinate to ensure non-blocking execution. 💬 In short: HTML Parsing → JS Engine → Call Stack → Web APIs → Callback Queue → Event Loop → Execution Understanding this flow helps in writing efficient, optimized, and clean JavaScript code. Excited to continue learning and sharing my progress each day under the guidance of Sudheer Velpula Sir. 🙌 #JavaScript #WebDevelopment #Frontend #LearningJourney #Coding #SudheerSir
To view or add a comment, sign in
-
-
✨Day 3/28 Consistency Challenge ✨ ✍️My 4 Go-To JavaScript Heavy Hitter🚀: As a developer, there are a few JavaScript features I keep returning to because they solve common problems elegantly and efficiently. Here are my top four: ✅ DOM Manipulation: Mastering this is essential for any dynamic web experience. The event delegation changed the game for me in optimizing listeners! ✅ Array Methods (map, filter, reduce): The functional approach to data transformation. reduce() in particular is incredibly powerful for aggregating data into a single source of truth. ✅Arrow Functions (=>): More than just concise syntax; they provide lexical scoping of the this keyword, making asynchronous code cleaner and less error-prone. ✅ setTimeout & set Interval: Key to creating dynamic timing and non-blocking asynchronous operations within the browser environment. Understanding the Event Loop here is crucial! **What JS features do you rely on most in your day-to-day coding? Share below! 👇 #JavaScript #WebDevelopment #CodeEffeciently
To view or add a comment, sign in
-
💡 Understanding var, let, and const in JavaScript — A Must for Every Developer! When writing JavaScript, knowing how variables behave is crucial for clean and bug-free code. Here’s a quick breakdown 👇 🔹 var Scope: Function-scoped Hoisted: Yes (initialized as undefined) Re-declaration: Allowed ⚠️ Can cause unexpected results due to hoisting and re-declaration. 🔹 let Scope: Block-scoped ({ }) Hoisted: Yes (but not initialized — Temporal Dead Zone) Re-declaration: ❌ Not allowed in same scope ✅ Preferred for variables that can change. 🔹 const Scope: Block-scoped Hoisted: Yes (not initialized — Temporal Dead Zone) Re-declaration / Re-assignment: ❌ Not allowed ✅ Use for constants and values that never change. 🔍 Example: { var a = 10; let b = 20; const c = 30; } console.log(a); // ✅ Works (function-scoped) console.log(b); // ❌ Error (block-scoped) console.log(c); // ❌ Error (block-scoped) 🧠 Pro tip: Always prefer let and const over var for predictable and safer code. ✨ Which one do you use most often — let or const? Let’s discuss 👇 #JavaScript #WebDevelopment #Frontend #CodingTips #ES6
To view or add a comment, sign in
-
I was reading a book called Eloquent JavaScript, and the author brought up the dilemma of speed vs. elegance. Let me give a simple example to explain what I mean: imagine a function that calculates the factorial of a number N. If we write it recursively, it’s short and elegant, but in JavaScript, recursion costs about 3x more than a regular loop. Of course, a factorial implemented with a for loop would still be short and easy to read. So here’s the question: is the trade-off between elegance and efficiency actually relevant, or is it trivial? In general, we aim to write code that works and is easy to understand. Focusing too much on elegance or efficiency can be paralyzing. Think about it — if we only focus on elegance, we’ll eventually need to iterate over complex data structures and deal with nested loops, where recursion becomes impractical. But if we only focus on efficiency, our code can quickly become long and verbose. In the end, leaning too far to either side is never a good thing.
To view or add a comment, sign in
-
Today I learned about the origin of null in JavaScript and why it behaves the way it does. When JavaScript was created in 1995, the language needed a special value to show an intentional absence of data. For this purpose, null was introduced. It means: “There is no value here, and that is intentional.” However, during the early implementation, a mistake was made: typeof null returns "object" instead of the correct type. This happened because JavaScript’s first version stored values in a way that caused null to be misidentified. Even though it was a mistake, it could not be changed later, because many websites and applications had already started using it. Changing it would break existing code. So this behavior still continues today. 💡 Key Points null was created to represent intentional empty value. It has been part of JavaScript since the beginning. The typeof null === "object" result is a historic bug that remains for compatibility. null ≠ undefined undefined → value not assigned null → value intentionally set to empty 🚀 Why It’s Useful Understanding this helps developers avoid confusion, write cleaner code, and handle data more confidently. #JavaScript #WebDevelopment #LearningJourney
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
Well put. Once you understand lexical this, a lot of JS behavior starts making sense