Sknoe / Notes

Scope, this, and the Event Loop: How Modern JavaScript Actually Runs

A practical guide for SFRA and Storefront Next developers—why `this` can change in Add-to-Cart callbacks, how block scope protects basket calculations, and how the event loop schedules Promise callbacks and timers around SCAPI requests.

4 min read

Brendan Eich has said JavaScript’s first engine prototype took ten days in May 1995. The language has changed considerably since then, but three execution details still matter in everyday code: scope, `this`, and asynchronous callback scheduling.

Why can `this` seem to change when an Add-to-Cart handler runs? And why does a Promise callback sometimes run before a timer? If you work across SFRA controllers and Storefront Next components, these questions lead to three JavaScript rules that are useful to understand: how declarations get their scope, how regular functions receive `this`, and how the event loop schedules asynchronous callbacks.

The examples use baskets, promo calculations, click handlers, and SCAPI requests, but the same rules apply to JavaScript in any browser or Node.js application.

1. Scope: why let and const protect basket math

A useful mental model is that JavaScript prepares declarations for their scope before running the statements in order. This is a teaching model, not a claim that the engine literally makes exactly two passes over every function. `var` is function-scoped (or script-global at top level), and it is initialized to `undefined` before its assignment runs. `let` and `const` are block-scoped and cannot be accessed before their declaration has initialized them.

basketDiscount.js
function calculateBasketTotal(subtotal, isVipShopper) {
if (isVipShopper) {
let vipDiscount = 15;
var legacyShippingFee = 0;
}
console.log(legacyShippingFee); // 0: var is function-scoped
console.log(vipDiscount); // ReferenceError: outside the block
}
{
console.log(promoRate); // ReferenceError: still in the TDZ
const promoRate = 0.15;
}

`vipDiscount` is not available outside the `if` block because `let` is block-scoped. `legacyShippingFee` is available throughout the function because `var` is function-scoped. The second example shows the TDZ: the `promoRate` binding exists in its block, but it has not been initialized yet.

In modern code, default to `const`, use `let` when a binding must be reassigned, and generally avoid `var` because its function scope can make values appear outside the block where they were assigned.

2. Finding this: look to the left of the dot

For a regular function, `this` depends on how the function is called. “Look to the left of the dot” is a handy shortcut for a direct method call such as `guestCart.logBasketAction()`:

cartHandlers.js
"use strict";
function logBasketAction() {
return `Updating basket: ${this.basketId}`;
}
const guestCart = { basketId: 'bsk-101', logBasketAction };
const memberCart = { basketId: 'bsk-202', logBasketAction };
guestCart.logBasketAction(); // this is guestCart
memberCart.logBasketAction(); // this is memberCart
const detachedHandler = guestCart.logBasketAction;
detachedHandler(); // in strict mode, this is undefined

When you detach the method, the call is no longer `guestCart.logBasketAction()`, so it does not keep `guestCart` as `this`. In a plain standalone call in strict mode, `this` is `undefined`; trying to read `this.basketId` then throws a TypeError. ES modules are strict mode, which is why this commonly appears in modern JavaScript projects.

Callback APIs can supply their own `this`. For example, a browser `addEventListener` callback receives the event’s current target as `this`; it is not the original cart object. Timer callback behavior also depends on the host environment. If a callback needs the cart, pass a wrapper or bind the method explicitly.

cartHandlers.js
button.addEventListener('click', () => {
guestCart.logBasketAction();
});
// Or bind the method once.
button.addEventListener('click', guestCart.logBasketAction.bind(guestCart));

How arrow functions preserve this in a timer

Regular functions receive `this` when they are called. Arrow functions do not create their own `this`; they use the value from the surrounding scope where they were created:

miniCartToast.js
const miniCart = {
basketId: 'bsk-101',
autoCloseAfterAdd() {
// This method is called as miniCart.autoCloseAfterAdd(), so its this is miniCart.
setTimeout(() => {
// The arrow keeps this from autoCloseAfterAdd.
console.log(`Closed mini-cart for ${this.basketId}`);
}, 3000);
},
};
Under the hoodWhy an arrow function is usually wrong as an object methodAn object literal does not create a new `this` scope for an arrow function.

Looking closer

In `const cart = { id: 'bsk-1', show: () => this.id }`, the arrow gets `this` from the surrounding scope, not from `cart`. In an ES module, top-level `this` is undefined, so accessing `this.id` throws. Use method shorthand (`show() { return this.id; }`) when the method should receive the object as `this`; use an arrow inside a callback when it should capture an enclosing method's `this`.

3. The event loop: call stack, microtasks, and tasks

JavaScript runs synchronous code to completion on a call stack. In the browser, Promise handlers such as `.then()` run as microtasks. Timers such as `setTimeout()` schedule tasks. After the current synchronous script finishes, the runtime processes queued microtasks before moving on to the next task.

What runs after this synchronous script?
  1. Synchronous script

    Log 1, register a timer, register a handler on an already-resolved Promise, then log 2.

  2. Microtask checkpoint

    Run the Promise .then() callback, which logs 3.

  3. Next timer task

    Run the setTimeout() callback, which logs 4.

addToCartEventLoop.js
console.log('1. Shopper clicked Add to Cart');
setTimeout(() => {
console.log('4. Hide confirmation toast (timer task)');
}, 0);
Promise.resolve({ basketCount: 2 }).then((res) => {
console.log(`3. Update badge to ${res.basketCount} (Promise microtask)`);
});
console.log('2. Disable button while request starts');
// Output: 1 -> 2 -> 3 -> 4

This example uses an already-resolved Promise, so its `.then()` callback is queued as a microtask while the script is running. It does not mean a real SCAPI `fetch()` response always beats a timer: the network request may take longer to settle, so its Promise callback might be queued later.

A `setTimeout(fn, 1000)` delay is not an exact appointment. The callback becomes eligible after the requested delay, but a busy main thread or browser scheduling can make it run later. If synchronous code is busy parsing a large catalog response, user interactions, timers, and Promise handlers all have to wait for that work to finish.

4. Three rules for today's e-commerce JavaScript

Use `const` by default and `let` for reassignment. Block scope and the TDZ help prevent promo or tax variables from leaking across `if` blocks.

Use method shorthand for object methods that need the object as `this`; use an arrow callback when you want to preserve the surrounding `this` in a timer or listener. Remember that callback APIs may bind `this` according to their own rules.

Keep synchronous work on the call stack short. Fast product-grid filtering helps the browser respond and render; a long-running calculation delays both tasks and microtasks.

Interview questions

For a prerequisite, read JavaScript Callbacks Explained: How They Work and Why They Matter. To see the Add-to-Cart journey in SFRA, continue with Build Add to Cart: A Backend-to-Frontend SFRA Journey.

Did this click?

Tap the bulb if this explanation helped.

Further reading

As an Amazon Associate I earn from qualifying purchases.

JavaScript book used as a source for this article (affiliate link)

Interview questions

What does `this` refer to when an object method is passed as a callback?

It depends on how the receiving API invokes the callback; passing a method by itself does not preserve its original object as `this`. Use `method.bind(object)` or a wrapper such as `() => object.method()` when the callback needs that object.

Why does the callback from `Promise.resolve().then(...)` run before a `setTimeout(..., 0)` callback in the same script?

The Promise is already resolved, so `.then()` queues a microtask. After the current synchronous script finishes, the runtime processes queued microtasks before moving to the next timer task. A real network request may settle later, so this order does not guarantee that a SCAPI response beats a timer.