Call, Apply, or Bind? 🚀 Mastering the "this" context in JavaScript Ever wondered how to borrow methods or control the this keyword in JavaScript? These three methods are essential for every JS developer's toolkit. Here’s a quick breakdown: 📞 .call(): Invokes the function immediately. Arguments are passed individually. fullName.call(personObject, "Hyderabad", "Telangana"); 📧 .apply(): Invokes the function immediately. Arguments are passed as an Array. fullNameWithAddress.apply(personObject2, ["Bangalore", "Karnataka", "India"]); 🔗 .bind(): Does not invoke the function immediately. It returns a new function with the context locked in, which you can call later. let bindMethod = fullNameWithAddresBind.bind(personObject3, "Chennai", "Tamilnadu"); bindMethod(); The Key Difference? It’s all about how you handle arguments and execution timing. Use call for speed, apply when working with arrays (like math operations), and bind for event listeners or delayed execution. Check out my code snippets below to see them in action! 👇 let personObject = { firstName: "Santha Kumar", lastName: "Chigurupati", } let fullName = function (city, state) { console.log(this.firstName + " " + this.lastName + " " + city + " , " + state); } // CALL fullName.call(personObject, "Hyderabad", "Telangana"); let personObject2 = { firstName: "Saahus Neal", lastName: "Chigurupati", } let fullNameWithAddress = function(city, state, country) { console.log(this.firstName + " " + this.lastName + " " + city + " " + state + " " + country) } // APPLY fullNameWithAddress.apply(personObject2, ["Banglore", "Karnataka", "India"]) let personObject3 = { firstName: "Suhaas Neal", lastName: "Chigurupati", } let fullNameWithAddresBind = function(city, state, country, profession) { console.log(this.firstName + " " + this.lastName + " " + city + " " + state + " " + country + " " + profession) } //BIND let bindMethod = fullNameWithAddresBind.bind(personObject3, "Chennai", "Tamilnadu", "India", "Artist"); bindMethod() #JavaScript #WebDevelopment #CodingTips #Frontend #Programming #JSFundamentals
Santha Kumar Chigurupati’s Post
More Relevant Posts
-
Symbols were the way to create private fields in JavaScript before private fields were a standard language feature. And in some cases, they're still the best option out there for performance purposes. How do they work? Instead of creating a regular string like "my-key", you create a symbol like `Symbol("my-key")`. The value that `Symbol` returns is unique, meaning that `Symbol("my-key") !== Symbol("my-key")`. This means that a developer can't access your class field using `obj[Symbol("my-key")]`. Rather, only those who have a reference to the uniquely-created symbol can access the field. Consider this code: const key = Symbol("my-key"); obj[key] = "value"; // ... export { obj }; Here, we export `obj`, but not `key`, meaning only we have the ability to read and write the value (kind of). The `ws` Node.js package has been using this clever approach for a long time. Since private fields are a native feature in JS now, there usually isn't a reason to take this approach. However, you might still find it useful when making Custom Elements, or other kinds of classes that need to use event listeners (e.g., in Node). If you remember, I made a post wayyyyyy back explaining how static event listeners provide the best performance in JavaScript. Of course, static event listeners prevent you from accessing `this`. And if you need access to a private field in your event listener, you'll be forced to use `this#key` and lose the performance boost. This is where Symbols shine! Instead of accessing private data through `this#key`, you can access it through `instance[symbolKey]`! As long as you have access to the symbol in your class's file, you'll be able to access data that the rest of the outside world can't (kind of). If you've been catching my "kind of"s, there's a caveat here: JS gives developers a way to inspect all of an object's Symbols. Generally speaking, most developers don't know about the existence of the global function that allows this, and many don't even know about Symbols at all. Plus, Symbol-based properties don't show up in IDE IntelliSense as devs type. So Symbol-based fields are semi-private! Nonetheless, Symbol-based properties are not "perfectly private". You might still choose to use them for performance purposes. But the adventurous devs who love scrutinizing code to find and use the `_DO_NOT_USE` properties will still be able to have their way. As with all things, this is about trade-offs. In my Combobox component, I've mostly been using private fields. But I've reached for Symbols in cases where I really wanted to keep using static event handlers. ComboBoxedIn Logs #17 (No, I haven't forgotten about these.)
To view or add a comment, sign in
-
𝗕𝗲𝘀𝘁 𝗝𝗮𝘃𝗮𝘀𝗰𝗿𝗶𝗽𝘁 𝗙𝗿𝗮𝗺𝗲𝘄𝗼𝗿𝗸𝘀 𝗳𝗼𝗿 𝗕𝗲𝗴𝗶𝗻𝗻𝗲𝗿𝘀 𝗶𝗻 𝟮𝟬𝟮𝟲 Starting with JavaScript is just the first step. Frameworks feel complicated next. This guide cuts through the noise. It shows you which tools to learn first in 2026 and why. Frameworks handle repetitive code. They let you build features faster. Over 70% of developers use one daily. Picking the right one saves you months of frustration. Look for these traits as a beginner: - Easy first project setup - Clear documentation - Helpful community - Good performance - Path to a job Here are the top choices. **React** Backed by Meta. Component-based, like Lego for UI. Huge job market. Setup: `npx create-react-app` or use Vite. Simple counter example: ```javascript import { useState } from "react"; function Counter() { const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ); } ``` Pros: Massive ecosystem, many jobs. Cons: Needs extra tools for routing, hooks have a learning curve. Netflix uses React. Server tweaks cut their load times by 30%. **Vue** Progressive and flexible. Easy to add to any project. Great docs. Setup: `npm init vue@latest`. Todo list example: ```vue <script setup> import { ref } from "vue"; const items = ref([]); const newItem = ref(""); function addItem() { if (newItem.value) { items.value.push(newItem.value); newItem.value = ""; } } </script> <template> <input v-model="newItem" @keyup.enter="addItem" placeholder="Add todo" /> <ul> <li v-for="item in items" :key="item">{{ item }}</li> </ul> </template> ``` Pros: Lightweight, reactive system. Cons: Smaller ecosystem than React. Alibaba uses Vue. It sped up their development by 50%. **Svelte** Compiles to tiny, fast vanilla JS. Minimal code. Feels natural. Setup: `npm create svelte@latest`. Reactive example: ```html <script> let name = 'world'; $: greeting = `Hello ${name}!`; </script> <input bind:value={name} /> <p>{greeting}</p> ``` Pros: Blazing speed, no virtual DOM. Cons: Smaller library selection. The New York Times uses Svelte. Slashed load times by 40%. **Next.js** React with built-in server features. Great for full apps. Setup: `npx create-next-app@latest`. Server component example: ```javascript async function Home() { const data = await fetch("https://api.example.com").then(res => res.json()); return <div>{data.message}</div>; } ``` Pros: Easy deploying, fast builds. Cons: Must learn React first. TikTok uses it for enterprise scale. **Angular** Full framework from Google. TypeScript-based. Highly structured. Setup: `ng new my-app`. Component with signal: ```typescript import { Component, signal } from "@angular/core"; @Component({ selector: "app-greeting", template: `<h1>Hello {{ message() }}!</h1>`, }) export class Gr
To view or add a comment, sign in
-
I used to manipulate objects directly in JavaScript. Until one day, it didn't work. And the errors were almost impossible to trace. Meanwhile JavaScript has built a clean, deliberate API specifically for the job I had been doing messily for a long time. What is Reflect? Reflect is a built-in JavaScript object that provides a set of methods for performing fundamental operations on objects. The same operations you've always done, but in a more controlled, predictable, and reliable way. Reading properties. Setting values. Checking existence. Deleting keys. Reflect does all of this in a clean way. The most important Reflect methods: -> Reflect.get() - reads a property from an object. const user = { name: "Markus" }; Reflect.get(user, "name"); -> "Markus" Same as user.name - but more explicit and safer in dynamic contexts. -> Reflect.set() - sets a property value and returns true or false. const user = { name: "Markus" }; Reflect.set(user, "name", "John"); -> true console.log(user.name); -> "John" Unlike direct assignment - it tells you whether it succeeded by returning true. -> Reflect.has() - checks if a property exists. Reflect.has(user, "name"); -> true Same as the in operator - but cleaner in functional and dynamic code. -> Reflect.deleteProperty() - deletes a property safely. Reflect.deleteProperty(user, "name"); -> true Same as the delete keyword - but returns a boolean instead of throwing silently. -> Reflect.ownKeys() - returns all keys of an object. const user = { name: "Markus", age: 25}; Reflect.ownKeys(user); -> ["name", "age"] Where Reflect truly shines - with Proxy. Reflect and Proxy are natural partners. Inside a Proxy trap, Reflect lets you perform the default operation in a clean way - without rewriting the behaviour from scratch. Example: const proxy = new Proxy(user, { get(target, key) { console.log(`Reading: ${key}`); return Reflect.get(target, key); -> clean default behaviour } }); Reflect doesn't replace what you already know. It refines it. It makes the operations you perform on objects more intentional, consistent, and significantly easier to debug when something goes wrong.
To view or add a comment, sign in
-
-
POST 1 — The JavaScript Event Loop Is Not What You Think ⚙️ Every JavaScript developer says they understand the event loop. Most of them don't. And that gap is exactly why async bugs are so hard to find and fix. Here's what's actually happening 👇 ───────────────────────── First — JavaScript is single-threaded. Always. One thread. One call stack. One thing running at a time. So how does it handle timers, fetch calls, and user events without freezing? It doesn't. The BROWSER does. And then it reports back. ───────────────────────── The pieces most developers mix up: The Call Stack → where your code actually runs. Functions get pushed in, executed, and popped out. This is the only place code runs. Web APIs → setTimeout, fetch, DOM events. These live OUTSIDE the JS engine — in the browser or Node runtime. They run in separate threads you never manage. The Task Queue (Macrotask Queue) → where callbacks from Web APIs wait to be picked up. setTimeout callbacks land here. The Microtask Queue → where Promise callbacks and queueMicrotask calls wait. This queue has HIGHER priority than the task queue. ───────────────────────── The loop itself: 1. Run everything currently on the call stack until it's empty 2. Drain the ENTIRE microtask queue — every single item, including new ones added during draining 3. Pick ONE task from the task queue 4. Go back to step 1 ───────────────────────── Why this produces bugs nobody expects: Promise.resolve().then() runs before setTimeout(() => {}, 0) — always. Microtasks can starve the task queue if you keep adding new ones during draining. Long synchronous code blocks EVERYTHING — no timers fire, no events respond, no UI updates. ───────────────────────── The practical rule: Never put heavy computation directly on the call stack. Break it up. Use setTimeout to yield back to the event loop. Keep microtask chains short and predictable. ───────────────────────── Did the microtask vs task queue distinction surprise you? Drop a comment below 👇 #JavaScript #WebDevelopment #FrontendDevelopment #Programming #WebPerformance
To view or add a comment, sign in
-
#js #19 **Optional Chaining in Javascript** Optional Chaining (?.) in JavaScript is used to safely access nested properties without causing errors if something is null or undefined. 🔹 Why We Need It Without optional chaining: const user = null; console.log(user.name); // ❌ Error: Cannot read property 'name' 👉 This crashes your code. ✅ With Optional Chaining const user = null; console.log(user?.name); // undefined ✅ (no error) 👉 If user is null or undefined, it stops and returns undefined 🔹 Syntax obj?.propertyobj?.[key]obj?.method() ✅ Examples 📌 1. Nested Objects const user = { profile: { name: "Navnath" }}; console.log(user?.profile?.name); // Navnath console.log(user?.address?.city); // undefined 📌 2. Function Calls const user = { greet() { return "Hello"; }}; console.log(user.greet?.()); // Hello console.log(user.sayHi?.()); // undefined (no error) 📌 3. Arrays const arr = [1, 2, 3]; console.log(arr?.[0]); // 1 console.log(arr?.[5]); // undefined 🔥 Real Use Case (Very Common) const response = { data: { user: { name: "Navnath" } }}; const name = response?.data?.user?.name; 👉 Avoids writing multiple checks like: if (response && response.data && response.data.user) ... ⚠️ Important Points ❌ Doesn’t Work on Undeclared Variables console.log(user?.name); // ❌ if user is not defined at all ⚠️ Stops Only on null / undefined const obj = { value: 0 }; console.log(obj?.value); // 0 ✅ (not skipped) 🔥 Combine with Nullish Coalescing (??) const user = {}; const name = user?.name ?? "Guest"; console.log(name); // Guest 🧠 Easy Memory Trick ?. → "If exists, then access" Otherwise → return undefined, don’t crash #Javascript #ObjectOrientedProgramming #SoftwareDevelopment
To view or add a comment, sign in
-
JavaScript has two completely different systems for sharing code between files. some developers use both without knowing which one they're using - or why it is necessary to know. Every JavaScript file you've ever written that shares code with another file, uses a module system. Some developers use them daily without truly understanding what separates one from the other. Though the gap is small. The consequences of it are not. Modules are a way to break your code into separate, reusable pieces rather than writing everything in one enormous file. It makes the code clean, organised and maintainable. There are two main systems for doing this in JavaScript. And they are not the same. CommonJS: - Uses require() to bring in modules and uses module.exports to send them - It loads modules synchronously (blocks execution) - It is mostly used in older Node.js environments Example: -> Exporting module.exports = { greet: () => console.log("Hello") }; -> Importing const myModule = require('./myModule.js'); myModule.greet(); -> "Hello" How CommonJS loads: It loads synchronously - meaning JavaScript stops everything and waits for the module to fully load before moving on. This is Problematic for browsers. ES Modules (ESM): The current standard for browsers and modern Node.js. It is cleaner, more powerful, and built for performance. -> Named export export const greet = () => console.log("Hello"); -> Default export export default function greet() { console.log("Hello"); } -> Importing named import { greet } from './myModule.js'; -> Importing default import greet from './myModule.js'; Dynamic Imports ES Modules loads only what you need, only when you need it. When you hear "you're not splitting," this is what they mean. Instead of loading every module upfront - dynamic imports let you load a module on demand, only when it's actually needed. It results to a faster initial load times. ES Modules import() returns a Promise - so it works with .then() or async/await. It is also supported natively in ESM and available in CJS environments too. ES Modules aren't just a syntax choice. They're an architectural decision. The right system, used the right way, is the difference between an app that loads instantly and one that makes users wait. And users don't like to wait. So if you need your code base to be performant, you have your answer.
To view or add a comment, sign in
-
🚀 Day 4 of #30DaysOfJavaScript (27 April 2026) Today I explored All Types of Functions in JavaScript (with definitions & examples) আজ আমি JavaScript-এর সব ধরনের Function শিখেছি (definition ও example সহ) 📌 Function (Definition | সংজ্ঞা) 👉 A function is a reusable block of code that performs a specific task. 👉 Function হলো reusable code block যেটা নির্দিষ্ট কাজ করে। 🔹 1. Function Declaration 👉 Defined using function keyword 👉 function keyword দিয়ে define করা হযfunction greet() { console.log("Hello"); } greet(); 🎯 Use: General reusable logic 🔸 2. Function Expression 👉 Function stored in a variable 👉 variable এর ভিতরে function রাখা হয়const greet = function() { console.log("Hi"); }; 🎯 Use: Dynamic function usage, callbacks ⚡ 3. Arrow Function (ES6) 👉 Short syntax using => 👉 shortcut way te function লেখা হয়const add = (a, b) => a + b; 🎯 Use: Clean & short code (React e beshi use) 🔁 4. Callback Function 👉 Function passed as argument to another function 👉 ekta function ke onno function er moddhe pathano hoy function greet(name, callback) { console.log("Hi " + name); callback(); } greet("Fahmida", () => console.log("Done")); 🎯 Use: Async কাজ, event handling 🧠 5. Anonymous Function 👉 Function without a name 👉 function er kono naam thake na setTimeout(function() { console.log("Hello"); }, 1000); 🎯 Use: One-time use, callbacks 🔄 6. IIFE (Immediately Invoked Function) 👉 Runs immediately after definition 👉 define korar sathe sathe run hoy (function() { console.log("Run instantly"); })(); 🎯 Use: Private scope, global variable avoid 🧩 7. Higher-Order Function 👉 Function that takes/returns another function 👉 function jeta onno function ke receive ba return kore function multiplier(x) { return function(y) { return x * y; }; } 🎯 Use: map, filter, reusable logic 🧱 8. Constructor Function 👉 Used to create objects with new 👉 object create korar jonno use hoy function User(name) { this.name = name; } const u1 = new User("Fahmida"); 🎯 Use: Object creation (OOP style) ⚠️ Common Mistakes 👉 Arrow function e this confusion 👉 Forgetting return 👉 Overusing anonymous functions 🔥 Learning 👉 Functions are the heart of JavaScript — everything from React components to APIs depends on them 👉 JavaScript-এর সবচেয়ে powerful concept হলো function #JavaScript #FullStackDeveloper #LearningInPublic #WebDevelopment #30DaysChallenge ়
To view or add a comment, sign in
-
🚀 Today we are going to analyse the JavaScript microtask queue, macrotask queue, and event loop. A junior developer once asked me during a code review: "Why does Node.js behave differently even when the code looks simple?" So I gave him a small JavaScript snippet and asked him to predict the output. console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); He answered confidently: Start Timeout Promise End But when we ran the code, the output was: Start End Promise Timeout He looked confused. That’s when we started analysing how JavaScript actually works internally. 🧠 Step 1: JavaScript is Single Threaded JavaScript runs on a single thread. It executes code line by line inside the call stack. So first it runs: console.log("Start") → Start console.log("End") → End Now the stack becomes empty. ⚙️ Step 2: Macrotask Queue setTimeout goes to the macrotask queue. Even though timeout is 0ms, it does not execute immediately. It waits in the macrotask queue. Examples of macrotasks: • setTimeout • setInterval • setImmediate • I/O operations • HTTP requests ⚡ Step 3: Microtask Queue Promise goes to the microtask queue. Examples of microtasks: • Promise.then() • Promise.catch() • Promise.finally() • process.nextTick (Node.js) • queueMicrotask() Microtasks always get higher priority. They execute before macrotasks. 🔁 Step 4: Event Loop Now the event loop starts working. The event loop checks: Is the call stack empty? Yes Check microtask queue Execute all microtasks Then execute macrotasks So execution becomes: Start End Promise Timeout Now everything makes sense. 🏗️ Real Production Example Imagine a Node.js API: app.get("/users", async (req, res) => { console.log("Request received"); setTimeout(() => console.log("Logging"), 0); await Promise.resolve(); console.log("Processing"); res.send("Done"); }); Execution order: Request received Processing Logging Why? Because Promise (microtask) runs before setTimeout (macrotask). This directly affects: • API response time • Logging • Background jobs • Queue processing • Performance optimization 🎯 Why Every Node.js / NestJS / Next.js Developer Should Know This Because internally: • Async/Await uses Promises • API calls use Event Loop • Background jobs use Macrotasks • Middleware uses Microtasks • Performance depends on queue execution Without understanding this, debugging production issues becomes very difficult. 💡 Final Thought JavaScript is not just a language. It is an event-driven execution engine. If you understand microtask queue, macrotask queue, and event loop, you don’t just write code — you understand how the runtime thinks. And once you understand the runtime, you start building faster and more scalable systems. #JavaScript #NodeJS #EventLoop #Microtasks #Macrotasks #NextJS #NestJS #SystemDesign #SoftwareEngineering
To view or add a comment, sign in
-
-
Lately, I’ve been going deeper into JavaScript coercion, and the more I study it, the less random JavaScript feels. A lot of behaviour that looks strange at first starts making sense once you realise that JavaScript is following rules defined in the ECMAScript specification. Recently, I focused on the abstract operations behind conversion, especially: - ToNumber - StringToNumber - ToString - ToPrimitive - OrdinaryToPrimitive One of the biggest takeaways for me is that JavaScript does not just “guess” what to do with values. It follows a defined process depending on the operation being performed. For example: - `"5" - 1` works because subtraction expects numbers. - `Number("")` becomes `0`. - `Number(undefined)` becomes `NaN`. - `ToNumber(BigInt)` throws an error, but `ToString(BigInt)` works. - When an object is involved, JS first tries to extract a primitive value before continuing coercion The part I found especially interesting was object-to-primitive conversion. If JavaScript encounters an object in a coercion context, it first checks for `Symbol.toPrimitive`. If that is not available, it falls back to `OrdinaryToPrimitive`, where the order of calling `toString()` and `valueOf()` depends on the hint being used: - string hint → toString() first - number hint → valueOf() first I also learned more about why string-to-number conversion behaves the way it does: - Number("25") gives 25 - Number(" 25 ") also gives 25 - Number("Infinity") gives Infinity - Number("1_000") gives NaN - Number("10n") gives NaN What is changing my understanding the most is this: - Instead of memorising “weird JavaScript behaviour”, I’m now trying to ask: 1. What operation is being performed? 2. What type of value does that operation expect? 3. Which abstract operation is JavaScript using behind the scenes? That mindset makes the language much easier to reason about. I’ve also been maintaining detailed notes on what I’m learning. If anyone wants to go deeper into these topics, I’ve uploaded them here: GitHub repo: https://lnkd.in/ephuZ-w6 #JavaScript #TypeScript #WebDevelopment #SoftwareEngineering #ECMAScript #100DaysOfCode
To view or add a comment, sign in
-
-
✨ 𝗪𝗿𝗶𝘁𝗲 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗦𝘁𝗿𝗶𝗻𝗴𝘀 𝗟𝗶𝗸𝗲 𝗔 𝗛𝘂𝗺𝗮𝗻 ⤵️ Template Literals in JavaScript: Write Strings Like a Human ⚡ 🔗 𝗥𝗲𝗮𝗱 𝗵𝗲𝗿𝗲: https://lnkd.in/d_HhAEsM 𝗧𝗼𝗽𝗶𝗰𝘀 𝗰𝗼𝘃𝗲𝗿𝗲𝗱 ✍🏻: ⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺ ⇢ Why string concatenation becomes messy in real apps ⇢ Template literals — the modern way to write strings ⇢ Embedding variables & expressions using ${} ⇢ Multi-line strings without \n headaches ⇢ Before vs After — readability transformation ⇢ Real-world use cases: HTML, logs, queries, error messages ⇢ Tagged templates (advanced but powerful concept) ⇢ How interpolation works under the hood ⇢ Tradeoffs & common mistakes developers make ⇢ Writing cleaner, more readable JavaScript Thanks Hitesh Choudhary Sir & Piyush Garg Sir, and the amazing Chai Aur Code community 🙌 #ChaiAurCode #JavaScript #WebDevelopment #Frontend #Programming #CleanCode #Hashnode
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