Salesforce Javascript(set 1)

1) A developer writes the code below to calculate the factorial of a given number.

						function sum(number) {
						  return number + sum(number - 1);
						}
						sum(3)
					

What is the result of executing line 04?

  1. 0
  2. 6
  3. Error
  4. Infinity

2) Refer to the code below:

						const searchText = 'Yay! Salesforce is amazing!';
						let result1 = searchText.search(/sales/i);
						let result2 = searchText.search(/sales/);
						console.log(result1);
						console.log(result2);
					

After running this code, which result is displayed on the console?

  1. 5 and -1
  2. 5 and undefined
  3. 5 and 0
  4. true and false

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.

						function listen(event) { 
						  alert('Hey! I am John Doe');
						  button.addEventListener ('click', listen);
						}
					

Which two code lines make this code work as required? Choose 2 answers

  1. On line 02, use event.first to test if it is the first execution.
  2. On line 04, use event.stopPropagation ();
  3. On line 04, use button.removeEventListener(‘click’, listen);
  4. On line 06, add an option called once to button.addEventListener().

4) A developer wants to use a module named universalContainersLib and them call functions from it. How should a developer import every function from the module and then call the fuctions foo and bar ?

  1. import (foo, bar) from ‘/path/universalContainersLib.js’;
    foo();
    bar();
  2. import * from ‘/path/universalContaineraLib.js’;
    universalContainersLib.foo();
    universalContainersLib.bar();
  3. import all from ‘/path/universalContaineraLib.js’;
    universalContainersLib.foo();
    universalContainersLib.bar();
  4. import * as lib from ‘/path/universalContainersLib.js’;
    lib.foo();
    lib.bar();

5) Which two console logs outputs NaN? Choose 2 answers

  1. console.log(10/’five’);
  2. console.log(parseInt(‘two’));
  3. console.log(10/0);
  4. console.log(10/ Number(‘5’));

6) Consider type coercion, what does the following expression evaluate to?

						true + 3 + '100' + null
					

  1. ‘3100null’
  2. 104
  3. 4100
  4. ‘4100null’

7) Given HTML below:

						<div>
						<div id ="row-uc">Universal Container</div>
						<div id ="row-as">Applied Shipping</div>
						<div id ="row-bt">Burlington Textiles</div>
						</div>
					

Which statement adds the priority-account CSS class to the Applied Shipping row ?

  1. document.querySelectorALL(‘#row-as’).classList.add(‘priority-account’);
  2. document.querySelector(‘#row-as’).classList.add(‘priority-account’);
  3. document.querySelector(‘#row-as’).classes.push(‘priority-account’);
  4. document.queryElementById(‘row-as’).addclass(‘priority-account’);

8) Refer to the code below:

						const pi = 3.1415326;
					

What is the data type of pi?

  1. Float
  2. Decimal
  3. Number
  4. Double

9) Developer is required to write a function that calculates the sum of elements in an array but is getting undefined every time the code is executed. The developer needs to find what is missing in the code below.

						const sumFunction = arr => {
						  return arr.reduce((result, current) => {
						    Result += current;
						  ), 10);
						);
					

Which line replacement makes the code work as expected?

  1. Replace line 02 return arr.forEach((result, current) => (
  2. Add in line 03 if (arr.length == 0) { return 0; }
  3. Replace line 03 current = result + current;
  4. Add in line 04 return result;

10) Refer to the following code:

						<html lang="en">
						  <body>
						    <span onclick="console.log('Span message');">
						      <button id="myButton">Send message!</button>
						    </span>
						  </body>
						  <script>
						    function displayMessage(ev) {
						      ev.stopPropagation();
						      console.log("Button message");
						    }
						    const elem = document.getElementById("myButton");
						    elem.addEventListener('click', displayMessage);
						  </script>
						</html>
					

What will the console show when the button is clicked?

  1. Span message
  2. Button message Span message
  3. Span message Button message
  4. Button message

11) Refer to the code below:

						<html lang="en">
						  <table onclick="console.log('Table log');">
						    <tr id="row1">
						      <td>Click me!</td>
						    </tr>
						  <table>
						  <script>
						    function printMessage(event) {
						      console.log('Row log');
						    }
						    Let elem = document.getElementById('row1');
						    elem.addEventListener('click', printMessage, false);
						  </script>
						</html>
					

Which code change should be made for the console to log only Row log when ‘Click me!’ is clicked?

  1. Add event.stopPropagation(); to window.onLoad event handler.
  2. Add event.removeEventListener(); to printMessage function.
  3. Add event.stopPropagation (); to printMessage function.
  4. Add event.removeEventListener(); to window.onLoad event handler.

12) The developer wants to test this code:

						const stringifyNumber = (num) => Number(num).toString();
					

