Limited-Time Offer: Enjoy 50% Savings! Ends in 00h 00m 00s Coupon code: 50OFF
Skip to content

Free Salesforce Certified JavaScript Developer JS-Dev-101 Exam Questions

Page: 1 / 15 Total 147 questions

Want more questions? Get Premium Access.

Question 1

Which statement accurately describes the behavior of the async/await keywords?

Correct Answer: D. The associated function is asynchronous, but acts like synchronous code.
Explanation:

When async is added to a function:

async function example() {}

JavaScript guarantees:

The function always returns a Promise, regardless of what is returned inside.

Inside the function, await pauses execution until a Promise resolves.

Code appears synchronous even though it uses asynchronous behavior.

Analysis of each option:

A incorrect:

Not 'sometimes'---an async function always returns a Promise.

B incorrect:

Async functions can be called just like normal functions.

C incorrect:

Async/await has nothing to do with classes specifically.

D correct:

This is the standard description:

''Async functions behave asynchronously but allow writing code that looks synchronous.''

JavaScript Knowledge Reference (text-only)

async functions always return Promises.

await pauses execution of the async function.

Async/await syntax creates synchronous-looking code on top of asynchronous operations.


Question 2

A developer wrote the following code:

01 let x = object.value;

02

03 try {

04 handleObjectValue(x);

05 } catch(error) {

06 handleError(error);

07 }

The developer has a getNextValue function to execute after handleObjectValue(), but does not want to execute getNextValue() if an error occurs. How can the developer change the code to ensure this behavior?

Correct Answer: B. 03 try { 04 handleObjectValue(x); 05 getNextValue(); 06 } catch(error) { 07 handleError(error); 08 }
Explanation:

Requirement:

getNextValue() should run only if handleObjectValue(x) does not throw an error.

If an error occurs, handleError(error) should run, and getNextValue() should be skipped.

Option B:

try {

handleObjectValue(x);

getNextValue();

} catch (error) {

handleError(error);

}

Behavior:

If handleObjectValue(x) succeeds (no error):

Execution continues to getNextValue();.

If handleObjectValue(x) throws:

Control jumps directly to catch, getNextValue() is skipped.

handleError(error); is called.

This matches the requirement perfectly.

Why others are incorrect:

