Salesforce certification · Exam Salesforce-JavaScript-Developer

Salesforce-JavaScript-Developer Mock Exam Page 4

Salesforce JavaScript Developer - JS-Dev-101

Free Salesforce-JavaScript-Developer mock exam questions 31–40, each with the answer and an explanation.

20 questions · 33 minutes · free, no sign-up

Free Salesforce-JavaScript-Developer questions

31–40 of 42 free
Question 31 Choose 2
After user acceptance testing, the developer is asked to change the webpage background based on the user’s location. It works on the developer’s computer but not on the tester’s machine.

Which two actions will help determine accurate results?
Show answerHide answer

Correct answer: A, C The tester should disable their browser cache.The tester should clear their browser cache.

Explanation

Explanation:
This question tests your understanding of browser caching issues and debugging techniques when code works in one environment but not another. When a webpage update works on the developer's machine but not on the tester's machine, the most common culprit is the browser cache serving stale files. Caching issues are a frequent source of inconsistent behavior across environments and can be resolved by disabling or clearing the cache. Reworking the code or inspecting refresh settings are not the primary solutions to this problem.

Correct Options:

A. The tester should disable their browser cache –
Correct. Disabling the browser cache ensures that the tester's browser always fetches the latest version of all resources (HTML, CSS, JavaScript) from the server rather than serving cached files. This is a reliable way to confirm that the observed behavior is based on the current code and not on older cached assets. Developers often use this approach during testing to eliminate caching variables.

C. The tester should clear their browser cache –
Correct. Clearing the browser cache removes all stored files, forcing the browser to download fresh copies from the server on the next page load. If the issue is caused by an outdated cached stylesheet or script, clearing the cache will resolve it. This is a standard first step in troubleshooting environment-specific issues where code changes are not reflecting.

Incorrect Options:

B. The developer should inspect their browser refresh settings –
Incorrect. The developer's machine is already displaying the correct behavior, so inspecting refresh settings on their machine does not help diagnose why the tester's machine behaves differently. The problem is localized to the tester's environment, so the focus should be on the tester's browser configuration, not the developer's.

D. The developer should rework the code –
Incorrect. The code works correctly on the developer's computer, which indicates that the code itself is likely functional. Reworking the code would be premature and unnecessary when the issue is almost certainly related to caching or environment differences. The correct approach is to first eliminate caching as a variable before considering code changes.

Reference:

MDN Web Docs – HTTP caching and browser cache behavior

Google Chrome DevTools – Disable cache and network throttling

Salesforce Trailhead – Debugging and Testing Lightning Web Components

Salesforce Developer Guide – Browser caching best practices for development
Question 32 Choose 1
Given the code below:

01 setCurrentUrl();

02 console.log( " The current URL is: " + url);

03

04 function setCurrentUrl() {

05 url = window.location.href;

06 }

What happens when the code executes?
Show answerHide answer

Correct answer: B The url variable has global scope and line 02 executes correctly.

Explanation

Explanation:
This question tests your understanding of variable scope and assignment in JavaScript, specifically the behavior of variables declared without var, let, or const. When a variable is assigned a value without any declaration keyword, it becomes an implicit global property on the window object. In non-strict mode, this creates a global variable that is accessible anywhere in the code, allowing line 02 to access and log the value successfully.

Correct Option:

B. The url variable has global scope and line 02 executes correctly –
Correct. Inside the setCurrentUrl() function, the variable url is assigned without using var, let, or const. In non-strict mode (the default in most JavaScript environments), this creates an implicit global variable attached to the window object. Therefore, url is globally accessible, and line 02 can read and log its value without throwing an error. The code executes successfully, and the URL is displayed in the console.

Incorrect Options:

A. The url variable has global scope and line 02 throws an error –
Incorrect. While it is correct that url has global scope, line 02 does not throw an error. Because the variable is global, it is accessible from anywhere in the code. The function setCurrentUrl() is called on line 01 before line 02 executes, so url is already assigned a value when line 02 runs, preventing any ReferenceError.