Which two tests are the most accurate for this code? Choose 2 answers

  1. console.assert(stringifyNumber() === ‘NaN’)
  2. console.assert(typeof stringifyNumber(2) === ‘string’)
  3. console.assert(stringifyNumber(-2) === ‘-2’)
  4. console.assert(stringifyNumber() == 0)

13) Given the code below:

						function myFunction() {
						 a = 5;
						 var b = 1;
						}
						myFunction();
						console.log(a);
						console.log(b);
					

What is the expected output?

  1. Line 06 throws an error, therefore line 07 is never executed.
  2. Both lines 06 and 07 are executed, and the variables are outputted.
  3. Line 06 outputs the variable, but line 07 throws an error.
  4. Both lines 06 and 07 are executed, but the values outputte are undefined.

14) Universal Containers recently launched its new landing page to host a crowd-funding campaign. The page uses an external library to display some third-party ads. Once the page is fully loaded, it creates more than 50 new HTML items placed randomly inside the DOM, like the one in the code below:

						<!-- This is an ad -->
						<div class="ad-library-item ad-hidden" onload="myFunction()">
						  <img src="/ad-library/ad01.gif"/>
						</div>
					

All the elements include the same ad-library-item class. They are hidden by default, and they are randomly displayed while the user navigates through the page. Tired of all the ads, what can the developer do to temporarily and quickly remove them?

  1. Use the DOM inspector to remove all the elements containing the class ad-library-item.
  2. Use the DOM inspector to prevent the load event to be fired.
  3. Use the browser console to execute a script that prevents the load event to be fired.
  4. Use the browser console to execute a script that removes all the elements containing the class ad-library-item.

15) A developer implements a function that adds a few values.

						function sum(num) {
						  if (num === undefined) {
						    num = 0;
						  }
						  return function(num2, num3) (
						    if (num3 === undefined) {
						      num3 = 0;
						    }
						    return num + num2 + num3;
						  }
						}
					

Which three options can the developer invoke for this function to get a return value of 10? Choose 3 answers

  1. sum(10)()
  2. sum()(5, 5)
  3. sum()(10)
  4. sum(5)(5)
  5. sum(5, 5)()

16) Given the code below:

						const delay = async delay => {
						  return new Promise((resolve, reject) => {
						    console.log(1);
						    setTimeout(resolve, delay);
						  });
						};
						const callDelay = async() => {
						  console.log(2);
						  const yup = await delay(1000)
						  console.log(3);
						};
						console.log(4);
						callDelay();
						console.log(5);
					

What is logged to the console?

  1. 14235
  2. 42135
  3. 42153
  4. 45123

17) Refer to the code below:

						function changeValue(obj) {
						  obj.value = obj.value / 2:
						}
						const objA = {value: 10};
						const objB = objA;
						changeValue(objB);
						const result = objA.value;
					

What is the value of result after the code executes?

  1. 10
  2. 5
  3. undefined
  4. NaN

18) Given the following code:

						let x = null;
						console.log(typeof x);
					

What is the output of the line 02?

  1. “undefined”
  2. “x”
  3. “null”
  4. “object”

19) Refer to the code below:

						let car1 = new Promise((_, reject) => setTimeout(reject, 2000, "Car 1 crashed in"));
						let car2 = new Promise(resolve => setTimeout(resolve, 1500, "Car 2 completed"));
						let car3 = new Promise(resolve => setTimeout(resolve, 3000, "Car 3 completed"));
						Promise.race([car1, car2, car3])
						  .then(value => {
						    let result = `${value} the race.`;
						    console.log(result);
						  }) 
						  .catch(err => {
						    console.log("Race is cancelled.", err);
						  });
					

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

  1. Race is cancelled.
  2. Car 1 crashed in the race.
  3. Car 2 completed the race.
  4. Car 3 completed the race.

