1. Home
  2. Blog
  3. Software Development

Software Development

JavaScript this Keyword Explained: Every Binding Rule, Tested in Node

The JavaScript this keyword changes value depending on how a function is called, not where it is written. Learn the five rules, why this gets lost in callbacks, and how arrow functions, bind and classes fix it, with 17 cases we ran.

10 min read
JavaScript this keyword explained: every binding rule, tested in Node

Key takeaways

  • The call site decides this. The same function can see different values on different calls.
  • Copying a method into a variable or passing it as a callback loses its object; in strict code this becomes undefined.
  • Arrow functions have no own this. They use the value from the surrounding code, which fixes most callback bugs.
  • bind locks this permanently. In our tests, a second bind and a later call were both ignored.

Few things confuse JavaScript developers as often as the JavaScript this keyword. A method works in one place, then fails with “Cannot read properties of undefined” when you pass it to a timer or an event handler. The reason is simple once you see it: this is not fixed when the function is written. It is decided each time the function is called.

We ran 17 small cases in Node.js 24.22.1, mostly in a CommonJS file with "use strict" at the top, and the outputs below are copied from that run. Browser-only cases, such as DOM event handlers, are described but were not run. If scope and closures are new to you, read our JavaScript closures guide first, because arrow functions rely on the same idea.

What is this in JavaScript?

this is a special value available inside every regular function. Think of it as an extra, hidden argument that JavaScript fills in when you call the function. Most of the time it points to the object the function was called on. The rules below explain exactly how JavaScript chooses it.

Rule 1: method calls use the object before the dot

"use strict";
const user = { name: "Asha", greet() { return `Hi, ${this?.name}`; } };
console.log(user.greet());   // Hi, Asha

Because we called user.greet(), the object before the dot, user, became this. With nested objects, only the nearest object counts:

const nested = { name: "outer", a: { name: "inner", hi() { return this.name; } } };
console.log(nested.a.hi());   // inner

How this gets lost

Now copy the same method into a variable and call it on its own:

const detached = user.greet;
console.log(detached());   // Hi, undefined

There is no dot at the call site, so there is no object. We used optional chaining (this?.name) to show the value; without it, the call would throw a TypeError. This is exactly what happens when you pass user.greet as a callback: the receiving code calls it as a plain function and the object is gone.

Rule 2: default binding in plain function calls

function whoAmI() { return this; }
console.log(whoAmI());   // undefined (strict mode)

In strict mode, a plain call gives undefined. We also ran the same function in a non-strict file, and this === globalThis printed true. That old behaviour silently writes to global variables when you forget new or lose a method, which is one reason modern code is strict. ES modules and class bodies are always strict, so you get the safer undefined by default.

Rule 3: call, apply and bind set this explicitly

console.log(whoAmI.call({ id: 1 }), whoAmI.apply({ id: 2 }));
// { id: 1 } { id: 2 }

const bound = user.greet.bind({ name: "Ben" });
console.log(bound());                        // Hi, Ben
console.log(bound.bind({ name: "X" })());   // Hi, Ben
console.log(bound.call({ name: "Y" }));     // Hi, Ben

call and apply invoke the function once with the this you pass; they differ only in how extra arguments are given (a list for call, an array for apply). bind returns a new function whose this is fixed forever. Our test confirms the “forever”: binding again and calling with a different object both still printed Hi, Ben.

Some array methods accept a thisArg too:

console.log([1, 2].map(function (x) { return x * this.k; }, { k: 10 }));   // [ 10, 20 ]

Arrow functions: this from the surrounding code

Arrow functions do not create their own this. They read it from the code around them at the moment they are created, just like any other outer variable.

const counter = {
  count: 0,
  startRegular() { return [1, 2, 3].map(function () { return this; }); },
  startArrow()   { return [1, 2, 3].map(() => this.count); },
  arrowMethod: () => typeof this,
};
console.log(counter.startRegular());   // [ undefined, undefined, undefined ]
console.log(counter.startArrow());     // [ 0, 0, 0 ]
console.log(counter.arrowMethod());    // object  (module.exports, not counter)

The regular callback lost this, while the arrow callback kept the method’s this and read count. The third line shows the opposite mistake: an arrow function used as a method does not see the object. In our CommonJS file it saw module.exports. Rule of thumb: use regular method syntax for object methods, and arrow functions for callbacks inside them.

Tip: call, apply and bind cannot change an arrow function’s this. If a library tries to set this for your callback, use a regular function instead.

Callbacks, timers and events