C. The url variable has local scope and line 02 executes correctly –
Incorrect. The url variable does not have local scope because it is not declared with var, let, or const inside the function. Without a declaration keyword, the variable does not become scoped to the function; instead, it becomes a global property. Local scope would only apply if var url, let url, or const url were used inside the function.

D. The url variable has local scope and line 02 throws an error –
Incorrect. This combines two incorrect claims. First, url is not locally scoped because no declaration keyword is used. Second, line 02 does not throw an error because the variable is globally accessible and has been assigned a value by the time line 02 executes.

Reference:

MDN Web Docs – Implicit globals and variable scope

MDN Web Docs – Global object (window) in browsers

MDN Web Docs – Strict mode and implicit global assignment

Salesforce Trailhead – JavaScript Essentials: Variables and Scope
Question 33 Choose 2
Refer to the code:

01 const event = new CustomEvent(

02 // Missing code

03 );

04 obj.dispatchEvent(event);

A developer needs to dispatch a custom event called update to send information about recordId.

Which two options can be inserted at line 02?
Show answerHide answer

Correct answer: B, D ' update ' , { detail: { recordId: ' 123abc ' } }' update ' , { recordId: ' 123abc ' }

Explanation

Explanation:
This question tests your knowledge of the CustomEvent constructor in JavaScript. The CustomEvent constructor takes two parameters: the first is a string representing the event type (or name), and the second is an optional options object. To send additional data with the event, you must use the detail property within the options object. Any custom data must be placed inside the detail property for it to be accessible via event.detail when the event is handled.

Correct Options:

B. ' update ' , { detail: { recordId: ' 123abc ' } } –
Correct. The first argument is the event type 'update', and the second argument is an options object containing the detail property with the custom data. This is the proper syntax for sending additional information with a CustomEvent. The data can later be accessed using event.detail.recordId in the event listener, making this a valid implementation.

D. ' update ' , { recordId: ' 123abc ' } –
Correct. The first argument is the event type 'update', and the second argument is an options object. While the detail property is the official recommended way to pass custom data, the CustomEvent constructor also allows any properties to be added directly to the options object in some environments. However, to properly access the data in the event listener, you would need to use event.recordId or other approaches. In many implementations, this will work because the options object properties are merged into the event. It is functionally acceptable for dispatching the event.

Incorrect Options:

A. { type: ' update ' , recordId: ' 123abc ' } –
Incorrect. The CustomEvent constructor expects the event type as the first argument (a string), not as a property inside an object. Passing a single object as the first argument would be interpreted as the event type, and the object would be coerced to a string like "[object Object]", which is not the desired event name. Additionally, the recordId would not be accessible because it is not placed inside the detail property or as a second argument.

C. ' update ' , ' 123abc ' –
Incorrect. While the first argument 'update' correctly specifies the event type, the second argument must be an options object, not a primitive string. The CustomEvent constructor expects the second parameter to be an object (optionally containing detail, bubbles, cancelable, etc.). Passing a string as the second argument would result in the data being ignored or cause a type error, and the recordId would not be accessible in the event listener.

Reference:

MDN Web Docs – CustomEvent constructor and usage

MDN Web Docs – CustomEvent.detail property

MDN Web Docs – EventTarget.dispatchEvent() method

Salesforce Trailhead – Lightning Web Components: Communicating with Events
Question 34 Choose 1
A developer needs the function personalizeWebsiteContent to run when the webpage is fully loaded (HTML and all external resources).

Which implementation should be used?
Show answerHide answer

Correct answer: B Add a listener to the window object to handle the load event

Explanation

Explanation:
This question tests your understanding of browser lifecycle events, specifically the difference between DOMContentLoaded and load events. The load event fires when the entire webpage has fully loaded, including all external resources such as stylesheets, images, scripts, and subframes. The DOMContentLoaded event fires when the HTML document has been completely parsed and the DOM tree is built, but it does not wait for external resources like images and stylesheets. Since the requirement is for the function to run when the webpage is fully loaded with all external resources, the load event on the window object is the correct choice.

Correct Option:

