LearnFrenzy
Sign in Take a free test

JavaScript for LWC Interview Prep · Lesson 25 of 25

JavaScript for LWC Interview Questions and Answers

10 min read Updated Nov 8, 2026 Saurabh Samir

Salesforce developer interviews have changed. Alongside Apex and SOQL, you'll now be asked plain JavaScript questions – this, closures, promises – and LWC questions that are really JavaScript questions in disguise: "why didn't my list update?", "why is my wire data read-only?". Here are the ones that come up most, with short answers you can say out loud. Each links to the lesson that covers it in depth.

How to use this page

  • Answer each question aloud before opening it – then compare.
  • Lead with the core idea in one sentence, then give an LWC example.
  • Finish with the code-review round: many interviews now include one.

Core JavaScript

Fundamentals

1. What is the difference between let, const and var?

let and const are block-scoped; const can't be reassigned (but an object it holds can still change). var is function-scoped and hoisted, which causes confusing bugs – don't use it. See variables and data types.

2. == vs ===?

=== compares type and value; == converts types first, so 0 == '' is true. Always use ===; value == null is the one common shortcut, true for null and undefined.

3. What is the difference between null and undefined in Salesforce data?

undefined means "not set" – blank fields are simply missing from Apex-returned sObjects. null is an intentional empty value, e.g. a blank field in Lightning Data Service data. Handle both with ?. and ??.

4. || vs ???

|| falls back on any falsy value, including 0 and ''. ?? only falls back on null and undefined, so an Amount of 0 stays 0. See operators.

5. How does this work?

For normal functions, this is decided by how the function is called – the object left of the dot. Detached, it's undefined in strict mode. Arrow functions don't have their own this; they use the surrounding one. That's why callbacks in components are written as arrows. See the this keyword.

6. What is a closure? Give a real use.

A function that remembers variables from where it was created. Real uses: a debounce helper keeping its timer id, a memoize cache, private counters. See closures and debounce.

7. Shallow vs deep copy?

Spread ({ ...obj }) copies the top level; nested objects are still shared. A deep copy duplicates everything – in LWC use JSON.parse(JSON.stringify(x)) for proxied data, since structuredClone can't clone proxies.

8. map vs forEach?

map returns a new array of transformed items; forEach returns nothing and is for side effects. Use map to shape records for the template, and remember neither waits for await in its callback.

9. Why is [10, 9, 100].sort() wrong?

Without a compare function, items are compared as strings, giving [10, 100, 9]. Use (a, b) => a - b, and prefer toSorted so you don't mutate (possibly read-only) data. See array methods.

10. What does the class keyword really create?

A constructor function with methods on its prototype – syntax over prototypal inheritance. A component is such a class extending LightningElement; mixins like NavigationMixin are functions that return subclasses. See classes.

Asynchronous JavaScript

Promises and the event loop

11. Explain the event loop.

JavaScript runs one piece of synchronous code at a time. When the stack is empty, it runs all queued microtasks (promise callbacks), then the next task (a timer, a click). That's why a promise callback runs before setTimeout(…, 0). See the event loop.

12. Why isn't the DOM updated right after I set a field?

LWC batches changes and re-renders in a microtask after your code finishes. Read the DOM in renderedCallback, or after await Promise.resolve().

13. Promise.all vs Promise.allSettled?

all resolves when everything succeeds and rejects on the first failure – good for loading what a screen needs. allSettled waits for everything and reports each result – good for bulk updates where some may fail. See promises.

14. Two awaits in a row – what's the performance issue?

The second call doesn't start until the first finishes. If they're independent, start both and await Promise.all([...]).

15. How do you handle errors with async/await?

Wrap the awaits in try/catch, show a message in catch, and turn off loading state in finally. An unhandled rejection only shows as "Uncaught (in promise)" in the console. See async/await with Apex.

16. What is debouncing and where would you use it in LWC?