const obj = {
  val: 42,
  later()      { setTimeout(function () { console.log(typeof this); }, 0); },
  laterArrow() { setTimeout(() => console.log(this.val), 0); },
};

The regular function printed object, but that object was Node’s internal Timeout, not obj. The arrow version printed 42. In browsers, a regular timer callback gets the global window object instead; we did not run the browser case. Either way, the regular function does not see your object.

DOM event handlers follow their own rule: with element.addEventListener("click", function () { ... }), this is the element that received the event. With an arrow function it is whatever the surrounding code had. Both are valid; choose based on whether you need the element or your component. We did not run DOM examples here. Timers and async callbacks run later through the event loop, which our event loop guide explains.

Rule 4: new and classes

function Car(make) { this.make = make; }
const c = new Car("Tata");
console.log(c.make, c instanceof Car);   // Tata true

new creates a fresh object, makes it this inside the function, and returns it. Classes work the same way, with a twist for detached methods:

class Timer {
  seconds = 0;
  tickArrow = () => ++this.seconds;
  tickMethod() { return ++this.seconds; }
}
const t = new Timer();
const { tickArrow, tickMethod } = t;
tickArrow();    // 1
tickMethod();   // TypeError: Cannot read properties of undefined (reading 'seconds')

A class field holding an arrow function captures the instance, so it survives being detached. That is why some codebases write event handlers this way. The cost is memory: each instance gets its own copy of the function instead of sharing one on the prototype. For TypeScript users, the same rules apply, as covered in our TypeScript tutorial.

Top-level this: CommonJS vs ES modules

Outside any function, this depends on the module system. In our CommonJS file, this === module.exports printed true. In an .mjs ES module, top-level this printed undefined. In a classic browser script it is the window object. If you are moving code between formats, our ES modules vs CommonJS guide covers other differences that bite.

The rule order in one table

When several rules could apply, JavaScript checks them in this order:

Call style this is Example result
new Fn() The new object Tata true
fn.bind(obj) or call/apply The object you pass Hi, Ben
obj.fn() The object before the dot Hi, Asha
fn() undefined (strict) or global object undefined
Arrow function Inherited from surrounding code [ 0, 0, 0 ]

Debugging this in practice

  • Log it: console.log(this) at the top of the function shows what you actually got.
  • Look at the call site, not the definition. Search for where the function is passed or invoked.
  • If a method is passed as a callback, wrap it: () => user.greet(), or bind it once in the constructor.
  • Prefer strict mode, so mistakes fail loudly with undefined instead of touching globals.
  • In tests, call methods both directly and as callbacks; the second style catches lost this before users do.

Async code adds one more layer, because callbacks run after the current function has returned. Our JavaScript promises guide shows how then callbacks and async functions handle this, and the same arrow-function fix applies.

Final thoughts

The JavaScript this keyword stops being mysterious once you look at how a function is called. A dot gives the object, new gives a fresh object, bind, call and apply give whatever you pass, a plain call gives undefined in strict code, and arrow functions simply borrow from their surroundings. Learn those five lines, and most “undefined” errors become quick fixes.

Frequently asked questions

What does this refer to in JavaScript?

It depends on how the function is called. For obj.method() it is obj, with new it is the new object, with bind, call or apply it is the value you pass, and in a strict plain call it is undefined.

Why is this undefined in my callback?

Passing a method as a callback removes its object, so it is called as a plain function. In strict code that makes this undefined. Use an arrow function wrapper or bind the method.

Do arrow functions have their own this?

No. Arrow functions use this from the surrounding code where they were created, and call, apply or bind cannot change it. That makes them ideal for callbacks inside methods.

What is the difference between call, apply and bind?

call and apply run the function once with a chosen this, taking arguments as a list or an array. bind returns a new function with this fixed permanently; rebinding it had no effect in our test.

What is this at the top level of a file?

In a CommonJS file it is module.exports, in an ES module it is undefined, and in a classic browser script it is the global window object. We confirmed the first two in Node 24.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
Software Development

HTTP Methods Explained: GET, POST, PUT, PATCH, DELETE, Tested on a Live Server

HTTP methods explained with a small server we ran: GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS, safe vs idempotent,…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Databases & SQL

SQL ORDER BY Multiple Columns: ASC, DESC, NULLS LAST, Case and Custom Order

SQL ORDER BY with multiple columns explained with tested queries: mixed ASC and DESC, tie-breakers, NULLS FIRST and LAST, case-insensitive…

Read article →
Databases & SQL

SQL Running Total: SUM OVER, Per-Group Totals, Moving Sums and the RANGE Trap