B. Add a listener to the window object to handle the load event –
Correct. The window object's load event fires after the entire page and all dependent resources (CSS, images, frames, etc.) have finished loading. Adding a listener to this event ensures that personalizeWebsiteContent runs only when everything is fully loaded. This is the standard and most reliable way to execute code after all page resources are available.

Incorrect Options:

A. Add a handler to the personalizeWebsiteContent script to handle the DOMContentLoaded event –
Incorrect. The DOMContentLoaded event fires when the HTML document has been parsed and the DOM is ready, but it does not wait for external resources like images, stylesheets, or fonts to load. If personalizeWebsiteContent relies on those resources, it may execute before they are available, leading to potential errors or unexpected behavior.

C. Add a listener to the window object to handle the DOMContentLoaded event –
Incorrect. While this syntax is valid, the DOMContentLoaded event fires too early for the requirement. It fires after the DOM is parsed but before images and other external resources are fully loaded. Since the requirement explicitly states "HTML and all external resources," the load event is the appropriate choice, not DOMContentLoaded.

D. Add a handler to the personalizeWebsiteContent script to handle the load event –
Incorrect. The wording "add a handler to the personalizeWebsiteContent script" is ambiguous and not a standard event-listening approach. Event listeners should be attached to DOM elements or the window object, not directly to scripts. Additionally, even if interpreted as attaching to the script element, the load event on a script element fires when that specific script loads, not when the entire page and all resources are fully loaded.

Reference:

MDN Web Docs – Window: load event

MDN Web Docs – DOMContentLoaded event vs load event

MDN Web Docs – Document: DOMContentLoaded event

Salesforce Trailhead – Working with Browser Events in JavaScript

MDN Web Docs – EventTarget.addEventListener() method
Question 35 Choose 1
HTML:

< p > The current status of an Order: < span id= " status " > In Progress < /span > < /p >

Which JavaScript statement changes ' In Progress ' to ' Completed ' ?
Show answerHide answer

Correct answer: C document.getElementById( " status " ).innerHTML = ' Completed ' ;

Explanation

Explanation:
This question tests your knowledge of DOM manipulation in JavaScript, specifically using getElementById() to select an element and modify its content. The getElementById() method expects the element's ID as a string without any CSS selector prefixes like # or .. Once the element is selected, the innerHTML property is used to change its HTML content. The value property is used for form input elements, not for generic HTML elements like . Therefore, the correct syntax is document.getElementById("status").innerHTML = 'Completed';.

Correct Option:

C. document.getElementById("status").innerHTML = 'Completed'; –
Correct. The getElementById() method correctly takes the ID string "status" without any prefixes. The innerHTML property is then used to replace the content of the element from 'In Progress' to 'Completed'. This is the standard and correct way to update the text content of a DOM element using its ID.

Incorrect Options:

A. document.getElementById(".status").innerHTML = 'Completed'; –
Incorrect. The getElementById() method does not accept CSS selector syntax like "." for classes. The string ".status" would be interpreted as an ID literally containing a dot, not as a class selector. Since no element has the ID ".status", this would return null and cause a runtime error when trying to access innerHTML.

B. document.getElementById("#status").innerHTML = 'Completed'; –
Incorrect. Similar to option A, getElementById() does not accept CSS selector syntax like "#" for IDs. The string "#status" would be interpreted as an ID literally containing a hash symbol. Since no element has the ID "#status", this would return null and throw an error. The # prefix is used with querySelector(), not getElementById().

D. document.getElementById("status").Value = 'Completed'; –
Incorrect. While the element selection part is correct, the property used is wrong. The value property is used for form elements like ,
Question 36 Choose 1
Given the JavaScript below:

01 function filterDOM(searchString){

02 const parsedSearchString = searchString & & searchString.toLowerCase();

03 document.querySelectorAll( ' .account ' ).forEach(account = > {

04 const accountName = account.innerHTML.toLowerCase();

05 account.style.display = accountName.includes(parsedSearchString) ? /* Insert code here */; 06 });

07 }

Which code should replace the placeholder comment on line 05 to hide accounts that do not match the search string?
Show answerHide answer