20) Which statement phrases successfully?

  1. JSON.parse(‘foo’);
  2. JSON.parse(“‘foo'”);
  3. JSON.parse(‘”foo”‘);
  4. JSON.parse(“foo”);

21) A developer is asked to fix some bugs reported by users. To do that, the developer adds a breakpoint for debugging.

						function Car(maxSpeed, color) {
						  this.maxSpeed = maxSpeed;
						  this.color = color;
						}
						let carspeed = document.getElementById('carSpeed');
						debugger;
						let fourWheels = new Car(carSpeed.value, "red");
					

When the code execution stops at the breakpoint on line 06, which two types of information are available in the browser console? Choose 2 answers

  1. The style, event listeners and other attributes applied to the carSpeed DOM element.
  2. The information stored in the window.localStorage property.
  3. A variable displaying the number of instances created for the Car object.
  4. The values of the carSpeed and fourWheels variables.

22) Refer to the HTML below:

						<div id="main">
						  <ul>
						    <li>Leo</li>
						    <li>Tony</li>
						    <li>Tiger</li>
						  </ul>
						</div>
					

Which JavaScript statement results in changing “Leo” to “The Lion”?

  1. document.querySelector(‘#main li:second-child’).innerHTML = ‘The Lion’;
  2. document.querySelectorAll(‘#main #Leo’).innerHTML = ‘The Lion’;
  3. document.querySelector(‘#main li:nth-child(1)’).innerHTML = ‘The Lion’;
  4. document.querySelector(‘#main li.Leo’).innerHTML = ‘The Lion’;

23) Refer to the code below:

						for (let number 2; number <= 5; number += 1) {
						  // Insert code statement here
						}
					

The developer needs to insert a code statement in the location shown. The code statement has these requirements:

1) Does not require an import

2) Logs an error when the Boolean statement evaluates to false

3) Works in both the browser and Node.js

Which statement meets these requirements?

  1. console.assert(number % 2 === 0);
  2. console.debug(number % 2 === 0);
  3. assert (number % 2 === 0);
  4. console.error(number % 2 === 0);

24) Refer to the following code block:

						class Animal {
						  constructor(name) {
						    this.name = name;
						  }
						  makeSound() {
						    console.log(`${this.name} is making a sound.`);
						  }
						}
						class Dog extends Animal {
						  constructor(name) {
						    super(name);
						    this.name = name;
						  }
						  makeSound() {
						    console.log(`${this.name} is barking.`);
						  }
						}
						let myDog = new Dog("Puppy");
						myDog.makeSound();
					

What is the console output?

  1. Undefined
  2. Puppy is making a sound.
  3. Puppy is barking.
  4. Uncaught ReferenceError

25) A developer wants to create an object from a function in the browser using the code below:

						function Monster() {this.name = ‘hello’}; 
						Const m = Monster();
					

What happens due to lack of the new keyword on line 02?

  1. The m variable is assigned the correct object.
  2. window.name is assigned to ‘hello’ and the variable m remains undefined.
  3. The m variable is assigned the correct object but this.name remains undefined.
  4. window.m is assigned the correct object.

26) Refer to the code below:

						console.log('Start');
						Promise.resolve('Success').then(function(value) {
						  console.log('Success');
						});
						console.log('End');
					

What is the output after the code executes successfully?

  1. End Start Success
  2. Start Success End
  3. Success Start End
  4. Start End Success

27) Refer to the code below:

						const server require('server');
						// Insert code here
					

A developer imports a library that creates a web server. The imported library uses events and callbacks to start the server. Which code should be inserted at line 02 to set up an event and start the web server?

  1. server();
  2. server.start();
  3. server.on(‘connect’, (port) => {
      console.log(‘Listening on, port);
    });
  4. server((port) => {
      console.log(‘Listening on, port);
    });

28) Refer to the code below:

						Let inArray =[[ 1, 2 ], [ 3, 4, 5 ]];
					

Which two statements result in the array [1, 2, 3, 4, 5]? Choose 2 answers

  1. [].concat.apply(inArray, []);
  2. [].concat.apply([], inArray);
  3. [].concat(…inArray);
  4. [].concat([…inArray]);

29) Refer to the code below:

						const objBook = {
						  title: 'JavaScript',
						}
						Object.prevent Extensions (objBook);
						const newObjBook = objBook;
						newObjBook.author = 'Robert';
					

What are the values of objBook and newobjBook respectively?

  1. {author: “Robert”, title: “JavaScript”} undefined
  2. {author: “Robert”} {author: “Robert”, title: “JavaScript”}
  3. {title: “JavaScript”} {title: “JavaScript” }
  4. {author: “Robert”, title: “JavaScript”} {author: “Robert”, title: “JavaScript”}