Delaying an action until input has paused, so it runs once. Search boxes that call Apex and auto-save fields. Clear the pending timer in disconnectedCallback.

JavaScript inside LWC

Component-level questions

17. Why doesn't this.items.push(x) update the screen?

Without @track, LWC only re-renders when a field is assigned a new value. push changes the same array. Assign a new array – this.items = [...this.items, x] – or decorate the field with @track. See reactivity.

18. When do you still need @track?

Only when you want LWC to notice mutations inside a plain object or array held in a field, e.g. a deeply nested form state. Primitives and reassigned values are reactive without it.

19. Why is @wire data read-only, and how do you edit it?

It comes from a cache shared with other components, so it's frozen. Make a copy – data.map((r) => ({ ...r, extra })) or a JSON round-trip – and edit that.

20. Why can't the template write {amount * 1.18}?

LWC templates don't evaluate expressions by design; computed values are getters in JavaScript, which keeps logic testable.

21. How do you know which row's button was clicked?

Put the id in a data-id attribute and read event.currentTarget.dataset.id in the handler. Templates can't pass arguments to handlers.

22. Why does document.querySelector return null for my element?

The element is in the component's shadow DOM. Use this.template.querySelector or lwc:ref with this.refs. See shadow DOM and querySelector.

23. Explain bubbles and composed for a CustomEvent.

Both false by default: only the parent listening on the child's tag hears it. bubbles: true lets it travel up the parent's template; adding composed: true lets it cross shadow boundaries to the whole page – avoid that unless necessary. See events.

24. How do sibling components talk to each other?

Through a common parent (event up, property down) or, if they're unrelated, Lightning Message Service.

25. Why use an @api getter/setter instead of a plain @api property?

To run code whenever the parent sets the value – normalising, validating or deriving other state – while keeping a private copy you're allowed to change.

26. How do you share a utility function across components?

Create a component folder with only a JavaScript file that exports functions (e.g. c/formatUtils) and import it. Module-level state in it is shared page-wide. See ES modules.

27. How do you read error messages from Apex?

Error shapes vary: body.message for Apex exceptions, body.pageErrors/fieldErrors for DML, body.output.errors for UI API. Use a reduceErrors helper. See error handling.

28. What is errorCallback?

A lifecycle hook on a parent that catches errors thrown by descendants during rendering or lifecycle hooks, so you can show a fallback. It doesn't catch errors in handlers or promises.

29. How do you load a third-party library like Chart.js?

Upload it as a static resource and call loadScript(this, URL) from lightning/platformResourceLoader, once, behind a flag; render into an element with lwc:dom="manual". CDNs are blocked by CSP. See Lightning Web Security.

30. How do you test a component that calls Apex?

With Jest and sfdx-lwc-jest: jest.mock the Apex module, set mockResolvedValue or mockRejectedValue, mount with createElement, trigger the action, flush promises and assert on the shadow DOM. See Jest testing.

Code-review round

"Here's a component a junior developer wrote. What's wrong with it?" Read it and list the problems before opening the answer.