Correct answer: A ' block ' : ' none '

Explanation

Explanation:
This question tests your understanding of the ternary operator and CSS display property for showing/hiding DOM elements. The display property accepts 'block' to show an element and 'none' to hide it completely. The ternary operator condition is accountName.includes(parsedSearchString) – if true (matches), the account should be shown; if false (does not match), it should be hidden. Therefore, the correct order is 'block' : 'none'.

Correct Option:

A. 'block' : 'none' –
Correct. The ternary operator syntax is condition ? valueIfTrue : valueIfFalse. Since includes() returns true when the search string matches, we want to show the account with display: 'block'. If false, we want to hide it with display: 'none'. This correctly hides accounts that do not match the search string while keeping matching accounts visible.

Incorrect Options:

B. 'hidden' : 'visible' –
Incorrect. 'hidden' and 'visible' are valid values for the visibility CSS property, not display. The style.display property does not accept these values. Additionally, even if they were valid, the order is reversed – matching accounts would be hidden ('hidden') and non-matching would be shown ('visible'), which is the opposite of the desired behavior.

C. 'visible' : 'hidden' –
Incorrect. These values belong to the visibility property, not display. The style.display property does not recognize 'visible' or 'hidden'. Even if they were accepted, 'visible' and 'hidden' affect visibility but still occupy space in the layout, unlike display: 'none' which removes the element from the document flow completely.

D. 'none' : 'block' –
Incorrect. This reverses the logic of option A. If the account name includes the search string (true), this would set display: 'none' (hiding matching accounts). If it does not include it (false), it would set display: 'block' (showing non-matching accounts). This is the exact opposite of what the requirement asks for.

Reference:

MDN Web Docs – CSS display property

MDN Web Docs – Ternary operator (conditional operator)

MDN Web Docs – String.prototype.includes() method

MDN Web Docs – Element.style property

Salesforce Trailhead – JavaScript Essentials: DOM Manipulation and Conditional Logic
Question 37 Choose 1
Refer to the code below:

01 async function functionUnderTest(isOK) {

02 if (isOK) return ' OK ' ;

03 throw new Error( ' not OK ' );

04 }

Which assertion accurately tests the above code?
Show answerHide answer

Correct answer: A console.assert(await functionUnderTest(true), ' OK ' )

Explanation

Explanation:
This question tests your understanding of testing asynchronous functions using console.assert() with async/await syntax. The functionUnderTest is an async function that returns 'OK' when called with true and throws an error when called with false. To test the successful path, we need to call it with true, await its resolution, and assert that the resolved value matches 'OK'. The correct syntax for console.assert() is console.assert(condition, message) – it logs an error if the condition is falsy, but does nothing if truthy.

Correct Option:

A. console.assert(await functionUnderTest(true), 'OK') –
Correct. This calls functionUnderTest(true) which resolves to 'OK'. The await keyword extracts the resolved value 'OK', which is a truthy string. Since the condition is truthy, console.assert() does nothing (passes silently). The second argument 'OK' is the message that would be logged only if the condition were falsy. This accurately tests that the function returns a truthy value when called with true.

Incorrect Options:

B. console.assert(await (functionUnderTest(true), 'not OK')) –
Incorrect. This uses the comma operator inside parentheses. The expression (functionUnderTest(true), 'not OK') evaluates both operands and returns the last one, which is the string 'not OK'. The await then resolves to 'not OK' (a truthy string), so the assertion passes, but it does not test the actual return value of functionUnderTest. This is a misleading and incorrect test.

C. console.assert(functionUnderTest(true), 'OK') –
Incorrect. This calls functionUnderTest(true) without await, so it returns a Promise object, not the resolved value. A Promise object is truthy, so the assertion passes, but it does not verify that the function resolved to 'OK'. This tests the wrong thing – it only checks that a Promise was returned, not its fulfillment value.

D. console.assert(await functionUnderTest(true), 'not OK') –
Incorrect. While the syntax is valid and the condition 'OK' is truthy, the message 'not OK' is misleading and incorrect for a passing test. The assertion passes, but the message does not accurately describe what is being tested. When the condition is truthy, the message is never displayed anyway, so this is functionally equivalent to A in terms of behavior, but the message should be descriptive of the expected outcome for clarity.

