Everyone reads about ".call()", ".bind()", ".apply()" But the real confusion is: 👉 Where do we actually use them? A simple example from real code: const user = { name: "Jayhind" }; function greet() { console.log("Hello " + this.name); } Now imagine this function is reused somewhere else: const anotherUser = { name: "Rahul" }; greet.call(anotherUser); // Hello Rahul 👉 Here ".call()" helps us control "this" dynamically --- Now ".bind()": const greetRahul = greet.bind(anotherUser); greetRahul(); // Hello Rahul 👉 Useful when you want to store function with fixed context --- Real-world use case: class Service { constructor() { this.name = "API Service"; } log() { console.log(this.name); } } const service = new Service(); setTimeout(service.log, 1000); // undefined ❌ setTimeout(service.log.bind(service), 1000); // API Service ✅ 👉 This is where ".bind()" actually matters --- One simple way to remember: - ".call()" → run function immediately with context - ".apply()" → same as call, but args in array - ".bind()" → return new function with fixed context Most tutorials explain syntax. Real understanding comes from where it breaks. #JavaScript #NodeJS #CallBindApply #BackendDevelopment #JSConcepts
JavaScript Call Bind Apply Use Cases Explained
More Relevant Posts
-
🧩 Demystifying the Node.js Event Loop: It's Not Just One Thread! Ever wondered what actually happens when you call setTimeout(() => {}, 1000)? Most people say "Node is single-threaded," but that’s only half the story. Here is the visual breakdown of how Node.js orchestrates asynchronous magic using libuv: 1. The Handoff (Main Thread) When you set a timer, the Main JS thread (V8) doesn't wait. It registers the callback and duration with libuv and moves on to the next line of code. 2. The Engine Room (libuv) This is where the heavy lifting happens. libuv maintains a Min-Heap—a highly efficient data structure that sorts timers by their expiration time. It puts the thread to "sleep" using OS-level polling (like epoll or kqueue) until the nearest timer is ready. 3. The Queue & The Tick Once the time arrives, libuv moves your callback into the Callback Queue. But it doesn't run yet! The Event Loop must cycle back to the "Timers Phase" to pick it up. ⚠️ The "Golden Rule" of Node.js Don't block the loop. If you run a heavy synchronous operation (like a massive while loop), the Event Loop gets stuck. Even if your timer has expired in the background, the Main Thread is too busy to check the queue. This is why a setTimeout(cb, 100) might actually take 5 seconds to fire if your main thread is congested. Key Takeaway: Node.js is fast because it offloads waiting to the OS via libuv, keeping the main thread free for execution. Keep your synchronous tasks light, and let the loop do its job! 🌀 #NodeJS #WebDevelopment #SoftwareEngineering #Backend #Javascript #ProgrammingTips
To view or add a comment, sign in
-
I was repeating the same logic in every component… and it started getting messy 😅 Yes, seriously. For a long time, I was doing this in React: useEffect(() => { fetchData(); }, []); const [data, setData] = useState(); const [loading, setLoading] = useState(false); Same pattern… in multiple components ❌ ⚠️ This caused: • Code duplication • Hard-to-maintain components • Bigger, messy files 💡 Then I changed my approach: Instead of repeating logic everywhere, 👉 I created a custom hook 🧠 Example: useFetch(url) Handles: • API call • Loading state • Error handling ✅ Result: • Cleaner components • Reusable logic • Easier maintenance 🔥 What I learned: If you’re repeating the same logic… you’re probably missing a custom hook. #ReactJS #FrontendDeveloper #JavaScript #CodingTips #WebDevelopment
To view or add a comment, sign in
-
🚀 map() vs. forEach(): Do you know the difference? The Hook: One of the first things we learn in JavaScript is how to loop through arrays. But using the wrong method can lead to "hidden" bugs that are a nightmare to fix. 🛑 🔍 The Simple Difference: ✅ .map() is for Creating. Use it when you want to take an array and turn it into a new one (like doubling prices or changing names). It doesn't touch the original data. ✅ .forEach() is for Doing. Use it when you want to "do something" for each item, like printing a message in the console or saving data to a database. It doesn't give you anything back. 💡 Why should you care? 1. Clean Code: .map() is shorter and easier to read. 2. React Friendly: Modern frameworks love .map() because it creates new data instead of changing the old data (this is called Immutability). 3. Avoid Bugs: When you use .forEach() to build a new list, you have to create an empty array first and "push" items into it. It’s extra work and easy to mess up! ⚡ THE CHALLENGE (Test your knowledge! 🧠) Look at the image below. Most developers get this wrong because they forget how JavaScript handles "missing" returns. What do you think is the output? A) [4, 6] B) [undefined, 4, 6] C) [1, 4, 6] D) Error Write your answer in the comments! I’ll be replying to see who got it right. 👇 #JavaScript #JS #softwareEngineer #CodingTips #LearnToCode #Javascriptcommunity #Programming #CleanCode #CodingTips
To view or add a comment, sign in
-
-
𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 𝘁𝗵𝗲 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽 JavaScript runs one thing at a time. One slow task freezes your screen. You wonder how apps stay fast. The Event Loop solves this. It manages three main parts. - Call Stack: Runs your code line by line. - Web APIs: Handles timers and API calls. - Queues: Holds callbacks until they run. Queues have levels. - Microtasks: Promises. These have high priority. - Macrotasks: Timers and DOM events. These have low priority. How it works. 1. Sync code runs on the stack. 2. Async tasks move to Web APIs. 3. Finished tasks move to queues. 4. The Event Loop waits for the stack to empty. 5. It pushes microtasks first. 6. It pushes macrotasks last. Look at this example. console.log(Start) setTimeout(Timeout, 0) Promise.then(Promise) console.log(End) The output is: Start End Promise Timeout Why? Start and End run first. The Promise is a microtask. It runs next. The timeout is a macrotask. It runs last. A common mistake is thinking setTimeout 0 runs immediately. It does not. It waits for the stack to empty. It waits for all microtasks to finish. This logic stops async bugs. Understand the loop to write better code. Source: https://lnkd.in/gjBYnFZB
To view or add a comment, sign in
-
Why is my code running "out of order"? (Eager vs. Lazy Evaluation) Ever passed a function as an argument and wondered why it executed before the function it was passed into? Look at this common "gotcha": javascript const main = (fn) => { console.log("start"); fn(); console.log("end"); }; const createLogger = (msg) => { console.log("start logger"); return () => console.log(msg); }; // ❌ Unexpected Order: "start logger" -> "start" -> "success" -> "end" main(createLogger("success")); Use code with caution. What’s happening? This is Eager Evaluation. In JavaScript, arguments are evaluated immediately before the outer function runs. Because we used parentheses () on createLogger, JS executes it first to find out what value to give to main. It’s like cooking a 5-course meal before your guests even knock on the door! 🥘 The Fix: Lazy Evaluation 💤 If we want main to control the timing, we need to wrap our logic in a "thunk" (a wrapper function). This tells JS: "Don't run this yet; run it only when I call it." javascript // ✅ Correct Order: "start" -> "start logger" -> "success" -> "end" main(() => createLogger("success")()); Use code with caution. Why does this matter in Node.js? Understanding this distinction is huge for: ✅ Middleware: Deciding when a request starts/ends. ✅ Performance: Avoiding expensive calculations unless they are actually needed. ✅ Closures: Controlling scope and execution timing. Stop executing, start referencing! 🚀 #JavaScript #WebDevelopment #NodeJS #CodingTips #SoftwareEngineering
To view or add a comment, sign in
-
-
𝗖𝗮𝗹𝗹𝗯𝗮𝗰𝗸𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: 𝗪𝗵𝘆 𝗧𝗵𝗲𝘆 𝗘𝘅𝗶𝘀𝘁 JavaScript handles one task at a time. Some tasks are slow. Fetching data or reading files takes time. You do not want your app to stop. Callbacks solve this. A callback is a function. You pass it as an argument to another function. The first function runs the callback when the task finishes. Common uses: - Timers - Button clicks - Array methods Functions are first-class objects. You pass them like strings or numbers. Deeply nested callbacks cause a problem. This is called callback hell. It makes code hard to read. Modern JS uses Promises and async/await to fix this. Source: https://lnkd.in/gQwDbR9q
To view or add a comment, sign in
-
🚨 JavaScript Gotcha: Objects as Keys?! Take a look at this 👇 const a = {}; const b = { key: 'b' }; const c = { key: 'c' }; a[b] = 123; a[c] = 456; console.log(a[b]); // ❓ 👉 What would you expect? 123 or 456? 💡 Actual Output: 456 🤯 Why does this happen? In JavaScript, object keys are always strings or symbols. So when you use an object as a key: a[b] → a["[object Object]"] a[c] → a["[object Object]"] Both b and c are converted into the same string: "[object Object]" ⚠️ That means: a[b] = 123 sets " [object Object] " → 123 a[c] = 456 overwrites it → 456 So finally: console.log(a[b]); // 456 🧠 Key Takeaways ✅ JavaScript implicitly stringifies object keys ✅ Different objects can collide into the same key ❌ Using objects as keys in plain objects is unsafe 🔥 Pro Tip If you want to use objects as keys, use a Map instead: const map = new Map(); map.set(b, 123); map.set(c, 456); console.log(map.get(b)); // 123 ✅ ✔️ Map preserves object identity ✔️ No unexpected overwrites 💬 Final Thought JavaScript often hides complexity behind simplicity. Understanding these small quirks is what separates a developer from an expert. #JavaScript #WebDevelopment #FrontendDevelopment #Programming #Coding #JavaScriptTips #JSConfusingParts #DevelopersLife #CodeNewbie #LearnToCode #SoftwareEngineering #TechTips #CodeQuality #CleanCode #100DaysOfCode #ProgrammingTips #DevCommunity #CodeChallenge #Debugging #JavaScriptDeveloper #MERNStack #FullStackDeveloper #ReactJS #NodeJS #WebDevTips #CodingLife
To view or add a comment, sign in
-
-
You know what is great? Developing a Rails application using importmaps instead of JS build pipeline. But if you know me, you know I like some linting and formatting. So it doesn't feel great to having to include a package manager and runtime just to lint and format any JS files in the project. Thats I created a gem to wrap the stand alone biome.js cli tool. Now you can have access to JS linting and formatting (As well as JSON, CSS, and others), in each dev's environment as well as in CI. https://lnkd.in/gFcvK4TM https://lnkd.in/gYB49Nsf
To view or add a comment, sign in
-
🏗️ Constructor Functions (Before Classes) Before class existed in JavaScript, developers used this: function User(name) { this.name = name; } User.prototype.sayHi = function () { console.log(this.name); }; const user1 = new User("Ahmed"); At first, it looks old… but it teaches something powerful. 💡 What’s really happening: user1 = { name: "Ahmed", __proto__: User.prototype } 🔥 Key idea: 👉 Methods are stored in prototype 👉 All instances share them So instead of duplicating functions in memory… ✔ One function ✔ Shared across all objects 🧠 Why this matters: This is the real foundation behind: Classes Inheritance Object behavior in JS 🚀 My takeaway: Constructor functions may look outdated… but they reveal how JavaScript actually works. And once you understand them, classes become much clearer. #JavaScript #OOP #WebDevelopment #Frontend
To view or add a comment, sign in
-
🚫 Stop using JSON.parse(JSON.stringify()) for deep cloning! It’s slow, breaks Dates, Maps, undefined, and more. Modern JS has better options like structuredClone(). If you're still using the old way in Angular or JS apps, you're risking bugs & performance issues. Read the blog & upgrade your approach 👇 #Angular #JavaScript #WebDevelopment #Frontend #CodingTips #Performance
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
#node