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

Levenshtein Distance: Formula, Worked Table and Python Code

Levenshtein distance explained: the edit operations, the dynamic programming table for kitten and sitting, Python code with two-row memory, normalised…

Read article →
Software Development

URL Encoding Explained: Spaces, Plus Signs and UTF-8

URL encoding explained with tested Python and JavaScript code: percent encoding, reserved characters, %20 vs plus, UTF-8 bytes, encodeURI vs…

Read article →
DevOps

Gitignore: Patterns, Negation and Fixing Tracked Files

A tested gitignore guide: pattern rules, leading and trailing slashes, negation with !, the ignored parent folder trap, git check-ignore…

Read article →
Software Testing

Acceptance Criteria: Given When Then Examples and Checklist

How to write acceptance criteria testers can run: rule-based and Given When Then formats, a worked discount code example turned…

Read article →
Software Testing

State Transition Testing: Diagram, Table and Example

State transition testing explained with a login lockout example: states, events, the diagram, the state table, valid and invalid transitions,…

Read article →
Databases & SQL

Second Highest Salary in SQL: 5 Tested Ways and the Tie Trap

Find the second highest salary in SQL five ways: MAX subquery, LIMIT OFFSET, DENSE_RANK, a correlated subquery and per department,…

Read article →
Databases & SQL

SQL ROW_NUMBER: Top N per Group, Dedupe and Pagination

SQL ROW_NUMBER explained with tested queries: PARTITION BY, top N per group, deleting duplicates, pagination, the tie trap and how…

Read article →
Software Development

JavaScript Set: Union, Intersection and Removing Duplicates

JavaScript Set explained with tested examples: add, has, delete, deduplicating arrays, the new union and intersection methods, equality rules and…

Read article →
Test Automation

Python Unittest: Assert Methods, setUp and Mocks With Examples

A practical Python unittest tutorial: TestCase, assert methods, setUp and tearDown, subTest, skips, expected failures and mock, with a test…

Read article →
Software Development

Python Map and Filter: Examples vs List Comprehensions

Python map and filter explained with tested examples: lazy map objects, multiple iterables, filter(None), chaining, and a timed comparison with…

Read article →
Artificial Intelligence

Jaccard Similarity: Formula, Python, MinHash

Jaccard similarity measures overlap between two sets as intersection over union. Work the formula, compute it in Python for words…

Read article →
Software Development

Unix Timestamp Explained: Seconds vs ms

A Unix timestamp counts seconds since 1 January 1970 UTC. Learn seconds vs milliseconds, converting in Python, JavaScript and SQL,…

Read article →
DevOps

Git Hooks: Pre-commit and Commit-msg Examples

Git hooks run scripts at key moments such as commit and push. See tested pre-commit, commit-msg and prepare-commit-msg hooks, sharing…

Read article →
Test Automation

API Testing in Python: Pytest + Requests Suite

Build an API testing suite in Python with pytest and requests: fixtures, status codes, headers, JSON schema validation, CRUD flows,…

Read article →
Software Testing

Test Design Techniques: 9 Methods + Examples

Test design techniques help you write fewer tests that catch more bugs. Learn 9 black-box, white-box and experience-based methods with…

Read article →
Databases & SQL

SQL Temporary Table: Create, Use and Drop It

SQL temporary tables store interim results for one session. Learn syntax for SQL Server, PostgreSQL, MySQL, Oracle and SQLite, session…

Read article →
Databases & SQL

SQL CROSS JOIN: Every Combination + Examples

SQL CROSS JOIN returns every combination of rows from two tables. See the row math, product variants, calendar grids that…

Read article →
Software Development

JavaScript Date: Format, Parse, Timezone Bugs

JavaScript Date explained with tested Node.js code: zero-based months, the date-only UTC parsing trap, toISOString, getTimezoneOffset, Intl formatting, date math…

Read article →
Software Development

Python Requests: GET, POST, Timeouts, Retries

Python requests explained with code tested against a local API: GET with params, POST json vs data, headers and auth,…

Read article →
Artificial Intelligence

TF-IDF Explained: Formula and Worked Example

TF-IDF scores a word by how often it appears in a document and how rare it is across all documents….

Read article →
DevOps

Git Tag: Create, Push and Delete Release Tags

Git tag explained with tested commands: annotated vs lightweight tags, listing and sorting, pushing with follow-tags, deleting local and remote…

Read article →
Test Automation

Pytest Coverage: pytest-cov and Branch Gaps

Measure pytest coverage with pytest-cov: term-missing reports, branch coverage, HTML reports, pyproject settings and a fail-under gate for CI, with…

Read article →
Software Testing

Error Guessing in Testing: Checklist + Demo

Error guessing uses tester experience to predict where code breaks. Get a ready checklist of risky inputs, a step by…

Read article →
Databases & SQL

SQL LAG and LEAD: Compare Rows, 5 Examples

SQL LAG and LEAD read values from the previous or next row without a self join. Five tested examples: change,…

Read article →
Databases & SQL

SQL STRING_AGG: Combine Rows Into One String

SQL STRING_AGG joins values from many rows into one string per group. See syntax for PostgreSQL, SQL Server, MySQL GROUP_CONCAT,…

Read article →
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 →
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 →
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 →
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 →
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 →
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 →