JS1 Final Flashcards
Refer to the code below:
01 const exec = (item, delay) =>{
02 new Promise(resolve => setTimeout( () => resolve(item), delay)),
03 asyncfunction runParallel() {
04 Const (result1, result2, result3) = await Promise.all{
05[exec(‘x’,‘100’),exec(‘y’,500),exec(‘z’,‘100’)]
06);
07 return parallel is done: $(result1) $(result2)$(result3)
;
08 }
}
}
Which two statements correctly execute the runParallel () function?
Choose 2 answers
A. Async runParallel () .then(data);
B. runParallel ( ). done(function(data){
return data;
});
C. runParallel () .then(data);
D. runParallel () .then(function(data)
return data
Answer: B,D
A developer needs to test this function:
01constsum3=(arr)=>(
02if(!arr.length)return0,
03 if (arr.length === 1) returnarr[0],
04 if(arr.length===2)returnarr[0]+arr[1],
05 return arr[0] + arr[1] + arr[2],
06 );
Which two assert statements are valid tests for the function?
Choose 2
A. console.assert(sum3(1, ‘2’)) == 12);
B. console.assert(sum3(0)) == 0);
C. console.assert(sum3(-3, 2 )) == -1);
D. console.assert(sum3(‘hello’, 2, 3, 4)) === NaN);
Answer: A,C
Which statement phrases successfully?
A. JSON.parse ( ‘ foo ’);
B. JSON.parse ( “ foo ” );
C. JSON.parse( “ ‘ foo ’ ” );
D. JSON.parse(‘ “ foo ” ’);
Answer: D
Refer to the code below:
01 let car1 = new promise((_, reject) =>
02 setTimeout(reject, 2000, “Car 1 crashed in”));
03 let car2 = new Promise(resolve => setTimeout(resolve, 1500, “Car 2
completed”));
04 let car3 = new Promise(resolve => setTimeout (resolve, 3000, “Car 3
Completed”));
05 Promise.race([car1, car2, car3])
06 .then(value =>(
07letresult = $(value)the race.`;
08 ))
09 .catch( arr => (
10 console.log(“Race is cancelled.”, err);
11 ));
What is the value of result when Promise.race executes?
A. Car 3 completed the race.
B. Car 1 crashed in the race.
C. Car 2 completed the race.
D. Race is cancelled
Answer: C
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:
- Does require an import
- Logs an error when the boolean statement evaluates to false
- WorksinboththebrowserandNode.js
Whichmeetthe requirements?
A. assert (number % 2 === 0);
B. console.error(number % 2 === 0);
C. console.debug(number % 2 === 0);
D. console.assert(number % 2 === 0);
Answer: D
Adeveloperisworking on an ecommerce website where the delivery date is dynamically
calculated based on the current day.Thecodelinebelowisresponsibleforthis calculation.
Const deliveryDate = new Date();
Due to changes in the business requirements, the delivery date must now be today’s
date + 9 days.
Which code meets this new requirement?
A. deliveryDate.setDate(( new Date ( )).getDate () +9);
B. deliveryDate.setDate( Date.current () + 9);
C. deliveryDate.date = new Date(+9) ;
D. deliveryDate.date = Date.current () + 9;
A
Which three statements are true about promises?
Choose 3 answers
A. The executor of a new Promise runs automatically.
B. A Promise has a .then() method.
C. A fulfilled or rejected promise will not change states.
D. A settled promise can become resolved.
E. A pending promise can become fulfilled, settled, or rejected.
Answer: B,C,E
Given the code below:
01 function GameConsole (name) {
02 this.name =name;
03 }
04
05 GameConsole.prototype.load = function(gamename) {
06 console.log( ` $(this.name) is loading a game : $(gamename)…);
07 )
08functionConsole 16Bit(name){
09GameConsole.call(this, name);
10 }
11 Console16bit.prototype = Object.create ( GameConsole.prototype) ;
12 //insert codehere
13 console.log(
$(this.name) is loading a cartridge game : $(gamename) …`);
14 }
15 const console16bit = new Console16bit(‘ SNEGeneziz ’);
16 console16bit.load(‘ Super Nonic 3x Force’);
Whatshouldadeveloperinsert atline 15tooutputthefollowingmessageusing the
method ?
> SNEGenezizisloading a cartridge game: Super Monic 3x Force . . .
A. Console16bit.prototype.load(gamename) = function() {
B. Console16bit.prototype.load = function(gamename) {
C. Console16bit = Object.create(GameConsole.prototype).load = function
(gamename) {
D. Console16bit.prototype.load(gamename) {
Answer: B
A developer has the following array of student test grades:
Let arr = [ 7, 8, 5, 8, 9 ];
TheTeacher wants to double each score and then see an array of the students
who scored more than 15 points.
How should the developer implement the request?
A. Let arr1 = arr.filter(( val) => (return val > 15 )) .map (( num) => ( return num *2 ))
B. Let arr1 = arr.mapBy (( num) => (return num 2 )) .filterBy (( val ) => return val > 15 )) ;
C. Let arr1 = arr.map((num) => num2). Filter (( val) => val > 15);
D. Let arr1 = arr.map((num) => ( num *2)).filterBy((val) => ( val >15 ));
C
A test has a dependency on database.query. During the test the dependency is replaced
with an object called data base with the method, query, that returns an array.The
developer needs to verify how many times the method was called and the arguments
used each time.
Which two test approaches describe the requirement?
Choose 2 answers
A. Integration
B. Black box
C. White box
D. Mocking
Answer: C,D
Given the JavaScript below:
01 function filterDOM (searchString) {
02 const parsedSearchString = searchString && searchString.toLowerCase() ;
03 document.quesrySelectorAll(‘ .account’ ) . forEach(account => (
04const accountName = account.innerHTML.toLOwerCase();
05 account. Style.display = accountName.includes(parsedSearchString) ? /Insert
code/;
06 )};
07 }
Whichcodeshouldreplacetheplaceholder commentonline05tohideaccountsthatdo
not match the search string?
A. ‘ name ’ : ‘ block ’
B. ‘ Block ’ : ‘ none ’
C. ‘visible’:‘hidden’
D. ‘hidden’:‘visible’
B
developer publishes a new version of a package with new features that do not break
backward compatibility. The previous version number was 1.1.3.
Following the semantic versioning format, what should the new package version number
be?
A.2.0.0
B.1.2.3
C.1.1.4
D. 1.2.0
D
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 alert ( ‘Hey! I am John Doe’) ;
03 button.addEventListener (‘click’, listen);
Which two code lines make this code work as required?
Choose 2 answers
A. On line 02, use event.first to test if it is the first execution.
B. On line 04, use event.stopPropagation ( ),
C. On line 04, use button.removeEventListener(‘ click” ,listen);
D. On line 06, add an option called once to button.addEventListener().
C, D
A developer uses aparsedJSONstring to work with user information as in the block below:
01 const userInformation={
02 “ id ” : “user-01”,
03 “email” : “user01@universalcontainers.demo”,
04 “age” : 25
Which two options access the email attribute in the object?
Choose 2 answers
A. userInformation(“email”)
B. userInformation.get(“email”)
C. userInformation.email
D. userInformation(email)
Answer: A,C
Refer to the code below:
01 const server = require(‘server’);
02 /* Insert code here*/
Adeveloperimports a library that creates a webserver. The imported library uses events and callbacks to start the servers
Which code should be inserted at the line 03 to set up an event and start the web server?
A. Server.start ();
B. server.on(‘ connect ’ , ( port) =>{
console.log(‘Listening on ’ , port) ;})
C. server()
D. serve(( port) => (
E. console.log( ‘Listening on ’, port) ;
B
Adeveloperwantstoiteratethroughanarrayofobjects andcounttheobjectsandcount
the objects whose property value, name,starts with the letter N.
Const arrObj = [{“name” : “Zach”} , {“name” : “Kate”},{“name” : “Alise”},{“name” : “Bob”},{“name” :
“Natham”},{“name” : “nathaniel”}
Refertothecodesnippetbelow:
01arrObj.reduce(( acc, curr)=>{
02//missing line02
02//missing line03
04 ). 0);
Which missing lines 02 and 03 return the correct count?
A. Constsum=curr.startsWith(‘N’)?1:0;
Return acc +sum
B. Const sum = curr.name.startsWith(‘N’) ? 1: 0;
Return acc +sum
C. Constsum=curr.startsWIth(‘N’)?1:0;
Return curr+ sum
D. Const sum = curr.name.startsWIth(‘N’) ? 1: 0;
Return curr+ sum
B
A developer creates a class that represents a blog post based on the requirement that a
Post should have a body author and view count.
The Code shown Below:
Class Post {
// Insert code here
This.body =body
This.author = author;
this.viewCount = viewCount;
}
}
Which statement should be inserted in the placeholder online 02toallowfor a variable to be set
to a new instance of a Post with the three attributes correctly populated?
A. super (body, author, viewCount){
B. Function Post (body, author, viewCount){
C. constructor (body, author, viewCount){
D. constructor() {
C
Which three options show valid methods for creating a fat arrow function?
Choose 3 answers
A. x => ( console.log(‘ executed ’);)
B. [] => ( console.log(‘ executed ’);)
C. () => ( console.log(‘ executed ’);)
D. X,y,z => ( console.log(‘ executed ’);)
E. (x,y,z) => ( console.log(‘ executed ’) ;)
A,C,E
Refer to the code below:
const event = new CustomEvent(
//Missing Code
);
obj.dispatchEvent(event);
A developer needs to dispatch a custom event called update to send information about
record Id.
Which two options could a developer insert at the placeholder inline 02 to achieve this?
Choose 2 answers
A. ‘Update’ , (
recordId : ‘123abc’
(
B. ‘Update’ , ‘123abc’
C. { type : ‘update’, recordId : ‘123abc’ }
D. ‘Update’ , {
Details : {
recordId : ‘123abc’
}
}
Answer: A,D
Refer to the code below:
Const pi = 3.1415326,
What is the data type of pi?
A. Double
B. Number
C. Decimal
D. Float
B
A 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 option makes the code work as expected?
A. Replace line 02 with return arr.map(( result, current) => (
B. Replace line 04 with result = result+current;
C. Replace line 03 with if(arr.length == 0 )
D. Replace line 05 with return result;
D
Given code below:
setTimeout (() => (
console.log(1);
). 0);
console.log(2);
New Promise ((resolve,reject)) = > (
setTimeout(() => (
reject(console.log(3));
). 1000);
)).catch(() => (
console.log(4);
));
console.log(5);
What is logged to the console?
A. 2 1 4 3 5
B. 2 5 1 3 4
C. 1 2 4 3 5
D. 1 2 5 3 4
B
Which statement accurately describes the behavior of the async/ await keywords?
A. The associated class contains some asynchronous functions.
B. The associated function will always return a promise
C. The associated function can only be called via asynchronous methods
D. The associated sometimes returns a promise
B
Adeveloperisdebugging awebserverthatusesNode.js Theserverhits a runtime error
every third request to an important endpoint on the web server.
The developer added a breakpoint to the start script, that is atindex.js at the root of the
server source code. The developer wants to make use of chromeDevToolstodebug.
Which command can be run toaccessDevTools and make sure the breakdown is hit ?
A. node -i index.js
B. Node –inspect-brk index.js
C. Node inspect index.js
D. Node –inspect index.js
D
Refer to the code below:
Async funct on functionUnderTest(isOK) {
If (isOK) return ‘OK’ ;
Throw new Error(‘not OK’);
)
Which assertion accurately tests the above code?
A. Console.assert (await functionUnderTest(true), ‘ OK ’)
B. Console.assert (await functionUnderTest(true), ‘ not OK ’)
C. Console.assert (await functionUnderTest(true), ‘ not OK ’)
D. Console.assert (await functionUnderTest(true), ‘OK’)
D
Consider type coercion, what does the following expression evaluate to?
True + 3 + ‘100’ + null
A. 104
B. 4100
C. ‘3100null’
D. ‘4100null’
D
ADeveloperwrotethefollowing code to test a sum3 function that takes in an array of
numbers and returns the sum of the first three number in the array, The test passes:
Let res = sum2([1, 2, 3 ]) ;
console.assert(res === 6 );
Res = sum3([ 1, 2, 3, 4]);
console.assert(res=== 6);
Adifferentdevelopermadechangestothebehaviorofsum3toinsteadsumallofthenumbers
present in the array. The test passes: Whichtworesultsoccurwhenrunning thetestontheupdatedsum3function?
Choose 2 answers
A. The line 02 assertion passes.
B. The line 02 assertion fails
C. The line 05 assertion passes.
D. The line 05 assertion fails.
Answer: A,D
Adevelopercreatesasimplewebpagewithaninputfield.Whenauserenterstextin
the input field and clicks the button, the actual value of the field must be displayed in the console.
Here is the HTML file content:
<input type =” text” value=”Hello” name =”input”>
<button type =”button” >Display </button>
The developer wrote the javascript code below:
Const button = document.querySelector(‘button’);
button.addEvenListener(‘click’, () => (
Const input = document.querySelector(‘input’);
console.log(input.getAttribute(‘value’));
When the user clicks the button, the output is always “Hello”.
What needs to be done make this code work as expected?
A. Replace line 04 with console.log(input .value);
B. Replace line 03 with const input =document.getElementByName(‘input’);
C. Replace line 02 with button.addEventListener(“onclick”, function() {
D. Replace line 02 with button.addCallback(“click”, function(){
A
A developer createsanobjectwhereitspropertiesshouldbeimmutableandprevent
properties from being added or modified.
Which method should be used to execute this business requirement?
A. Object.const()
B. Object.eval()
C. Object.lock()
D. Object.freeze()
D
A developer has an ErrorHandler module that contains multiple functions.
What kind of export be leveraged so that multiple functions can be used?
A. Named
B. All
C. Multi
D. Default
A
A team that works on a big project uses npm to deal with project dependencies.
A developer added a dependency does not get downloaded when they execute npm
install.
Whichtworeasonscouldbepossibleexplanationsforthis?
Choose 2 answers
A. The developer missed the option –add when adding the dependency.
B. The developer added the dependency as a dev dependency and
NODE_ENV Is set to production.
C. The developer missed the option –save when adding the dependency.
D. The developer didn’t pull back the current version
Answer: B,C
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 =masSpeed;
This.color = color;
Let carSpeed = document.getElementById(‘ CarSpeed’);
Debugger;
Let fourWheels =new Car (carSpeed.value, ‘red’);
Whenthecodeexecutionstops atthebreakpointonline06,whichtwotypesofinformationare
available in the browser console?
Choose 2 answers:
A. The values of the carSpeed and fourWheels variables
B. A variable displaying the number of instances created for the Car Object.
C. The style, eventlisteners and other attributes applied to the carSpeed DOM element
D. The information stored in the window.local Storage property
C, D
AtUniversalContainers, every team has its own way of copying JavaScript objects. The
code Snippet shows an implementation from one team:
Function Person() {
this.firstName = “John”;
this.lastName = ‘Doe’;
This.name =() => (
console.log(‘Hello $(this.firstName) $(this.firstName)’);
)}
Const john = new Person ();
Const dan = JSON.parse(JSON.stringify(john));
dan.firstName =’Dan’;
dan.name();
What is the Output of the code execution?
A. Hello Dan Doe
B. Hello John DOe
C. TypeError: dan.name is not a function
D. TypeError: Assignment to constant variable
C
Refer to the code below:
Let textValue = ’1984’;
Which code assignment shows a correct way to convert this string to an integer?
A. let numberValue = Number(textValue);
B. Let numberValue = (Number)textValue;
C. Let numberValue = textValue.toInteger();
D. Let numberValue = Integer(textValue);
A
A developer writers the code below to calculate the factorial of a given number.
Function factorial(number) {
Return number + factorial(number -1);
}
factorial(3);
What is the result of executing line 04?
A. 0
B. 6
C. -Infinity
D. RuntimeError
D
Given the following code:
Let x =null;
console.log(typeof x);
What is the output of the line 02?
A. “Null”
B. “X”
C. “Object”
D. “undefined”
C
Which function should a developer use to repeatedly execute code at a fixed interval?
A. setIntervel
B. setTimeout
C. setPeriod
D. setInteria
A
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?
A. 10
B. Nan
C. 5
D. Undefined
C
Given HTML below:
//<div>
//<div id =”row-uc”> Universal Container</div>
//<div id =”row-aa”>Applied Shipping</div>
//<div id =”row-bt”> Burlington Textiles </div>
//</div>
Which statement adds the priority-account CSS class to the universal Containers row ?
A. Document .querySelector(‘#row-uc’).classes.push(‘priority-account’);
B. Document .queryElementById(‘row-uc’).addclass(‘priority-account’);
C. Document .querySelector(‘#row-uc’).classList.add(‘priority-account’);
D. Document .querySelectorALL(‘#row-uc’).classList.add(‘priority-account’);
C
Refer to the code below:
const addBy = ?
const addByEight =addBy(8);
const sum = addBYEight(50);
Which two functions can replace line 01 and return 58 to sum?
Choose 2 answers
A. const addBy = function(num1){
return function(num2){
return num1 + num2;
}
B. const addBy = function(num1){
return num1 +num2;
}
C. const addBy = (num1) => num1 + num2 ;
D. const addBY = (num1) => (num2) => num1 +num2;
A, D
given a value which three options can a developer use to detect if the value isNaN?
Choose 2 answers!
A. value == NaN
B. Object.is(value, NaN)
C. value === Number.NaN
D. value ! == value
E. Number.isNaN(value)
Answer: A, E
a developer wants to use a module named universalContainersLib and then call functions
from it.
Howshouldadeveloperimportevery function from the module andthencallthefuctionsfoo
and bar?
A. import * ad lib from ‘/path/universalContainersLib.js’;
lib.foo();
lib.bar();
B. import (foo, bar) from ‘/path/universalContainersLib.js’;
foo();
bar();
C. import all from ‘/path/universalContaineraLib.js’;
universalContainersLib.foo();
universalContainersLib.bar();
D. import * from ‘/path/universalContaineraLib.js’;
universalContainersLib.foo();
universalContainersLib.bar();
A
Refer to the code snippet:
Function getAvailabilityMessage(item) {
If (getAvailability(item)){
Var msg =”Username available”;
}
Return msg;
}
A developer writes this code to return a message to user attempting to register a new
username. If the username is available, variable.
What is the return value of msg when get AvailabilityMessage (“newUserName”) is
executed and getAvailability(“newUserName”) returnsfalse?
A. “Username available”
B. “newUserName”
C. “Msg is not defined”
D. undefined
D
Given the requirement to refactor the code above to JavaScript class format. Which class definition is correct?
function vehicle (name, price){
this.name = name;
this.price = price;
}
vehicle.prototype.priceinfo = function (){
return ‘cost of the $(this.name) is $(this.price);
}
var ford = new vehicle (‘Ford Mustang’, ‘20,000’);
A.
class vehicle {
constructor (name, price){
this.name = name;
this.price = price;
}
priceInfo(){
return ‘cost of the $(this.name) is $(this.price);
}
}
B.
class vehicle {
vehicle (name, price){
this.name = name;
this.price = price;
}
priceInfo(){
return ‘cost of the $(this.name) is $(this.price);
}
}
C.
class vehicle {
constructor (name, price){
name = name;
price = price;
}
priceInfo(){
return ‘cost of the $(this.name) is $(this.price);
}
}
D.
class vehicle {
constructor (){
this.name = name;
this.price = price;
}
priceInfo(){
return ‘cost of the $(this.name) is $(this.price);
}
}
A
AdeveloperwantstosetupasecurewebserverwithNode.js. The developer creates a
directory locally called app-server, and the first file is app-server/index.js
Withoutusinganythird-party libraries, what should the developer add to index.js to create the secure web server?
A. const https =require(‘https’);
B. const server =require(‘secure-server’);
C. const tls = require(‘tls’);
D. const http =require(‘http’);
A
Given the code below:
const delay = sync delay => {
Return new Promise((resolve, reject) => {
setTimeout (resolve, delay);});};
const callDelay =async () =>{
const yup =await delay(1000);
console.log(1);
What is logged to the console?
A. 123
B. 132
C. 213
D. 231
D
Refertothefollowingcode:
Let obj ={
Foo: 1,
Bar: 2
}
Let output =[],
for(let something in obj{
output.push(something);
}
console.log(output);
What is the output line 11?
A. [1,2]
B. [“bar”,”foo”]
C. [“foo”,”bar”]
D. [“foo:1”,”bar:2”]
C
Refer to the code below?
Let searchString = ‘ look for this ’;
Which two options remove the whitespace from the beginning of searchString?
Choose 2 answers
A. searchString.trimEnd();
B. searchString.trimStart();
C. trimStart(searchString);
D. searchString.replace(/\s\s/, ‘’);
B,D
Which three actions can be using the JavaScript browser console?
Choose 3 answers:
A. View and change DOM the page.
B. Display a report showing the performance of a page.
C. Run code that is not related to page.
D. view, change, and debug the JavaScript code of the page.
E. View and change security cookies.
A,C,D
Aclasswaswrittentorepresentitemsforpurchaseinanonlinestore,andasecondclass
Representing itemsthatareonsaleatadiscountedprice.THeconstructorsetsthenametothe
first value passed in. The pseudocode is below:
Class Item {
constructor(name, price) {
… // Constructor Implementation
}
}
Class SaleItem extends Item {
constructor (name, price, discount) {
…//Constructor Implementation
}
}
There is a new requirement for a developer to implement a description method that will return a brief description for Item and SaleItem.
Let regItem =new Item(‘Scarf’, 55);
Let saleItem = new SaleItem(‘Shirt’ 80, -1);
Item.prototype.description =function(){return‘Thisisa’+this.name;
console.log(regItem.description());
console.log(saleItem.description());
SaleItem.prototype.description=function(){return‘Thisisadiscounted’+
this.name; }
console.log(regItem.description());
console.log(saleItem.description());
What is the output when executing the code above?
A. This is a Scarf
Uncaught TypeError: saleItem.description is not a function
This is aScarf
This is a discounted Shirt
B. Thisis a Scarf
This is a Shirt
Thisis a Scarf
This is a discounted Shirt
C. Thisis a Scarf
Thisis a Shirt
ThisisadiscountedScarf
Thisis adiscounted Shirt
D. This is aScarf
Uncaught TypeError: saleItem.description is not a function
This is a Shirt
This is a did counted Shirt
B
Given the following code:
Let x =(‘15’ + 10)*2;
What is the value of a?
A. 3020
B. 1520
C. 50
D. 35
A
Refer to the following code:
01 function Tiger(){
02 this.Type = ‘Cat’;
03 this.size = ‘large’;
04 }
05
06 lettony = new Tiger();
07 tony.roar = () =>{
08 console.log(‘They\’re great1’);
09 };
10
11 function Lion(){
12 this.type = ‘Cat’;
13 this.size = ‘large’;
14 }
15
16 letleo = new Lion();
17//Insertcodehere
18 leo.roar();
Which two statements could be inserted at line 17 to enable the function call on line 18?
Choose 2 answers.
A. Leo.roar = () => { console.log(‘They\’re pretty good:’);};
B. Object.assign(leo,Tiger);
C. Object.assign(leo,tony);
D. Leo.prototype.roar = () => { console.log(‘They\’re pretty good:’); };
A, C
Which statement accurately describes an aspect of promises?
A. Arguments for the callback function passed to .then() are optional.
B. In a then() function returning results is not necessary since callbacks will catch the result of a previous promise.
C. .then() cannot be added after a catch.
D. .then() manipulates and returns the original promise.
A
Given the code below:
Function myFunction(){
A = 5;
Var b =1;
}
myFunction();
console.log(a);
console.log(b);
What is the expected output?
A. Both lines 08 and 09 are executed, and the variables are outputted.
B. Line 08 outputs the variable, but line 09 throws an error.
C. Line 08 thrones an error, therefore line 09 is never executed.
D. Both lines 08 and 09 are executed, but the values outputted are undefined.
B
WhichtwoconsolelogsoutputsNaN?
Choose 2 answers
A. console.log(10/ Number(‘5’));
B. console.log(parseInt(‘two’));
C. console.log(10/ ‘’five);
D. console.log(10/0);
B,C
Given the following code:
Counter = 0;
constlogCounter = () => {
console.log(counter);
);
logCounter();
setTimeout(logCOunter, 1100);
setInterval(() => {
Counter++
logCounter();
}, 1000);
What is logged by the first four log statements?
A. 0 0 1 2
B. 0 1 2 3
C. 0 1 1 2
D. 0 1 2 2
C
Refer to the code below:
Function Person(firstName, lastName, eyecolor) {
this.firstName =firstName;
this.lastName = lastName;
this.eyeColor =eyeColor;
}
Person.job = ‘Developer’;
const myFather = new Person(‘John’, ‘Doe’);
console.log(myFather.job);
What is the output after the code executes?
A. ReferenceError: eyeColor is not defined
B. ReferenceError: assignment to undeclared variable“Person”
C. Developer
D. Undefined
D
A developer at Universal Containers creates a new landing page based on HTML,CSS, and JavaScript TO ensure that visitors have a good experience, a script named personalize Context needs to be executed when the webpage is fully loaded (HTML content and related files), in order to do some custom initialization.
Which statement should be used to call personalize website content based on the above
business requirement?
A. document.addEventListener(‘’onDOMContextLoaded’, personalizeWebsiteContext);
B. window.addEventListener(‘load’,personalizeWebsiteContext);
C. window.addEventListener(‘onload’, personalizeWebsiteContext);
D. Document.addEventListener(‘‘’DOMContextLoaded’ , personalizeWebsiteContext);
B
In which situation should a developer include a try .. catch block around their function call ?
A. The function has an error that should not be silenced.
B. The function results in an out-of-memory issue.
C. The function might raise a runtime error that needs to be handled.
D. The function contains scheduled code.
C
Adeveloperisleading the creation of a new browser application that will serve a single
page application. Theteamwantstouse anewwebframeworkMinimalsit.js. The Lead
developer wants to advocate for a more seasoned web framework that already has a
community around it.
Which two frameworks should the lead developer advocate for?
Choose 2 answers
A. Vue
B. Angular
C. Koa
D. Express
B, D
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 createsmorethan50newHTML items placed randomly inside theDOM, like the one in the code below:
//<div class='ad-libary-item ad-hidden' onload="myFunction()">
//<img src=”/ad-libary/ad01.gif”
//</div>
All the elements include the same ad-library-itemclass, They are hidden by default and they are randomly displayed while the user navigates through the page.
A. Use the DOM inspector to prevent the load event to be fired.
B. Use the brows to execute a script that removes all the elements containing the class ad-library item.
C. Use the DOM inspector to remove all the elements containing the class ad-library-item.
D. Use the browser console to execute a script that prevents the load event to be fired.
C
Which code statement correctly retrieves and returns an object from localStorage?
A. const retrieveFromLocalStorage = () =>{
return JSON.stringify(window.localStorage.getItem(storageKey));
}
B. const retrieveFromLocalStorage = (storageKey) =>{
returnwindow.localStorage.getItem(storageKey);
}
C. const retrieveFromLocalStorage = (storageKey) =>{
return JSON.parse(window.localStorage.getItem(storageKey));
}
D. const retrieveFromLocalStorage = (storageKey) =>{
returnwindow.localStorage[storageKey];
}
C
<input type=”file” onchange=”previewFile()”>
<img src=”” height=”200” alt=”Image Preview…”/>
The JavaScript portion is:
01 function previewFile(){
02 const preview = document.querySelector(‘img’);
03 const file =document.querySelector(‘input[type=file]’).files[0];
04 //line 4 code
05 reader.addEventListener(“load”, () =>{
06 preview.src = reader.result;
07 },false);
08 //line 8 code
09 }
Inlines 04 and 08 which code allows the user to select an image from their local
computer, and to display the image in the browser?
A. 04 const reader = new File();
08 if (file) URL.createObjectURL(file);
B. 04constreader=newFileReader();
08if(file)URL.createObjectURL(file);
C. 04 const reader = new File();
08 if (file) reader.readAsDataURL(file);
D. 04constreader=newFileReader();
08 if (file)reader.readAsDataURL(file);
D
The developer creates a generic function to log custom messages in the console. To do this, the function below is implemented.
01 function logStatus(status){
02 console./Answer goes here/{‘Item status is: %s’, status};
03 }
Which three console logging methods allow the use of string substitution in line 02?
A. Assert
B. Log
C. Message
D. Info
E. Error
Answer: B,D,E
Adeveloperwrotethefollowingcode:
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?
A. 03 try{
04 handleObjectValue(x);
05 } catch(error){
06 handleError(error);
07 } then{
08 getNextValue();
09 }
B. 03 try{
04 handleObjectValue(x);
05 } catch(error){
06 handleError(error);
07 } finally{
08 getNextValue();
10 }
C. 03 try{
04 handleObjectValue(x);
05 } catch(error){
06 handleError(error);
07 }
08 getNextValue();
D. 03 try {
04 handleObjectValue(x)
05 ……………………
D
Given the code above which three properties are set pet1?
function Animal(size, type){
this.size = size || “small”;
this.type = type || “Animal”;
this.canTalk = false;
}
let Pet = function (size, type, name, owner){
animal.call(this, size, type);
this.name = name;
this.owner = owner;
}
pet.prototype = Object.create(Animal.prototype);
let pet1 = new pet();
console.log(pet1);
Choose 3 answers:
A. Name
B. canTalk
C. Type
D. Owner
E. Size
B,C,E
Refer to the code below:
Let car1 = new Promise((_ , reject) =>
setTimeout(reject,2000,“car1crashedin”=>
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.’;)}
.catch(arr => {
console.log(“Race is cancelled.”, err);
});
What is the value of result when Promise.race executes?
A. Car 3 completes the race
B. Car 2 completed the race.
C. Car 1 crashed in the race.
D. Race is cancelled.
B
Refer to the following code:
Let sampleText = ‘The quick brown fox jumps’;
A developer needs to determine if a certain substring is part of a string.
Which three expressions return true for the given substring?
Choose 3 answers
A. sampleText.includes(‘fox’);
B. sampleText.includes(‘ quick ’, 4);
C. sampleText.includes(‘ Fox ’,3)
D. sampleText.includes(‘ fox ’);
E. sampleText.includes(‘ quick ’) !== -1;
Answer: A, D, E
Given two expressions var1 and var2. What are two valid ways to return the logical AND
of the two expressions and ensure its data type is Boolean?
Choose 2 answers:
A. Boolean(var1 && var2)
B. var1 && var2
C. var1.toBoolean() && var2toBoolean()
D. Boolean(var1) && Boolean(var2)
A D
CloudKicks has a class to represent items for sale in an online store, as shown below:
ClassItem{
constructor (name, price){
this.name = name;
this.price = price;
}
formattedPrice(){
return ‘s’ + String(this.price);}}
A new business requirement comes in that requests a ClothingItemclass that should have all of the properties and methods of the Item class but will also have properties that are specific to clothes.
Which line of code properly declares the clothingItemclass such that it inherits from
Item?
A. Class ClothingItem implements Item{
B. Class ClothingItem {
C. Class ClothingItem super Item {
D. Class ClothingItem extends Item {
D
Refer to the code below:
let greetings = ‘Goodbye’;
let salutation = ‘Hello, hello, hello’;
try{
greeting = ‘Hello’;
decodeURI (‘%%%’);
salutation = ‘Goodbye’
}catch(error){
salutation = ‘I say hello’;
}finally{
salutation = ‘Hello, Hello’;
}
Line 05 causes an error.
What are the values of greeting and salutation once code completes?
A. Greeting is Hello and salutation is Hello, Hello.
B. Greeting is Goodbye and salutation is Hello, Hello.
C. Greeting is Goodbye and salutation is I say Hello.
D. Greeting is Hello and salutation is I say hello.
A
Refer to the code below:
Let str = ‘javascript’;
Str[0] = ‘J’;
Str[4] = ’S’;
After changing the string index values, the value of str is ‘javascript’. What is the reason for this value:
A. Non-primitive values are mutable.
B. Non-primitive values are immutable.
C. Primitive values are mutable.
D. Primitive values are immutable.
D
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?
A. When rejected
B. When resolved and settled
C. When resolved
D. When resolved or rejected
D
Refer to the following array:
Let arr1 = [ 1, 2, 3, 4, 5 ];
Which two lines of code result in a second array, arr2 being created such that arr2 is not a reference to arr1?
A. Let arr2 = arr1.slice(0, 5);
B. Let arr2 = Array.from(arr1);
C. Let arr2 = arr1;
D. Let arr2 = arr1.sort();
A,B
Refer to code below:
Function muFunction(reassign){
Let x = 1; var y = 1;
if( reassign )
{ Let x= 2; Var y = 2; console.log(x); console.log(y);
}
console.log(x);
console.log(y);
}
What is displayed when myFunction(true) is called?
A. 2 2 1 1
B. 2 2 undefined undefined
C. 2 2 1 2
D. 2 2 2 2
C
A developer wants to create an object from a function in the browser using the code below:
Function Monster() { this.name = ‘hello’ };
Const z = Monster();
What happens due to the lack of the new keyword on line 02?
A. The z variable is assigned the correct object.
B. The z variable is assigned the correct object but this.name remains undefined.
C. Window.name is assigned to ‘hello’ and the variable z remains undefined.
D. Window.m is assigned the correct object.
C
developer removes the HTML class attribute from the checkout button, so now it is simply:
<button>Checkout</button>.
There is a test to verify the existence of the checkout button, however, it looks for a button with class= “blue”. The test fails because no such button is found. Which type of test category describes this test?
A. True positive
B. True negative
C. False positive
D. False negative
D
Which two code snippets show working examples of a recursive function? Choose 2 answers
A. Let countingDown = function(startNumber) { If ( startNumber >0) { console.log(startNumber) ;
return countingDown(startNUmber);
} else {
return startNumber;
}};
B. Function factorial ( numVar ) { If (numVar < 0) return; If ( numVar === 0 ) return 1; return numVar -1;
C. Const sumToTen = numVar => {
If (numVar < 0) Return; return sumToTen(numVar + 1)};
D. Const factorial =numVar => {
If (numVar < 0) return; If ( numVar === 0 ) return 1;
return numVar * factorial ( numVar - 1 );
};
A,D
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 “ Tony” to “Mr. T.”?
A. document.querySelectorAll(‘$main $TONY’).innerHTML = ’ Mr. T. ’;
B. document.querySelector(‘$main li:second-child’).innerHTML = ’ Mr. T. ’;
C. document.querySelector(‘$main li.Tony’).innerHTML = ’ Mr. T. ’;
D. document.querySelector(‘$main li:nth-child(2)’),innerHTML = ’ Mr. T. ’;
D
Considering type coercion, what does the following expression evaluate?
True + ‘13’ + NaN
A. ‘ 113Nan ’
B. 14
C. ‘ true13 ’
D. ‘ true13NaN ’
D
A developer wrote a fizzbuzz function that when passed in a number, returns the following:
● ‘Fizz’ if the number is divisible by 3.
● ‘Buzz’ if the number is divisible by 5.
● ‘Fizzbuzz’ if the number is divisible by both 3 and 5.
● Empty string if the number is divisible by neither 3 or 5.
Which two test cases will properly test scenarios for the fizzbuzz function?
Choose 3 answers
A. let res = fizzbuzz(5); console.assert ( res === ‘ ’ );
B. let res = fizzbuzz(15); console.assert ( res === ‘ fizzbuzz ’ )
C. let res = fizzbuzz(Infinity); console.assert ( res === ‘ ’ )
D. let res = fizzbuzz(3); console.assert ( res === ‘ fizz ’ )
Answer: B, C, D
A developer has code that calculates a restaurant bill, but generates incorrect answers while testing the code:
function calculateBill ( items ) {
let total = 0;
total += findSubTotal(items);
total += addTax(total);
total += addTip(total);
return total;
}
Which option allows the developer to step into each function execution within calculateBill?
A. Using the debugger command on line 05.
B. Using the debugger command on line 03
C. Calling the console.trace (total) method on line 03.
D. Wrapping findSubtotal in a console.log() method.
A
The developer has a function that prints “Hello” to an input name. To test this, the developer created a function that returns “World”. However, the following snippet does not print “ Hello World”.
const sayHello = (name) => {
console.log(“Hello”, name());
};
const world = () => {
return “world”;
};
sayhello(world);
What can the developer do to change the code to print “Hello World”?
A. Change line 7 to ) () ;
B. Change line 2 to console.log(‘Hello’ , name() );
C. Change line 9 to sayHello(world) ();
D. Change line 5 to function world ( ) {
B
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?
A. Terminal running the web server.
B. Browser performance toots
C. Browser javaScript console
D. On the webpage.
C
Refer to the code below: let sayHello = () => {
console.log (‘Hello, world!’);
};
Which code executes sayHello once, two minutes from now?
A. setTimeout(sayHello, 12000);
B. setInterval(sayHello, 12000);
C. setTimeout(sayHello(), 12000);
D. delay(sayHello, 12000);
A