30) Refer to the code below:

						let foodMenul = ['Pizza', 'Burger', 'French fries'];
						let finalMenu = foodMenul;
						finalMenu.push('Garlic bread');
					

What is the value of foodMenul after the code executes?

  1. [‘Garlic bread’, ‘Pizza’, ‘Burger’, ‘French fries’]
  2. [‘Garlic bread’]
  3. [‘Pizza’, ‘Burger’, ‘French fries’, ‘Garlic bread’]
  4. [‘Pizza’, ‘Burger’, ‘French fries’]

31) A developer tries to retrieve all cookies, then sets a certain key value pair in the cookie. These statements are used:

						document.cookie;
						document.cookie = "key=John Smith";
					

What is the behavior?

  1. Cookies are read and the key value is set, and all cookies are wiped.
  2. Cookies are read and the key value is set, the remaining cookies are unaffected.
  3. Cookies are not read because line 01 should be document.cookies, but the key value is set and all cookies are wiped.
  4. Cookies are read, but the key value is not set because the value is not URL encoded.

32) A developer uses the code below to format a date.

						const date = new Date(2020, 11, 10);
						const dateDisplayOptions = {
						  year: 'numeric',
						  month: long",
						  day: 'numeric'
						};
						const formattedDate = date.toLocaleDateString("en", dateDisplayOptions);
					

After executing, what is the value of formattedDate?

  1. December 10, 2020
  2. November 11, 2020
  3. October 11, 2020
  4. November 10, 2020

33) A team that works on a big project uses npm to deal with the project’s dependencies. A developer added a dependency to manipulate dates and pushed the updates to the remote repository. The rest of the team complains that the dependency does not get downloaded when they execute npm install.

Which two reasons could be possible explanations for this? Choose 2 answers.

  1. The developer missed the option –add when adding the dependency.
  2. The developer missed the option –save when adding the dependency.
  3. The developer added the dependency as a dev dependency, and NPM_ENV is set to production.
  4. The developer added the dependency as a dev dependency, and NODE_ENV is set to production.

34) 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:

						class Story {
						  // Insert code here
						    this.body = body;
						    this.author author;
						    this.viewCount = viewCount;
						  }
						}
					

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?

  1. function Story (body, author, viewCount) {
  2. super (body, author, viewCount) {
  3. constructor (body, author, viewCount) {
  4. constructor() {

35) Given the code below:

						function Person() {
						  this.firstName = 'John';
						}
						Person.proto = {
						    job: x => 'Developer";
						}
						const myFather new Person();
						const result = myFather.firstName + ' ' + myFather.job();
					

What is the value of result when line 8 executes?

  1. John Developer
  2. Error: myFather.job is not a function
  3. undefined Developer
  4. John undefined

36) Which statement accurately describes an aspect of promises?

  1. .then() manipulates and returns the original promise.
  2. .then () cannot be added after a catch.
  3. In a,then() function, returning results is not necessary since callbacks will catch the result of a previous promise.
  4. Arguments for the callback function passed to .then() are optional.

37) Refer to the following code block:

						let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
						let output = 0;
						for (let num of array) {
						  if (output > 10) {
						    break;
						  }
						  if (num % 2 == 0) {
						    continue
						  }
						  output += num;
						}
					

What is the value of output after the code executes?

  1. 16
  2. 25
  3. 11
  4. 36

38) Refer to the code below:

						let sayHello = () => {
						  console.log("Hello, World!');
						};
					

Which option executes sayHello once every two minutes?

  1. delay(sayHello, 120000)
  2. setInterval(sayHello, 120000);
  3. setTimeout(sayHello(), 120000);
  4. setTimeout(sayHello, 120000);

39) Which option is a core Node.js module?

  1. locale
  2. path
  3. ios
  4. memory

40) A developer has an ErrorHandler module that contains multiple functions. What kind of export should be leveraged so that multiple functions can be used?

  1. default
  2. named
  3. all
  4. multi

41) A developer has the function, shown below, that is called when a page loads.

						function onLoad() (
						  console.log("Page has loaded!");
						};
					

Where can the developer see the log statement after loading the page in the browser?

  1. Terminal running the web server
  2. Browser performance tools
  3. On the webpage
  4. Browser JavaScript console