// contactList.js – find the bugs
import { LightningElement, api, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
import searchContacts from '@salesforce/apex/ContactController.searchContacts';

export default class ContactList extends LightningElement {
    @api recordId;
    contacts = [];
    timer;

    @wire(getContacts, { accountId: '$recordId' })
    wired({ data }) {
        if (data) {
            data.forEach((c) => { c.FullName = c.FirstName + ' ' + c.LastName; });
            this.contacts = data;
        }
    }

    connectedCallback() {
        this.timer = setInterval(this.refresh, 30000);
    }

    handleSearch(event) {
        searchContacts({ term: event.target.value }).then(function (result) {
            this.contacts = result;
        });
    }

    get sortedContacts() {
        return this.contacts.sort((a, b) => a.LastName > b.LastName);
    }

    handleSelect(event) {
        this.dispatchEvent(new CustomEvent('onContactSelect', { detail: this.contacts[event.target.dataset.index] }));
    }
}
Show the problems
  1. Mutating wire data – c.FullName = … on read-only records throws. Use data.map((c) => ({ ...c, FullName: … })). Errors are ignored too: handle error.
  2. Lost this – setInterval(this.refresh, …) calls refresh without the component as this.
  3. Timer never cleared – no disconnectedCallback, so it runs after the component is gone. (And polling every 30s should be questioned – refreshApex on demand or Platform Events?)
  4. this inside function() – the then callback uses a regular function, so this.contacts fails. Use an arrow and async/await with try/catch.
  5. No debounce, no stale-response guard – a call on every keystroke, and results can arrive out of order.
  6. sort in a getter – mutates the array in place on every render, and the comparator returns a boolean instead of a number. Use toSorted((a, b) => a.LastName.localeCompare(b.LastName)), ideally computed once.
  7. Event name – 'onContactSelect' should be lowercase without "on": 'contactselect'. Send an id or a copy, not the internal object; and use currentTarget with a data-id, not an index.

Here's a corrected version for comparison:

// contactList.js – fixed
import { LightningElement, api, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
import searchContacts from '@salesforce/apex/ContactController.searchContacts';
import { reduceErrors } from 'c/ldsUtils';

const SEARCH_DELAY = 300;

export default class ContactList extends LightningElement {
    @api recordId;
    contacts = [];
    error;
    searchTimer;
    latestSearch = 0;

    @wire(getContacts, { accountId: '$recordId' })
    wired({ data, error }) {
        if (data) {
            this.setContacts(data);
            this.error = undefined;
        } else if (error) {
            this.error = reduceErrors(error).join(', ');
        }
    }

    setContacts(records) {
        this.contacts = records
            .map((c) => ({ ...c, FullName: `${c.FirstName ?? ''} ${c.LastName}`.trim() }))
            .toSorted((a, b) => a.LastName.localeCompare(b.LastName));
    }

    handleSearch(event) {
        const term = event.target.value;
        clearTimeout(this.searchTimer);
        // eslint-disable-next-line @lwc/lwc/no-async-operation
        this.searchTimer = setTimeout(() => this.runSearch(term), SEARCH_DELAY);
    }

    async runSearch(term) {
        const requestId = ++this.latestSearch;
        try {
            const result = await searchContacts({ term });
            if (requestId === this.latestSearch) this.setContacts(result);
        } catch (e) {
            this.error = reduceErrors(e).join(', ');
        }
    }

    handleSelect(event) {
        const contactId = event.currentTarget.dataset.id;
        this.dispatchEvent(new CustomEvent('contactselect', { detail: { contactId } }));
    }

    disconnectedCallback() {
        clearTimeout(this.searchTimer);
    }
}

Practice

Try it yourself

  1. Without running it, what does this print? console.log('a'); setTimeout(() => console.log('b')); Promise.resolve().then(() => console.log('c')); console.log('d');

    Show answer

    a, d, c, b – synchronous first, then the microtask, then the timer.

  2. In one sentence each, explain to an interviewer why LWC uses getters instead of template expressions, and why you prefer immutable updates.

    Show answer

    Getters keep templates simple and put logic in testable JavaScript; immutable updates make every change visible to LWC's reactivity and work with read-only wire and @api data.

Summary

  • Know the JavaScript basics cold: scope, equality, this, closures, copying, array methods.
  • Explain async behaviour with the event loop, Promise.all and try/catch.
  • Connect each answer to LWC: reactivity, read-only data, shadow DOM, events, errors, tests.
  • In code reviews, look for mutation, lost this, missing cleanup and unhandled errors.

Want more practice? Try our LWC interview questions and JavaScript interview questions, or continue with the full Lightning Web Components course.

Finished this lesson?

Mark it complete to track your progress. You have reached the end of this track — well done!

Search LearnFrenzy

Esc

Quick links