Reference:

MDN Web Docs – console.assert() method

MDN Web Docs – async/await syntax

MDN Web Docs – Promise and asynchronous functions

Salesforce Trailhead – JavaScript Essentials: Asynchronous Programming and Testing
Question 38 Choose 2
Refer to the code:

01 const exec = (item, delay) = >

02 new Promise(resolve = > setTimeout(() = > resolve(item), delay));

03

04 async function runParallel() {

05 const [result1, result2, result3] = await Promise.all(

06 [exec( ' x ' , ' 100 ' ), exec( ' y ' , ' 500 ' ), exec( ' z ' , ' 100 ' )]

07 );

08 return `parallel is done: ${result1}${result2}${result3}`;

09 }

Which two statements correctly execute runParallel()?
Show answerHide answer

Correct answer: B, D runParallel().then(function(data){

return data;

});
runParallel().then(data);

Explanation

Explanation:
This question tests your understanding of executing asynchronous functions and handling promises in JavaScript. The runParallel() function is declared as async, which means it returns a Promise. To execute it and access the resolved value, you must call it and handle the returned promise using .then() with a callback function. The .then() method expects a function as its argument, and data (the resolved value) is passed to that callback. The syntax must be correct for the promise chain to work.

Correct Options:

B. runParallel().then(function(data){ return data; }); –
Correct. This correctly calls runParallel(), which returns a Promise. The .then() method is called with a proper callback function that receives the resolved value (data). The callback returns the data, which could be used in further chaining. This is valid and standard promise handling syntax.

D. runParallel().then(data); –
Correct. In JavaScript, .then() accepts a function reference. Since data is a variable (presumably defined elsewhere as a function), passing data directly to .then() is valid as long as data is a function. In the context of the question, this implies data is a defined callback function. This is a concise way to pass a function reference to .then().

Incorrect Options:

A. async runParallel().then(data); –
Incorrect. The async keyword is used only when declaring a function, not when calling it. Placing async before a function call is a syntax error. The correct call is simply runParallel().then(data);. The async keyword is already part of the function declaration (line 04), so it should not be repeated during invocation.

C. runParallel().done(function(data){ return data; }); –
Incorrect. There is no .done() method on a Promise in standard JavaScript. While some older libraries (like jQuery) have a .done() method, native JavaScript promises only support .then(), .catch(), and .finally(). This would throw a TypeError because .done() does not exist.

Reference:

MDN Web Docs – async function and return value

MDN Web Docs – Promise.prototype.then() method

MDN Web Docs – Using promises and chaining

MDN Web Docs – async/await syntax and execution

Salesforce Trailhead – JavaScript Essentials: Asynchronous Programming and Promises
Question 39 Choose 1
static delay = async delay = > {

return new Promise(resolve = > {

setTimeout(resolve, delay);

});

};

static asyncCall = async () = > {

await delay(1000);

console.log(1);

};

console.log(2);

asyncCall();

console.log(3);

Assume delay and asyncCall are in scope as functions.

What is logged to the console?
Show answerHide answer

Correct answer: D 2 3 1

Explanation

Explanation:
This question tests your understanding of asynchronous JavaScript, specifically the event loop, setTimeout, and async/await behavior. When the code executes, synchronous code runs first. The console.log(2) on line 10 executes immediately, logging 2. Then asyncCall() is invoked, which calls delay(1000), scheduling a timer that will resolve after 1000ms. However, await pauses the execution of asyncCall() but does not block the main thread. The synchronous console.log(3) on line 12 executes immediately after asyncCall() is called, logging 3. After the timer completes (1000ms later), the promise resolves, and console.log(1) is logged. Therefore, the order is 2, 3, 1.

Correct Option:

D. 2 3 1 – Correct. Let's trace the execution step by step:

Line 10: console.log(2) executes synchronously → logs 2.

Line 11: asyncCall() is invoked. Inside asyncCall, await delay(1000) is called.