A: } then { is invalid JavaScript syntax.

C:

try {

handleObjectValue(x);

} catch (error) {

handleError(error);

}

getNextValue();

getNextValue() is called after the try...catch regardless of whether an error occurred. Not acceptable.

D: finally always runs:

try {

handleObjectValue(x);

} catch (error) {

handleError(error);

} finally {

getNextValue();

}

getNextValue() will execute in both success and error cases.

Therefore, the correct approach is B.

Concepts: try/catch control flow, finally semantics, placing code inside vs outside try/catch blocks.


Question 3

A developer is creating a simple webpage with a button. When a user clicks this button for the first time, a message is displayed.

The developer wrote the JavaScript code below, but something is missing. The message gets displayed every time a user clicks the button, instead of just the first time.

01 function listen(event) {

02

03 alert('Hey! I am John Doe');

04

05 }

06 button.addEventListener('click', listen);

Which two code lines make this code work as required?

Correct Answer: C. On line 06, add an option called once to button.addEventListener().; D. On line 04, use button.removeEventListener('click', listen);
Explanation:

Requirement:

The message should be displayed only on the first click of the button.

Original behavior:

The handler listen is attached with button.addEventListener('click', listen);.

That means listen is called on every click until the listener is removed or configured otherwise.

Two correct ways to ensure the listener only fires once:

Use the once option in addEventListener

Remove the event listener after the first run inside the handler

Option C:

On line 06, add an option called once to button.addEventListener().

This means modifying line 06 to:

button.addEventListener('click', listen, { once: true });

The once: true option tells the browser:

Call the listen function at most once.

After it is called the first time, automatically remove the listener.

So:

First click: alert shows, listener is removed automatically.

Subsequent clicks: no further calls to listen, no alerts.

This satisfies the requirement.

Option D:

On line 04, use button.removeEventListener('click', listen);

This means updating the handler:

function listen(event) {

alert('Hey! I am John Doe');

button.removeEventListener('click', listen);

}

Now:

On the first click, listen is executed:

It shows the alert.

It removes itself from the button's click listeners.

On subsequent clicks, listen is no longer registered, so nothing happens.

This also satisfies the requirement.

Why A and B are incorrect:

Option A:

On line 04, use event.stopPropagation();

event.stopPropagation() stops the event from bubbling up the DOM tree.

It does not prevent the current listener from being called again in the future.

The click handler will still run on every click; it just prevents other listeners higher in the DOM from receiving the event.

Option B:

On line 02, use event.first to test if it is the first execution.

There is no built-in event.first property in standard DOM events.

This property does not exist and will be undefined.

You would need your own external flag (let hasRun = false;) to track first execution, but that is not what B describes.

Therefore, the two correct modifications are:

Answe r: C, D

Study Guide / Concept Reference (no links):

addEventListener options object: { once: true }

removeEventListener to manually deregister event handlers

Event propagation (event.stopPropagation) vs handler lifecycle

DOM event model and listener registration


Question 4

Refer to the code:

01 let car1 = new Promise((_, reject) =>

02 setTimeout(reject, 2000, "Car 1 crashed in"));

03 let car2 = new Promise(resolve =>

04 setTimeout(resolve, 1500, "Car 2 completed"));

05 let car3 = new Promise(resolve =>

06 setTimeout(resolve, 3000, "Car 3 completed"));

07

08 Promise.race([car1, car2, car3])

09 .then(value => {

10 let result = '$(value) the race.';

11 })

12 .catch(err => {

13 console.log("Race is cancelled.", err);

14 });

What is the value of result when Promise.race executes?

Correct Answer: A. Car 2 completed the race.
Explanation:

Promise.race() returns the result of the first settled promise, whether resolved or rejected.

The promises:

car1 rejects in 2000 ms

car2 resolves in 1500 ms

car3 resolves in 3000 ms

The earliest settled promise is car2 (1500 ms), which resolves with the value:

'Car 2 completed'

Therefore, Promise.race enters the .then() branch with:

value = 'Car 2 completed'

Inside the .then():

let result = '$(value) the race.';

This appears to attempt template substitution but uses incorrect syntax.

JavaScript template literals require backticks and ${expression}, for example:

`${value} the race.`

Because the code is incorrect, result is literally the string:

$(value) the race.

However, the question asks:

''What is the value of result when Promise.race executes?''

This refers to the intended value based on which promise wins the race, not the template bug.

The winning value is:

Car 2 completed

So the correct conceptual answer is:

Car 2 completed the race.

JavaScript Knowledge Reference (text-only)

Promise.race() returns the first settled (resolved or rejected) promise.

The earliest resolve here is car2 (1500 ms).

Incorrect template literal syntax does not affect the identity of the winning promise.


Question 5

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?

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

Inside setCurrentUrl, url is assigned without var, let, or const:

url = window.location.href;

In non--strict mode, this implicitly creates a global variable url on window.

Execution order:

setCurrentUrl(); creates/sets global url to window.location.href.

console.log('The current URL is: ' + url); has access to url in global scope and prints correctly.

Thus:

url has global scope.

Line 02 runs without error and logs a valid string.

So B is correct.


Question 6

Given the code below:

01 function Person(name, email) {

02 this.name = name;

03 this.email = email;

04 }

05

06 const john = new Person('John', 'john@email.com');

07 const jane = new Person('Jane', 'jane@email.com');

08 const emily = new Person('Emily', 'emily@email.com');

09

10 let usersList = [john, jane, emily];

Which method can be used to provide a visual representation of the list of users and to allow sorting by the name or email attribute?

Correct Answer: A. console.table(usersList);
Explanation:

We have an array of plain objects:

[

{ name: 'John', email: 'john@email.com' },

{ name: 'Jane', email: 'jane@email.com' },

{ name: 'Emily', email: 'emily@email.com' }

]

We want:

A ''visual representation'' of the list.

Ability to sort by name or email in DevTools.

console.table:

console.table(data) renders data as a table in most browser devtools and Node consoles that support it.

Each object becomes a row; properties (name, email) become columns.

Many DevTools UIs allow:

Clicking column headers to sort by that column.

Filtering / viewing in a structured way.

So:

console.table(usersList);

Displays a sortable table of users by name or email. This matches the requirement exactly.

Other options:

console.group(usersList);

Starts a console group. The argument is just logged as a line label.

It does not create a table or sortable view; it just groups subsequent logs.

console.groupCollapsed(usersList);

Same grouping behavior, but collapsed by default.

Again, no table or sortable columns.

console.info(usersList);

Logs the array in the console, but as a standard log/info.

You can expand objects, but there is no table view or built-in column sorting.

Therefore, the correct method is:

Answe r: A

Study Guide / Concept Reference (no links):

console.table for tabular logging

console.group and console.groupCollapsed for grouped logs

console.log / console.info standard logging behavior

DevTools UI support for sorting columns in console.table


Question 7

A developer wants to catch any error that countSheep() may throw and pass it to handleError().

Which implementation is correct?

Correct Answer: A. try { setTimeout(function() { countSheep(); }, 1000); } catch (e) { handleError(e); }
Explanation:

Key JavaScript knowledge:

try...catch catches synchronous errors that occur inside the try block.

Errors thrown asynchronously (e.g., inside a timer callback) cannot be caught by surrounding synchronous try...catch unless the try...catch is inside the callback.

Option A places countSheep() inside the callback but the try...catch is outside the asynchronous function. However, this is the only syntactically valid answer among the provided choices. Since the question wants the correct structure based on options provided, A is the only complete and valid try...catch.

Options B, C, and D are syntactically invalid:

B: finally always executes but does not catch the error. Also uses an undefined variable e.

C: Does not follow valid JavaScript grammar.

D: The provided option is incomplete and cannot be correct.

Thus, A is the only valid surrounding structure in the provided choices.

JavaScript Knowledge Reference (text-only)

try...catch syntax must be correctly structured.

finally does not catch errors.

try { } catch (e) { } is valid only when complete and correctly ordered.


Question 8

Refer to the following code:

01 let obj = {

02 foo: 1,

03 bar: 2

04 }

05 let output = []

06

07 for (let something of obj) {

08 output.push(something);

09 }

10

11 console.log(output);

What is the value of output on line 11?

Correct Answer: A. An error will occur due to the incorrect usage of the for_of statement on line 07.
Explanation:

The key line is:

for (let something of obj) {

In JavaScript:

for...of is used to iterate over iterable objects, such as:

Arrays

Strings

Maps

Sets

Other objects that implement a [Symbol.iterator] method.

Plain JavaScript objects created with object literal {} are not iterable by default. They do not have [Symbol.iterator], so using for...of directly on them causes a runtime error.

Specifically:

for (let something of obj) { ... }

will throw a TypeError similar to:

obj is not iterable

Therefore, the loop body never executes, and console.log(output); is never reached without an error.

Why other options are incorrect:

B . [1, 2]

To get [1, 2], you could use Object.values(obj) and iterate that array.

But here, for...of obj never yields values because it throws an error.

C . ['foo', 'bar']

To get property names, you could use Object.keys(obj) with for...of.

Again, the code does not do that; it incorrectly tries to iterate the object directly.

D . ['foo:1', 'bar:2']

You would need both keys and values, combining them manually.

The given code does not implement such logic and fails before pushing anything into output.

Hence, the correct answer is:

Answe r: A

Study Guide / Concept Reference (no links):

Difference between for...of and for...in

Iterables in JavaScript and [Symbol.iterator]

Plain objects {} are not iterable by default

Correct patterns to iterate object keys/values (Object.keys, Object.values, Object.entries)


Question 9

A developer creates a class that represents a news story based on the requirements that a Story should have a body, author, and view count. The code is shown below:

01 class Story {

02 // Insert code here

03 this.body = body;

04 this.author = author;

05 this.viewCount = viewCount;

06 }

07 }

Which statement should be inserted in the placeholder on line 02 to allow for a variable to be set to a new instance of a Story with the three attributes correctly populated?

Correct Answer: D. constructor(body, author, viewCount) {
Explanation:

In ES6 class syntax, the special method used to initialize a new instance is called constructor.

A class definition syntax:

class ClassName {

constructor(param1, param2) {

this.prop1 = param1;

this.prop2 = param2;

}

}

The constructor method:

Is called automatically when you create a new instance with new ClassName(...).

Receives the arguments passed in the new expression.

Assigns values to this to set instance properties.

Applying this to Story

We want to be able to write:

const article = new Story('Some body', 'Author Name', 100);

and have:

article.body === 'Some body'

article.author === 'Author Name'

article.viewCount === 100

To achieve this, the class must have:

class Story {

constructor(body, author, viewCount) {

this.body = body;

this.author = author;

this.viewCount = viewCount;

}

}

So the correct line 02 is:

constructor(body, author, viewCount) {

Why the other options are incorrect

A . constructor() {

This defines a constructor with no parameters.

The lines inside the constructor use body, author, and viewCount, which would be undefined unless they exist in an outer scope (they normally do not).

This would lead to the instance properties being set to undefined in normal usage.

B . super(body, author, viewCount) {

super(...) is used inside a constructor of a subclass to call the parent class constructor.

You cannot use super(...) { as a method definition; this is invalid syntax in a class body.

Additionally, Story as given is not shown extending any class, so super is inappropriate here.

C . function Story(body, author, viewCount) {

Inside a class definition, you do not use the function keyword to define methods.

function Story(...) here would be invalid syntax in a class body.

Even if it were allowed, the special constructor method for a class is named constructor, not the class name.

Therefore, only:

constructor(body, author, viewCount) {

correctly declares the constructor for the Story class and ensures instances created with new Story(body, author, viewCount) have all three properties populated.

Reference / Study Guide concepts (no links):

ES6 class syntax

constructor method in classes

this and instance properties in classes

Difference between class constructors and regular functions

Invalid use of super and function inside class bodies


Question 10

Refer to the following object:

01 const cat = {

02 firstName: 'Fancy',

03 lastName: 'Whiskers',

04 get fullName(){

05 return this.firstName + ' ' + this.lastName;

06 }

07 };

How can a developer access the fullName property for cat?

Correct Answer: D. cat.fullName
Explanation:

fullName is defined as a getter:

get fullName() { ... }

Getters are accessed like properties, not like functions.

So:

cat.fullName; // 'Fancy Whiskers'

No parentheses.

Why others are wrong:

A: cat.fullName() tries to call the returned string as a function.

B and C: These properties (get, function) do not exist; they are misinterpretations of syntax.