42) Refer to the code below:

						let first = 'Who';
						let second = 'What';
						try {
						  try {
						    throw new Error('Sad trombone');
						  } catch(err) {
						    first = 'Why';
						    throw err;
						  } finally {
						    second = "When";
						  }
						} catch (err) {
						  second = 'Where';
						}
					

What are the values for first and second once the code executes?

  1. first is Why and second is Where.
  2. first is Who and second is Where.
  3. first is Who and second is When.
  4. first is Why and second is When.

43) Refer to the code below:

						const monthName = 'July';
						const year = 2019;
						if(monthName === 'July') {
						  year = 2020;
						}
					

A developer receives feedback from the Tech Lead that the code gives an error. Which line edit should the developer make so this code runs?

  1. if(monthName === July) (
  2. const year = 2019;
  3. let year = 2019;
  4. if(monthName === ‘July’) {

44) A developer writes the code below to return a message to a user attempting to register a new username. If the username is available, a variable named mag is declared and assigned a value on line 03.

						function getAvailabilityMessage(item) {
						  if (getAvailability(item)) (
						    var msg="Username available";
						  }
						return msg;
					

What is the value of msg when getAvailabilityMessage(“newUserName”) is executed and getAvailability(“newUserName”) returns true?

  1. undefined
  2. “newUserName”
  3. “msg is not defined”
  4. “Username available”

45) A developer wrote the following code to test a sum3 function that takes in an array of numbers and returns the sum of the first three numbers in the array, and the test passes.

						let res = sum3([1, 4, 1]);
						console.assert (res = 6);
						res = sum3 ([1, 5, 0, 5]);
						console.assert (res === 6);
					

A different developer made changes to the behavior of sum3 to instead sum only the first two numbers present in the array. Which two results occur when running this test on the updated sum3 function? Choose 2 answers.

  1. The line 04 assertion fails.
  2. The line 04 assertion passes.
  3. The line 02 assertion passes.
  4. The line 02 assertion fails.

46) A developer needs to debug a Node.js web server because a runtime error keeps occurring at one of the endpoints. The developer wants to test the endpoint on a local machine and make the request against a local server to look at the behavior. In the source code, the server.js file will start the server. The developer wants to debug the Node.js server only using the terminal. Which command can the developer use to open the CLI debugger in their current terminal window?

  1. node -i server.js
  2. node inspect server.js
  3. node start inspect server.js
  4. node server.js –inspect

47) Universal Containers (UC) notices that its application that allows users to search for accounts makes a network request each time a key is pressed. This results in too many requests for the server to handle. To address this problem, UC decides to implement a debounce function on the search string change handler. What are three key steps to implement this debounce function?

  1. Ensure that the network request has the property debounce set to true.
  2. If there is an existing setTimeout and the search string changes, allow the existing setTimeout to finish, and do not enqueue a new setTimeout.
  3. When the search string changes, enqueue the request within a setTimeout.
  4. Store the timerId of the setTimeout last enqueued by the search string change handler.
  5. If there is an existing setTimeout and the search string changes, cancel the existing setTimeout using the persisted timerId and replace it with a new setTimeout.

48) Given the code below:

						setCurrentUrl();
						console.log('The current URL is:' + url);
						function setCurrentUrl() {
						  url=window.location.href;
						}
					

What happens when the code executes?

  1. The url variable has local scope and line 02 executes correctly.
  2. The url variable has local scope and line 02 throws an error.
  3. The url variable has global scope and line 02 executes correctly.
  4. The url variable has global scope and line 02 throws an error.

49) Refer to the code below:

						document.body.addEventListener("click", (event) => {
						  if(/ ANSWER HERE /) {
						    console.log('myElement clicked!');
						  };
						)};
					

Which replacement for the conditional statement on line 02 allows a developer to correctly determine that a specific element, myElement, on the page had been clicked?

  1. e.nodeTarget == myElement
  2. button.addEventListener(‘click’, ‘myElement’)
  3. event.target.id == “myElement”
  4. myElement.clicked

50) Refer to the code below:

						new Promise((resolve, reject) => {
						  const fraction = Math.random();
						  if (fraction > 0.5) reject("fraction > 0.5" + fraction);
						  resolve(fraction);
						}
						.then(() => console.log('resolved'))
						.catch((error) => console.error(error))
						.finally(()=> console.log('when am I called?'));
					

When does Promise. finally on line 08 get called?

  1. When resolved
  2. When resolved and settled
  3. When resolved or rejected
  4. When rejected

Leave a Comment

Your email address will not be published. Required fields are marked *