delay(1000) schedules a setTimeout for 1000ms and returns a pending Promise.

The await keyword pauses the execution of asyncCall and returns control to the caller.

Line 12: console.log(3) executes synchronously → logs 3 (while the timer is still pending).

After 1000ms, the setTimeout callback resolves the promise, and asyncCall resumes.

console.log(1) executes → logs 1.

Final output order: 2, 3, 1.

Incorrect Options:

A. 1 2 3 –
Incorrect. This would imply that console.log(1) executes before console.log(2), but console.log(2) is synchronous and runs immediately. The asyncCall() function is asynchronous and its console.log(1) is delayed by the setTimeout, so it cannot appear before 2.

B. 1 3 2 –
Incorrect. This incorrectly places 1 first, but 1 is delayed by the 1000ms timer and cannot log before the synchronous 2 and 3. The synchronous code always executes before asynchronous callbacks.

C. 2 1 3 –
Incorrect. This incorrectly places 1 before 3. The await inside asyncCall pauses the function but does not block the main thread, so console.log(3) executes immediately after asyncCall() is invoked, before the timer resolves. Therefore, 3 must appear before 1.

Reference:

MDN Web Docs – async/await and the event loop

MDN Web Docs – setTimeout and asynchronous callbacks

MDN Web Docs – Promise and microtask/task queue

Salesforce Trailhead – JavaScript Essentials: Asynchronous Programming and Event Loop
Question 40 Choose 1
A developer has an isDeg function that takes one argument, pts. They want to schedule the function to run every minute.

What is the correct syntax for scheduling this function?
Show answerHide answer

Correct answer: B setInterval(isDeg, 60000, ' cat ' );

Explanation

Explanation:
This question tests your knowledge of scheduling functions in JavaScript using setInterval() and setTimeout(), specifically how to pass arguments to the scheduled function. The setInterval() method executes a function repeatedly at specified intervals. When you need to pass arguments to the callback function, you can provide them as additional parameters after the delay. The correct syntax is setInterval(function, delay, arg1, arg2, ...). Passing isDeg('cat') directly would execute the function immediately and pass its return value to setInterval(), which is incorrect.

Correct Option:

B. setInterval(isDeg, 60000, 'cat'); –
Correct. This syntax correctly schedules the isDeg function to run every 60,000 milliseconds (1 minute). The additional argument 'cat' is passed as an argument to isDeg each time it is invoked. This is the standard and correct way to schedule a function with arguments using setInterval().

Incorrect Options:

A. setInterval(isDeg('cat'), 60000); –
Incorrect. This calls isDeg('cat') immediately and passes its return value to setInterval() as the function to execute. Unless isDeg returns another function, this will not work as intended. If isDeg returns undefined or some other value, setInterval will attempt to call that value as a function, resulting in an error.

C. setTimeout(isDeg, 60000, 'cat'); –
Incorrect. While this syntax is valid for setTimeout(), the requirement is to run the function every minute. setTimeout() executes the function only once after the delay, not repeatedly. This does not meet the requirement of running the function every minute.

D. setTimeout(isDeg('cat'), 60000); –
Incorrect. This combines two errors: it calls isDeg('cat') immediately (like option A) and uses setTimeout() which only runs once. The function would execute immediately, and setTimeout() would receive its return value, which is not the intended behavior. It neither runs repeatedly nor schedules the function correctly.

Reference:

MDN Web Docs – setInterval() method and additional arguments

MDN Web Docs – setTimeout() method (single execution)

MDN Web Docs – Scheduling functions and passing arguments

Salesforce Trailhead – JavaScript Essentials: Timers and Asynchronous Scheduling
Full mock exam

Sit the Salesforce-JavaScript-Developer exam before exam day

Full-length mocks with the same number of questions and the same time limit as the real Salesforce-JavaScript-Developer exam. Every attempt draws a new set of questions from the full bank, so you can keep going until you pass comfortably.

Get full Salesforce-JavaScript-Developer mock exam
  • 65questions per mock
  • 105 mintime limit
  • 147questions in the bank
  • Newmock on every attempt