How to calculate a SQL running total with SUM() OVER: per-group totals, daily cumulative sums, moving sums, percent of total,…

Read article →
Software Development

JavaScript Sort Array: Numbers, Objects, Strings and Why 10 Comes Before 5

How to sort an array in JavaScript correctly: numbers with a compare function, objects by one or more fields, strings…

Read article →
Software Development

Python String Methods: Cheat Sheet, Real Examples and the strip() Trap

Python string methods with tested examples: split, join, strip, replace, find, startswith, is-methods, casefold, partition and translate, plus the strip()…

Read article →
Software Development

Python zip() Explained: Loop Two Lists at Once, Unzip, strict=True and Traps

Python zip() pairs items from several lists in one loop. Tested examples for dicts, unzipping with *, strict=True, zip_longest, sliding…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
Software Development

UTF-8 Encoding Explained: How Text Becomes Bytes and How to Fix Garbled Text

UTF-8 encoding explained with byte-level examples we ran in Python: how characters become 1 to 4 bytes, why café turns…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Databases & SQL

Delete Duplicate Rows in SQL: 5 Safe Methods, Tested Step by Step

How to delete duplicate rows in SQL safely: find them, preview them, then remove them with ROW_NUMBER, MIN(id), EXISTS, rowid…

Read article →
Databases & SQL

SQL RANK vs DENSE_RANK vs ROW_NUMBER: Differences with Tested Examples

SQL RANK vs DENSE_RANK vs ROW_NUMBER in one table: how each handles ties, top-N per group, the second-highest salary trap…

Read article →
Software Development

JavaScript Optional Chaining (?.) Explained: 8 Examples, ?? Defaults and Traps

JavaScript optional chaining stops “Cannot read properties of undefined” errors. 8 tested examples for properties, arrays and methods, ?? vs…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Software Testing

Pairwise Testing Explained: How All-Pairs Cuts 216 Tests to 13, Tested

Pairwise testing explained with a generator we ran in Python 3.13: a checkout with 216 combinations covered by 13 tests,…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →
Databases & SQL

SQL COALESCE Explained: Defaults, NULLIF, IFNULL vs ISNULL and Traps, Tested

SQL COALESCE explained with queries we ran in SQLite 3.50: first non-null values, empty strings, NULL in maths, NULLIF for…

Read article →
Databases & SQL

SQL Self Join Explained: Employee-Manager, Pairs and Row Comparisons, Tested

SQL self join explained with queries we ran in SQLite 3.50: employee and manager, earning more than the manager, unique…

Read article →
Artificial Intelligence

LLM Context Window Explained: Tokens, Limits and How to Fit More, Measured

The LLM context window explained with token counts we measured using tiktoken: words vs tokens for prose, code and Hindi,…

Read article →
DevOps

Git Cherry-Pick Explained: Copy the Commit You Need, Safely, Tested

Git cherry-pick explained with commands we ran in Git 2.56: copying a hotfix to a release branch, new hashes and…

Read article →
Test Automation

Snapshot Testing Explained: How It Works, When It Helps and When It Hurts

Snapshot testing explained with a pytest and syrupy demo we ran: creating snapshots, reading the diff after a code change,…

Read article →
Software Testing

Mutation Testing Explained: Why 100% Coverage Still Missed Our Bug

Mutation testing explained with a small mutation tool we built and ran: 14 mutants, a test suite with 100% line…

Read article →
Artificial Intelligence

Prompt Injection Explained: How AI Apps Get Tricked and How to Defend Them

Prompt injection explained for builders: direct and indirect attacks, why keyword filters fail (our test blocked 1 of 4), and…

Read article →
DevOps

DNS Records Explained: A, AAAA, CNAME, MX, TXT and TTL With Real Lookups

DNS records explained with lookups we ran: how resolution works, A and AAAA, CNAME rules, MX and null MX, TXT…

Read article →
DevOps

Feature Flags Explained: Safe Releases, Gradual Rollouts and Flag Hygiene

Feature flags explained with a rollout simulation we ran: flag types, percentage rollouts with stable hashing, kill switches, allow lists,…

Read article →
Test Automation

Test Data Generation With Python Faker: Realistic, Repeatable and Safe Data

Test data generation with Python Faker, run and measured: seeding for repeatable data, locales, unique values, domain-shaped records, edge cases…

Read article →
Software Testing

Shift-Left Testing Explained: Find Bugs Earlier Without Slowing the Team

Shift-left testing explained: what it means, why early defects are cheaper, practices from requirement reviews to CI checks, the tester's…

Read article →
Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →