0% found this document useful (0 votes)
19 views40 pages

Javascript Merged

The document is a JavaScript Cookbook that provides a series of questions and answers related to setting up a development environment, strings, numbers, and dates in JavaScript. It covers topics such as console methods, data types, random number generation, and date formatting. Each chapter includes multiple-choice questions to reinforce understanding of JavaScript concepts and functionalities.

Uploaded by

siam.ytacc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views40 pages

Javascript Merged

The document is a JavaScript Cookbook that provides a series of questions and answers related to setting up a development environment, strings, numbers, and dates in JavaScript. It covers topics such as console methods, data types, random number generation, and date formatting. Each chapter includes multiple-choice questions to reinforce understanding of JavaScript concepts and functionalities.

Uploaded by

siam.ytacc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

JavaScript Cookbook

Chapter 01: Setting Up a Development Environment

Q1. How can you see the errors that occur in your web page and the messages you write to the console?
A. Use browser's source code view
B. Use the developer console in your browser
C. Use terminal of the code editor you use
D. All of the above
Answer: B
Q2. Which console method outputs text with a red background.?
A. console.log()
B. console.error()
C. console.wran()
D. console.assert()
Answer: B
[Page: 6]
Q3. Which console method outputs text with a yellow background.?
A. console.log()
B. console.error()
C. console.wran()
D. console.assert()
Answer: C
[Page: 6]
Q4. What does the following console method output?
c ons ol e . a s s e r t ( e xpr e s s i on, obj e c t )
A. If the expression is true, the message is written to the console along with a stack trace.
B. If the expression is false, the message is written to the console along with a stack trace.
C. If the expression is true, a message is written to the console
D. If the expression is false, a message is written to the console
Answer: B
[Page 6]
Q5. You want that in the developer console in your browser some messages are indented underneath a
heading, so they appear to be part of one logically related section. After writing some messages, you want to
revert back to normal.
Which console methods should you use?
A. console.log() & console.assert()
B. console.group() & console.assert()
C. console.dir() & console.assert()
D. console.group() & console.groupEnd()
Answer: D
[Page 6]
Q6. You want to change markup and styles temporarily to quickly test potential edits.
Which panel of the browser’s developer tool should you use?
A. Elements
B. Console
C. Sources
D. Network
Answer: A
[Page 7]

1
Q7. Which panel of browser’s developer tool should you use to browse all the files the current page is using,
including JavaScript libraries, images, and style sheets?
A. Elements
B. Console
C. Sources
D. Network
Answer: C
[Page 7]
Q8. Which panel of browser’s developer tool should you use to start tracking the time your code takes to
execute?
A. Application
B. Performance
C. Sources
D. Network
Answer: B
[Page 7]
Q9. Which panel of browser’s developer tool should you use to review all the data the current site is storing
with cookies, in local storage or with the IndexedDB API?
A. Application
B. Performance
C. Sources
D. Network
Answer: A
[Page 7]
Q10. You want to disallow potentially risky features, like automatic variable creation and some statements
that fail silently.
What should you do?
A. Add the use strict directive at the top of your JavaScript code file: ‘use strict’
B. Add the import es5 directive at the top of your JavaScript code file: import ‘es5’
C. Add the export module directive at the top of your JavaScript code file: export ‘es5-module’
D. All of the above
Answer: A
[Page 9]
Q11. Which command will you use to install a specific software package from the npm registry?
A. npm get package-name
B. npm update package-name
C. npm install package-name
D. node install package-name
Answer: A
Q12. Which command will you use to package.json with default values?
A. npm init
B. npm init -y
C. npm create
D. npm create -y
Answer: B
[Page 16]
Q13. Which command will you use to see installed packages and their dependencies of the current project?
A. npm init
B. npm dev
C. npm list
D. npm i
Answer: C
[Page 17]
Q14. Which command will you use to see all the global npm packages installed on your computer?

2
A. npm list depth 0
B. npm list -g --depth 0
C. npm list -g
D. npm list --dev --depth 0
Answer: B
[Page 17]
Q15. Which one is the true package.lock.json?
A. Dependency is recorded in this file using a property named dependencies
B. This file stores basic project settings and lists all the packages you use.
C. This file stores the exact version and checksum of every package you use
D. This file stores only global packages you use
Answer: C
[Page 17]
Q16. Which command should you use to run lite-server directly?
A. npm lite-server
B. npx lite-server
C. node lite-server
D. npm start lite-server
Answer: B
[Page 22]
Q17.

3
JavaScript Cookbook
Chapter 02: Strings and Regular Expressions

Q1. How many data types are there in JavaScript?


A. 4
B. 6
C. 8
D. 10
Answer: C
Q2. You want to verify that a variable is defined. Which expression should you use?
A. !variableName
B. variableName == undefined
C. variableName === ‘undefined’
D. typeof variableName === ‘undefined’
Answer: D
[Page 36]
Q3. If you want to make sure that your variable is a string. Which expression should you use?
A. !typeof unknownVariable
B. unknownVariable === null
C. typeof unknownVariable === string
D. typeof unknownVariable === 'string'
Answer: D
[Page 36]
Q4. You want to verify that a variable is defined, is a string, and is not empty before you use it. Which
expression should you use?
A. unknownVariable && unknownVariable.length > 0
B. typeof unknownVariable === string && unknownVariable.length
C. typeof unknownVariable === 'string' && unknownVariable.length > 0
D. typeof unknownVariable === 'string' && unknownVariable.length !== ‘’
Answer: C
[Page 36]
Q5. typeof operator.returns_______________.
A. the type name of the variable as a uppercase string
B. the type name of the variable as a lowercase string
C. the type name of the variable as a numeric value
D. the type name of the variable as a integer value
Answer: B
[Page 37]
Q6. Which one is not a JavaScript data type?
A. String
B. undefined
C. null
D. Integer
Answer: D
[Page 35
• Number
• String
• Boolean
• BigInt (for very large integers)
• Symbol (for unique identifiers)

1
• Object (the root of every other JavaScript type)
• undefined (a variable that hasn’t been assigned a value)
• null (a missing object)]
Q7. undefined means _____________________.
A. a missing object
B. empty value
C. 0 value
D. a variable that hasn’t been assigned a value
Answer: D
[Page 35]
Q8. null means _____________________.
A. a missing object
B. empty value
C. 0 value
D. a variable that hasn’t been assigned a value
Answer: A
[Page 35]
Q9. Consider the code block
i f ( unknownVa r i a bl e ) {
/ * c od t o r un*/
}
In which case the if block will not execute?
A. unknownVariable has not been declared
B. unknownVariable has been declared
C. unknownVariable is not null
D. unknownVariable is not the empty string ''
Answer: A
[Page 37]
Q10. You want to create a string representation of a number specifying the number of digits to keep after the
decimal point.
Which method should you use?
A. Number.toString()
B. Number.toFixed()
C. Number.toPrecision()
D. Number.toExponential()
Answer: B
[Page 38]
Q11. To insert Double quote in your string, you use?
A. "
B. \”
C. “”
D. *”
Answer: B
[Page 41]
Q12. To create a template literal, you use _________________.
A. apostrophe (‘)
B. double quotes (“)
C. backtick (`)
D. hash (#)
Answer: C
[Page 43]
Q13. Which one template string literal?
A. string text = “Repeat it “ + times + “ times”
B. string text = ‘Repeat it ‘ + times + ‘ times’

2
C. string text = `Repeat it {times} times`
D. string text = “Repeat it {times} times”
Answer: C
[Page 43]
Q14. Which string method should you use perfect Case-Insensitive String Comparison?
A. String.compare()
B. String.localeCompare()
C. String.equals()
D. String.match()
Answer: B
Q15. You want to check if one string contains another substring. Which method should you use?
A. String.indexOf()
B. String.search()
C. String.Includes()
D. .Sting.Contains()
Answer: C
[Page 46]
Q16. Which expression will return true?
A. “New version of C# is 8.0”.indexOf(“C#”)
B. “New version of C# is 8.0”.search(“C#”)
C. “New version of C# is 8.0”.includes(“C#”)
D. “New version of C# is 8.0”.charCodeAt(“C#”)
Answer: C
[A, B returns integer (15), C: will return true]
Q17. You want to find all occurrences of a specific substring in a string, and replace them with something
else. Which method should you use?
A. String.replace()
B. String.replaceAll()
C. String.find()
D. String.findAll()
Answer: B
[Page 48]
Q18. A __________is a sequence of characters that defines a textpattern.
A. template string
B. regular expression
C. string expression
D. string interpolation
Answer: B
[Page 49]
Q19. Which Regular expression special character matches the beginning of input?
A. ^
B. $
C. *
D. ?
Answer: A
[Page 51]
Q19. Which Regular expression special character indicates the end of input?
A. ^
B. $
C. *
D. ?
Answer: B
[Page 51]
Q20. Which Regular expression special character indicates zero or one time?

3
A. {n}
B. +
C. *
D. ?
Answer: B
[Page 51]
Q21. [^…] matches _______________________.
A. Any character within brackets
B. Any character but those within brackets
C. Any non digit character
D. Matches word character (letters, digits, underscores)
Answer: B
[Page 51]
Q22. \w matches _______________________.
A. Any character within brackets
B. Any character but those within brackets
C. Any non digit character
D. Matches word character (letters, digits, underscores)
Answer: D
[Page 51]

4
JavaScript Cookbook
Chapter 03: Numbers

Q1. Math.random() method generates ________________________________.


A. a integer value negative or positive
B. a numeric value of arbitrary range
C. a floating-point value between 0 and 1
D. none of the above
Answer: C
Q2. To generate a random number between min and max, which code should you use?
A. Math.random() * (max - min + 1) + min;
B. Math.floor(Math.random() * (max - min + 1) )
C. Math.floor(Math.random() * (max - min + 1) ) + min
D. Math.floor(Math.random() + min);
Answer: C
[page 61]
Q3. Math.floor(2.245948938) + 1 returns _________________
A. 2
B. 3
C. 4
D. 5
Answer: C
[Page 62]
Q4. Math.round(19.48938) returns_________.
A. 19
B. 20
C. 19.50
D. 19.4894
Answer: A
[Page 65]
Q5. Math.round(19.58938*10**2)/10**2 return _________
A. 19
B. 19.59
C. 19.60
D. 19.51
Answer: B
[Page 65]
Q6. You want to parse a number in a string and convert it to the number data type.
Which function should you use?
A. Number
B. IsNaN
C. parseInteger
D. None
Answer: A
[Page 68]
Q7. The Number() function also converts empty strings or strings with only whitespace to the number ___.
A. NaN
B. 0
C. undefined
D. null

1
Anser: B
[Page 68]
Q7. You want to parse a number in a string and convert it to the number data type.
Your code is
c ons t s t r i ngDa t a = ' 42' ;
c ons t numbe r Da t a = Numbe r ( s t r i ngDa t a ) ;
To test for failure what code you will write.
A. if (numberData) {
// code
}
B. if (typeof numberData === ‘number’) {
// code
}
C. if (Number.isNumeric(numberData)) {
// code
}
D. if (Number(numberData)) {
// code
}
Answer: B
[Page 68]
Q8. Number(' ') returns _______.
A. NaN
B. 0
C. undefined
D. null
Answer: B
[Page 69]
Q10. Number('2001/01/01') returns _______.
A. NaN
B. 0
C. undefined
D. null
Answer: A
[Page 69]
Q11. parseFloat('2001/01/01') returns _______.
A. NaN
B. 0
C. 2001
D. undefined
Answer: C
[Page 69]
Q12. To convert N degrees to radians , you will write code ____________________.
A. N * (Math.PI / 90)
B. N * (Math.PI / 180)
C. N * (Math.PI / 360)
D. N* Math.PI
Answer: B
[Page 71]
Q13. Which one denotes a BigInt value?
A. 10
B. 10n
C. (BigInt)10
D. 10b

2
Answer: B
[Page 10n]
Q14. Which code will not produce errors?
A. let x = 10n; x= x*2;
B. let x = 10n; x= x+1;
C. let x = 10n; x= x+1n;
D. let x = 10n; x= x/2;
Answer: C
[Page 74]

3
JavaScript Cookbook
Chapter 04: Dates

Q1. Which one outputs the current date and time?


A. console.log(now())
B. console.log(Date())
C. console.log(new Date())
D. console.log(new Date().getDate())
Answer: C
[Page 75]
Q2. Which one ISO 8601 standard date string?
A. 2021-12-17 03:24:00
B. 2021-12-17 03:24:00 pm
C. 2021-12-17T03:24:00Z
D. 2021-12-17@03:24:00
Answer: C
[Page 77]
Q4. You want to find a date that’s a specific number of days before or after another date.
Which code will work?
A. const today = new Date();
today.setDate(today + 21);
B. const today = new Date();
const currentDay = today.getDate();
today.setDate(currentDay + 21);
C. const today = new Date();
const currentDay = today.getDate();
today.add(currentDay + 21);
D. const today = new Date();
const currentDay = today.getDate();
today.setDate(currentDay + offset(21));
Answer: B
[Page 79]
Q5. new Date(2021, 0, 1, 10, 30).toUTCString() returns __________________________.
A. Fri, 01 Jan 2021 15:30:00 GMT
B. Fri Jan 01 2021
C. 2021-01-01T15:30:00.000Z
D. 1/1/2021, 10:30:00 AM
Answer: A
[Page 84]
Q6. new Date(2021, 0, 1, 10, 30).toDateString() returns __________________________.
A. Fri, 01 Jan 2021 15:30:00 GMT
B. Fri Jan 01 2021
C. 2021-01-01T15:30:00.000Z
D. 1/1/2021, 10:30:00 AM
Answer: B
[Page 84]
Q7. new Date(2021, 0, 1, 10, 30).toISOString() returns __________________________.
A. Fri, 01 Jan 2021 15:30:00 GMT
B. Fri Jan 01 2021
C. 2021-01-01T15:30:00.000Z

1
D. 1/1/2021, 10:30:00 AM
Answer: C
[Page 84]

2
JavaScript Cookbook
Chapter 05: Arrays

Q1. To verify that your object truly is an array, which function should you use?
A. Array.isArray()
B. Array.isPrototyoeOf()
C. Array.is()
D. Array()
Answer: A
[Page 75]
Q2. You have the following array
const animals = ['elephant', 'tiger', 'lion', 'zebra', 'cat', 'dog', 'rabbit'];
Which of the following code will not work to iterarate over array items?
A. for (const animal of animals) {}
B. animals.forEach(function(animal, index, array) { });
C. animals.reduce(function(animal, index, array) { });
D. for (let i = 0; i < animals.length; ++i) { }
Answer: C
Q3. Which functional array processing function is used to change every array element?
A. map()
B. every()
C. some()
D. reduce()
Answer: A
[Page 89]
Q4. Which functional array processing function is used to see if all elements meet a specific condition?
A. map()
B. every()
C. some()
D. reduce()
Answer: B
[Page 89]
Q5. Which functional array processing function is used to use all the values of an array in one calculation?
A. map()
B. every()
C. some()
D. reduce()
Answer: D
Q6. Which one is the spread operator?
A. ..
B. …
C. --
D. ---
Answer: B
Q7. What does the spread operator do?
A. spread operator use all the values of an array in one calculation.
B. spread operator finds array elements matching your criteria.
C. spread operator reorders an array.
D. spread operator unfolds an array into a list of elements.
Answer: D

1
[Page 94]
Q8. Which code copies array items of one array to another?
A. const numbers = [2, 42, 5, 304, 1, 13];
const numbersCopy = [numbers];
B. const numbers = [2, 42, 5, 304, 1, 13];
const numbersCopy = [...numbers];
C. const numbers = [2, 42, 5, 304, 1, 13];
const numbersCopy = numbers.slice();
D. const numbers = [2, 42, 5, 304, 1, 13];
const numbersCopy = numbers.clone();
Answer: B, C
[Page 94]
Q9. Which method is used to join two entire arrays together into a new array?
A. Array.join()
B. Array.push()
C. Array.concat()
D. Array.shift()
Answer: C
[Page 97]
Q10. Which code will empty an array named myArray?
A. myArray.clear();
B. myArray.pop();
C. myArray.length = 0;
D. myArray.splice(0);
Answer: C
[Page 101]

2
JavaScript Cookbook
Chapter 06: Functions

Q1. You have the following array and a function (line numbers are for reference only)
1. c ons t numbe r s = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ;
2. f unc t i on pr i nt Numbe r ( n) {
3. c ons ol e . l og( n) ;
4. }
5. c ons t s qua r e s = numbe r s . f or Ea c h( s qua r e Numbe r ) ;
Which one of the following is an exact alternative code, that uses arrow function, at line 5?
A. const squares = numbers(x=> console.log(x));
B. const squares = numbers.forEach(console.log(x));
C. const squares = numbers.forEach(x: console.log(x));
D. const squares = numbers.forEach(x=> console.log(x));
Answer: D
[Page 75]
Q2. Which of the following is not a valid arrow function?
A. x => x**2
B. (x, n) => x**n;
C. (x,n) => x**n
D. (x,n) => {x**n;}
Answer: D
[Page 121
(x,n) => { return x**n;}
Since it used a block {}]
Q3. You have the following function
f unc t i on a ddNumbe r s ( n1=10, n2=20, n3=30, mul t i pl i e r =1) {
r e t ur n mul t i pl i e r *( n2+n2+n3) ;
}
Which one is not a valid call to the function?
A. addNumbers(42, 10, 3, 1);
B. addNumbers(42, 10);
C. addNumbers(42, 10, undefined, 1);
D. addNumbers(42, 10, null, 1);
Answer: D
[Page 125]
Q4. Which one do you use to create a function that accepts unlimited arguments?
A. typeof operator
B. rest parameter
C. arrow function
D. higher order function
Answer: B
Q5. Which function accepts unlimited arguments?
A. function sumRounds(...) {}
B. function sumRounds(...numbers) {}
C. function sumRounds(numbers= []) {}
D. function sumRounds([numbers]) {}
Answer: B
[Page 125]

1
Q6. Consider the function
function crea t e Count e r ( ) {
l e t c ount = 0;
f unc t i on c ount e r ( ) {
c ount += 1;
c ons ol e . l og( c ount ) ;
}
r e t ur n c ount e r ;
}
Which one correctly calls the function?
A. counterFunction();
B. counterFunction.counter();
C. const counterFunction = createCounter();
counterFunction();
D. const counterFunction = createCounter();
counterFunction()();
Answer: C
[Page 130]
Q7. How do you declare a generator function?
A. by replacing the function keyword with generator
B. by replacing the function keyword with function*
C. Inside the generator function, use the push keyword each time you want to return a result
D. Inside the generator function, use the yield keyword each time you want to return a result
Answer: B, D
[Page 131]
Q8. You have the following generator function
function* generateValues() {
yield 3;
yield 5;
return 7;
}
Which of the following correctly use the function?
A. const generator = generateValues();
generator.value;
B. const generator = generateValues();
generator.next().value;
C. const generator = generateValues();
generator.next()
D. const generator = generateValues();
generator.nextValue();
Answer: B
Q9. Which one is a recurve function?
A. function factorial(n) {
var r=1;
for(var i=n; n>=1;i++) r *=i;
return r;
}

B. function factorial(n) {
var r=1;
for(var i=1; I<=1;i--) r *=i;
return r;
}

2
C. function factorial(n) { return n <= 1 ? 1 : n * factorial(n - 1); }
D. function factorial(n) { return n <= 1 ? 1 : n * (n - 1); }
Answer: C
[Page 161]

3
JavaScript Cookbook
Chapter 07: Objects

Q1. Which operator is used to determine the type of an object?


A. typeof
B. instanceof
C. is
D. ===
Answer: B
[Page 145]
Q2. Which one do you use to group several variables together to create a basic data package?
A. Object constructor
B. object literal
C. array
D. generator function
Answer: B
[Page 147]
Q3. You have the following object
var employee = {};
Which of the following object property definitions is not valid?
A. employee.name = “John”;
B. employee[‘jonedOn’] = new Date();
C. employee[‘address’+1]= “Mirpur, Dhaka”;
D. let propName =’Address2”;
employee.propName = “Bangladesh”;
Answer: D
[Page 150
employee[propName]=“Bangladesh”;]
Q4. You want to check at runtime if an object has a given property.
Which code should you use?
A. country in address
B. 'country' in address
C. 'country' intanceof address
D. 'country' typeof address
Answer: B
[Page 151]
Q5. Which one is used to get an array with the property names for your object?
A. Object.properties()
B. Object.keys()
C. Object.values()
D. Object.entries()
Answer: B
[Page 152]
Q6. Which one returns an array of property arrays, each of which holds a property name and the
corresponding value?
A. Object.properties()
B. Object.keys()
C. Object.values()
D. Object.entries()
Answer: D

1
[Page 154]
Q7. Which one returns each property name?
A. Object.properties()
B. Object.keys()
C. for...in loop
D. Object.entries()
Answer: C
[Page 154]
Q9.Which one do you use to make sure that its properties aren’t redefined or edited by other code?
A. Object.lock()
B. Object.freeze()
C. Object.seal()
D. Reflect.ownKeys()
Answer: B
[Page 160]

2
JavaScript Cookbook
Chapter 08: Classes

Q1. Which function in a class initializes your object?


A. getter & setter
B. constructor
C. prototype
D. instance
Answer: B
[Page 174]
Q2. Which of the following are constructor requirements?
A. Constructor functions are always named constructor
B. Constructor function does not use function keyword
C. Constructor function does not accept arguments
D. Constructor function parameter cannot have default values
Answer: A, B
[Page 174]
Q3. JavaScript supports constructor overloading or method overloading.
A. True
B. False
Answer: B
[Page 176]
Q4. If you create a class without a constructor, what will be the effects?
A. You cannot create an object of the class
B. Error will be thrown if you try to create an object of the class
C. JavaScript automatically gives it a blank no-argument constructor
D. None of the above
Answer: C
[Page 176]
Q5. Which one correctly defines a getter property?
A. getAge(){}
B. get age(){}
C. age(){}
D. age get(){}
Answer: B
[Page 178]
Q6. Which one correctly defines a getter property?
A. setAge(value){}
B. set age(value){}
C. age(value){}
D. age set(value){}
Answer: B
[Page 178]
Q7. JavaScript does not have a way to make member variables private.
A. True
B. False
Answer: A
[Page 181]
Q8. You want to choose a suitable text representation that will be used for your object when it’s converted to
a string.

1
What should you do?
A. Add a getter property named string
B. Add a method named toString()
C. Return a string from the constructor function
D. None of the above
Answer: B
Q9. Which one uses the constructor pattern class?
A. class Employee {
constructor(name) {this.name=name;}
}
B. class Employee {
Employee (name) {this.name=name;}
}
C. function Employee {
constructor(name) {this.name=name;}
}
D. function Employee(name) {
this.name=name;
}
Answer: D
[Page 183]
Q10. You want to create a utility method that’s tied to your class, but can be called without creating an object.
What should you do?
A. Make the method public
B. Place the static keyword before the method
C. Place the this keyword before the method
D. Place the # symbol before the method name
Answer: B
[Page 188]
Q11. To inherit a class from another class which keyword is used?
A. inherits
B. extends
C. exports
D. base
Answer: B
[Page 192]
Q12. Which one is used to call the base class constructor from the class?
A. base()
B. this()
C. super()
D. parent()
Answer: C
[Page 192]
Q13. What should you do to encapsulate your classes in a separate namespace to facilitate reuse and
prevent naming conflicts with other libraries?
A. Use native code
B. Use module system
C. Create npm package
D. Use es6 class
Answer: B
[Page 197
Q14. Which statement in a module system lists all the functions, variables, and classes that will be made
accessible to other code files?
A. default

2
B. pack
C. export
D. public
Answer: C
[Page 198]
Q15. In which script block, module I,port system will work?
A. <script type="javascript"><script>
B. <script type="module"><script>
C. <script><script>
D. <script language="module"><script>
Answer: B
[Page 199]

3
JavaScript Cookbook
Chapter 09: Asynchronous Programming

Q1. __________is an object that helps you manage an asynchronous task?


A. A Promise
B. A callback function
C. The setTimeout() function
D. A higher order function
Answer: A
[Page 204]
Q2. Which one is the correct syntax for the promise wrapper function?
A. function (callback){}
B. function (){}
C. function (()=>{})
D. function (resolve, reject){}
Answer: D
[Page 204]
Q3. What are the purposes of the parameters of the promise wrapper function?
function (resolve, reject){}
A. resolve() is called with your return value to successfully end the promise and reject() is called with an
error object to indicate a failure.
B. reject() is called with your return value to successfully end the promise and resolve() is called with an
error object to indicate a failure.
C. resolve() is called start the promise and reject() is called end the promise
D. resolve() is called when you want to access the status of the promise and reject() is called with an
error object to indicate a failure.
Answer: A
[Page 204]
Q4. What does the Promise.all() return?
A. a new promise that represents the completion of all your promises you passed as arguments
B. the value returned by the first promise of all the promises you passed as arguments
C. the value returned by the last promise of all the promises you passed as arguments
D. the status the first promise of all the promises you passed as arguments
Answer: A
[Page 212]
Q5. Which method resolves as soon as one promise has resolved successfully?
A. Promise.all()
B. Promise.any()
C. Promise.allSettled()
D. Promise.one()
Answer: B
[Page 212]
Q6. Which method resolves when every promise has been resolved or rejected?
A. Promise.all()
B. Promise.any()
C. Promise.allSettled()
D. Promise.one()
Answer: C
[Page 212]
Q7. What should you do instead of creating a promise chain, you want to write linear logic?

1
A. use the await keyword on your promise:
B. use the wait() method on your promise:
C. use the async keyword on your promise:
D. use the delay keyword on your promise:
Answer: A
[Page 214]
Q8. The await keyword only works in _____________________?
A. an async function
B. a promise function.
C. an arrow function
D. the setTimeout function
Answer: A
[Page 214]

2
JavaScript Cookbook
Chapter 10: Errors and Testing

Q1. You are performing a task that may not succeed, and you don’t want an error to interrupt your code or
appear in the developer console.
What should you do?
A. Wrap the section of your code in a try...catch block
A. Place the section of your in a method
B. Wrap the section of your code in a strict block
C. Wrap the section of your code in a arrow function
Answer: A
[Page 228]
Q2. Which property of the Error object returns a string that gives you a human-language description of the
problem?
A. message
B. text
C. reason
D. stack
Answer: A
[Page 228]
Q3. What type of error occurs when a numeric value is outside of its allowed range?
A. RangeError
B. ReferenceError
C. TypeError
D. AggregateError
Answer: A
[Page 231]
Q4. What type of error occurs when trying to assign a nonexistent object to a variable?
A. RangeError
B. ReferenceError
C. TypeError
D. AggregateError
Answer: B
[Page 231]
Q5. What type of error occurs when value is not the right data type for a given operation?
A. RangeError
B. ReferenceError
C. TypeError
D. AggregateError
Answer: C
[Page 231]
Q6. What is the result of the following code?
console.log(null.length);
A. empty string
B. 0
C. null
D. Cause an unhandled error
Answer: D
[Page 234]
Q7. What should you do to catch unhandled errors?

1
A. Handle window.error event
B. Handle document.error event
C. Handle.body.error event
D. Handle window.unhandledrejection event
Answer: A
[Page 234]
Q8. What should you do to catch unhandled errors for promise-based APIs?
A. Handle window.error event
B. Handle document.error event
C. Handle.body.error event
D. Handle window.unhandledrejection event
Answer: D
[Page 235]
Q9. You want to indicate an error condition by throwing an error object. What should you do?
A. Create an instance of the Object, passing a short description of the problem to the constructor
B. Create an instance of the Error object, passing a short description of the problem to the constructor
C. Create an instance of the Promise object, and call reject callback passing a short description of the
problem
D. Create an instance of the Promise object, call resolve callback passing a short description of the
problem
Answer: B
[Page 237]
Q10. Which of the following statements is valid?
A. throw new Error(`Dividing by zero is not allowed`);
B. throw Error(`Dividing by zero is not allowed`);
C. throw `Dividing by zero is not allowed`;
D. let err = new Error(`Dividing by zero is not allowed`); throw err;
Answer: C
[Page 237]
Q11. You are using jest for unit-testing. Which one is valid test code?
A. test(‘2 + 2 is 4’,()=>{
expect(2+2).toBe(4);
});
B. test(()=>{
expect(2+2).toBe(4);
});
C. test(‘2 + 2 is 4’,expect(2+2).toBe(4););
D. test(‘2 + 2 is 4’,()=>{
expect(2+2)== 4;
});
Answer: A
[Page 242]
Q12. You have the function below
function divide(number, divisor) {
if (divisor == 0) {
throw new Error('Dividing by zero is not allowed');
}
else {
return number/divisor;
}
}
You are using jest for unit-testing. Which code should you write for testing the method?
A. test(()=>{
expect(divide(20,5).toBe(4)

2
});
B. test(‘divide 20 by 5’, ()=>{
expect(divide(20,5)== 4
});
C. test(‘divide 20 by 5’,
expect(divide(20,5).toBe(4)
);
D. test(‘divide 20 by 5’, ()=>{
expect(divide(20,5).toBe(4)
});
Answer: D
[Page 242]
Q13. Which jest matcher function performs a deep comparison that checks if one object has the same
content as another?
A. toBe()
B. toEqual()
C. toStrictEqual()
D. toBeTruthy()
Answer: B
[Page 245]
Q14. Which jest matcher function checks if a value is null?
A. toBe()
B. toEqual()
C. toStrictEqual()
D. toBeNull()
Answer: D
[Page 245]

3
JavaScript Cookbook
Chapter 12: Working with HTML

Q1. Consider the following HTML fragment


<div id="demodiv">
<p>
Thi s i s t e xt .
</ p>
</ di v>
Which code should you write to access the div element?
A. document.getElementByTagName(“div”)
B. document.getElementById(“demodiv”)
C. document.getElementById("#demodiv")
D. document.querySelector(“demodiv”)
Answer: B
[Page 264
document.querySelector(“#demodiv”)]
Q2. Consider the following HTML fragment
<di v i d=" de modi v" >
<p>
Thi s i s t e xt .
</ p>
</ di v>
Which code should you write to access the pelement?
A. document.getElementByTagName(“div”).childNodes
B. document.getElementById(“demodiv”).childNodes
C. document.getElementById("#demodiv").childNodes
D. document.querySelector(“demodiv”).childNodes
Answer: B
[Page 264
document.querySelector(“#demodiv”)]
Q3. Which one should you use to find out the type of element from a node element?
A. through the nodeName property
B. through the type property
C. through the element property
D. using typeof operator
Answer: A
[Page 265]
Q4. document.querySelectorAll() returns _________________.
A. NodeList
B. Node
C. Array of node
D. Array of objects
Answer: A
Q5. You want to loop over the nodeList returned from a call to querySelectorAll(). Which does this correctly?
A. const items = document.querySelectorAll('li');
items.each(item => {
console.log(item.firstChild.data);
});

1
B. const items = document.querySelectorAll('li');
items.for(item => {
console.log(item.firstChild.data);
});
C. const items = document.querySelectorAll('li');
items.forEach(item => {
console.log(item.firstChild.data);
});
D. const items = document.querySelectorAll('li');
items.all(item => {
console.log(item.firstChild.data);
});
Answer: C
[Page 266]
Q6. You need to add JavaScript functionality when a user clicks a button with id btn.
Which will not work?
A. const clickHandler = (event) => {/*code*/};
const btn = document.getElementById('btn');
addEventListener(btn, 'click', clickHandler);
B. const clickHandler = (event) => {/*code*/};
const btn = document.getElementById('btn');
btn.addEventListener('click', clickHandler);
C. const btn = document.getElementById('btn');
btn.addEventListener('click', (event) => {/*code*/});
D. document.getElementById('btn').addEventListener('click', (event) => {/*code*/});
Answer: A
[Page 267]
Q7. _________________method allows our JavaScript to listen for a specific type of event and define a function
that will be called when the event is triggered.
A. on()
B. addEventListener()
C. onEvent()
D. onload()
Answer: B
[Page 268]
Q8. You want to find all elements in a web document that has the class red.
Which code should you use?
A. document.querySelectorAll('[class="red"]');
B. document.querySelectorAll('*[class="red"]');
C. document.querySelectorAll('^[class="red"]');
D. document.querySelectorAll('$[class="red"]');
Answer: B
[Page 269
Use *]
Q9. You want to access all img elements in a given document.
Which code should you use?
A. document.getElements('img')
B. document.getElementsByTagName('img')
C. document.querySelector('img')
D. document.getElementsByType('img')
Answer: B
[Page 270]
Q10. You want to get a list of all instances of img elements that are descendants of a parent article element.
Which code should you use?

2
A. document.getElements('article img')
B. document.getElementsByTagName('article img')
C. document.querySelector('article img')
D. document.querySelectorAll('article img')
Answer: D
[Page 271]
Q11. You want to get a list of all instances of img elements that are direct children of a parent article
element.
Which code should you use?
A. document.getElements('article img')
B. document.getElementsByTagName('article img')
C. document.querySelectorAll('article img')
D. document.querySelectorAll('article > img')
Answer: D
[Page 272]
Q12. You want to apply the CSS rules to an element by adding its class value.
Which code should you use?
A. element.class.add('class-name');
B. element.classes.add('class-name');
C. element.classList.add('class-name');
D. element.classNames.add('class-name');
Answer: C
[Page 273]
Q13. You want to directly replace background-color style on a specific element.
Which code should you use?
A. elem.style = 'background-color: red';
B. elem.backgroundColor = 'red';
C. elem.style.backgroundColor = 'red';
D. elem.style.background = 'red';
Answer: C
[Page 273]
Q14. You want to directly replace inline style on a specific element.
Which code should you use?
A. elem.style = 'rules…';
B. elem.style.rules = 'rules…';
C. elem.style.cssText = rules…;
D. elem.style.text = 'rules…';
Answer: C
[Page 275]
Q15. You have HTML table with each row is like below
<td>Washington</td><td>145</td>
You want to sum all numbers in a table column.
Which code should you use?
A. let sum = 0;
const cells = document.querySelectorAll('td:nth-child(2)');
cells.forEach(cell => {
sum += Number.parseFloat(cell.firstChild.data);
});
B. let sum = 0;
const cells = document.querySelectorAll('td:nth-of-type(2)');
cells.forEach(cell => {
sum += Number.parseFloat(cell.firstChild.data);
});
C. let sum = 0;

3
const cells = document.querySelectorAll('td(2)');
cells.forEach(cell => {
sum += Number.parseFloat(cell.firstChild.data);
});
D. let sum = 0;
const cells = document.querySelectorAll('td:child(2)');
cells.forEach(cell => {
sum += Number.parseFloat(cell.firstChild.data);
});
Answer: B
[Page 280]
Q16. Which one is not a HTML5 built-in form validation?
A. pattern
B. minlength and maxlength
C. type (email, number, URL etc)
D. creditcard
Answer: D
[Page 292]

4
JavaScript Cookbook
Chapter 13: Fetching Remote Data

Q1. Which API is used to request remote data from a server and manipulate the response.
A. XMLHttpRequest
B. Fetch API
C. Lite server
D. JSON server
Answer: B
[Page 301]
Q2. Using the fetch API, you want to request the URL, parse the JSON response and manipulate data.
Which code should you use?
A. fetch(url)
.then(data => /* code */));
B. fetch(url)
.then(response => response.json())
.then(data => /* code */);
C. fetch(url)
.then(response => response.json())
D. fetch(url)
.then(response => response.json())
.then( /* code */);
Answer: C
[Page 302]
Q4. Which of the following tasks cannot be done with the fetch API?
A. Form autocomplete suggestions
B. “Like” a social media post
C. Submit a form without navigating away from the page
D. Directly access database to retrieve data with any data access API
Answer: D
[Page 302]
Q5. Which is the mandatory parameter of the fetch method?
A. url
B. options
C. mode
D. method
Answer: A
[Page 302
The fetch() method accepts two parameters:
url (mandatory): The URL to which you are making a request
options: An object of options when making the request]
Q6. Which fetch() option is used to set the request method (GET, POST, PUT, or DELETE)?
A. mode
B. header
C. method
D. signal
Answer: C
[Page: 303]
Q7. Which fetch() option is used to set the mode of the request (cors, no-cors, or same-origin)?
A. mode

1
B. header
C. method
D. signal
Answer: A
[Page: 303]
Q8. You have the following code
fetch(url)
.then(response => response.json())
.then(data => /* code */);
You want to wrap the code in an asynchronous function. Which code writes the function correctly?
A. async function fetchRequest() {
const response = await fetch(url);
const data = async response.json();
/* code */
}
B. async function fetchRequest() {
const response = await fetch(url);
const data = await response.json();
}
C. async function fetchRequest() {
const response = await fetch(url);
const data = response.json();
/* code */
}
D. async function fetchRequest() {
const response = await fetch(url);
const data = await response.json();
/* code */
}
Answer: D
[Page 302]
Q9. Which one correctly calls data from a remote server using the post method?
A. fetch(url, “post”)
B. fetch(()=>{
url: url,
method: “post
})
C. fetch(url, {method: ‘post’})
D. fetch({method: ‘post’},url)
Answer: C
[Page 303]
Q10. Which one is not the possible parsing method of HTTP response?
A. arrayBuffer()
B. josn()
C. blob()
D. query(()
Answer: D
[Page 304
Possible methods are
arrayBuffer()
blob()
json()
text()
formData()]

2
Q11. Which HTTP response method parses the body as a UTF-8 string?
A. arrayBuffer()
B. josn()
C. blob()
D. text(()
Answer: D
[Page 304]
Q12. Your application needs to request remote data while supporting older browsers.
Which one should you use?
A. XMLHttpRequest
B. Fetch API
C. Lite server
D. JSON server
Answer: A
[Page 304]
Q13. You have a HTML form
<form id=”f” action=”http://localhost:8080/process”>
..
</form>
You want to submit a form from the client using Fetch api. Which code should you write?
A. const myForm = document.getElementById('my-form');
myForm.addEventListener('submit', async event => {
event.preventDefault();
const formData = new FormData(myForm);
const response = await fetch(url, {
method: 'post',
body: formData
});
const result = await response.text();
/* code to do with result */
});
B. const myForm = document.getElementById('my-form');
myForm.addEventListener('submit', async event => {
event.preventDefault();
const formData = new FormData(myForm);
const response = await fetch(url, formData);
const result = await response.text();
/* code to do with result */
});
C. const myForm = document.getElementById('my-form');
myForm.addEventListener('submit', event => {
event.preventDefault();
const formData = new FormData(myForm);
const response = await fetch(url, {
method: 'post',
body: formData
});
const result = await response.text();
/* code to do with result */
});
D. const myForm = document.getElementById('my-form');
myForm.addEventListener('submit', async event => {
event.preventDefault();
const response = await fetch(url, {

3
method: 'post',
body: myForm
});
const result = await response.text();
/* code to do with result */
});
Answer: A
[Page 307]
Q14. JavaScript’s _____________provides a means for easily creating key/value pairs of all the form data.
A. FormData
B. Form
C. Blob
D. Body
Answer: A
[Page 308]
Q15. Which one is not a method of the FormData?
A. FormData.append(key, value)
B. FormData.append(key, blob, filename)
C. FormData.add(key, value)
D. FormData.set(key, value)
Answer: C
[Page 308]
Q16. Which method FormData should you use to append new data, removing a duplicate key, if present?
A. FormData.append(key, value)
B. FormData.append(key, blob, filename)
C. FormData.add(key, value)
D. FormData.set(key, value)
Answer: D
[Page 308]
Q17. You want to populate a drop-down list with values based on a user’s actions with another form element.
What should you do?
A. Capture the click event from the element and in the event handler post fetch a request to the server to
get the options
B. Capture the change event from the element and in the event handler post fetch a request to the server
to get the options
C. Capture the focus event from the element and in the event handler post fetch a request to the server
to get the options
D. Capture the blur event from the element and in the event handler post fetch a request to the server to
get the options
Answer: B
[Page 311]
Q18. Which one is the JASON equivalent of the following code?
const arr = new Array("one","two","three");
A. ["one","two","three"];
B. ("one","two","three");
C. {"one","two","three"};
D. [‘one’,’two’,’three’];
Answer: A
[Page 315
Note the use of double quotes ("") rather than single(‘’), which are not allowed in JSON]
Q19. Which one is the JASON equivalent of the following code?
{
prop1 : "test",

4
result : true,
num : 5.44,
name : "Joe",
cts : [45,62,13]
}
A. {prop1:"test",result:true,num:5.44,name:"Joe",cts:[45,62,13]}
B. {"prop1":"test","result":true,"num":5.44,"name":"Joe","cts":[45,62,13]}
C. {‘prop1’:"test",’result’:true,’num’:5.44,’name’:"Joe",’cts’:[45,62,13]}
D. {"prop1":’test’,"result":true,"num":5.44,"name":’Joe’,"cts":[45,62,13]}
Answer: B
[Page 315
Property named and string value must be within double quotes ("") rather than single(‘’), which are not
allowed in JSON]
Q20. JSON objects can contain methods.
A. True
B. False
Answer: B
[Page 315
JSON objects cannot contain methods. If it does, an error is thrown. JSON works with data only.]
Q21. Which method is used to convert a JSON-formatted string into an object?
A. JSON.stringify()
B. JSON.parse()
C. JSON.convert()
D. JSON.object()
Answer: B
[Page 315]
Q22. What do you need to retrieve a remote XML file and parse its content?
A. fetch API
B. fetch along with the DomParser API
C. DomParser API
D. fetch setting response type blob
Answer: B
[Page 317]
Q23. What should be the response type when using fetch to retrieve XML?
A. json
B. text
C. blob
D. arraybuffer
Answer: B
[Page 317]
Q24. What should be the response type when using fetch to retrieve binary data?
A. json
B. text
C. blob
D. arraybuffer
Answer: C
[Page 318]
Q25.

5
JavaScript Cookbook
Chapter 14: Data Persistence

Q1. Which one cannot be used to persist data with JavaScript in the browser?
A. cookies
B. sessionStorage
C. localStorage.
D. Lite server
Answer: D
[Page 325
cookies, sessionStorage, localStorage, IndexedDB, WebSql(obsolete in most browser)]
Q2. To encode strings, use _________________.
A. encode
B. encodeURI
C. encodeURIComponent
D. encodeDataUrl
Answer: C
[Page 325
encodeURI does not encode queryString or hash values
encodeURIComponent will encode everything with special meaning]
Q3. In a browser cookies are accessed via the ____________object.
A. window.cookie
B. document.cookie
C. navigator.cookie
D. HttpCookie
Answer: B
Q4. Which option of cookie object controls if cookie will be sent in cross-site browsing or not?
A. domain
B. cors
C. secure
D. samesite
Answer: D
[Page 326]
Q5. You want to easily store information for a single session, without running into the size and cross-page
contamination problems. Which option should you choose?
A. cookie
B. sessionStorage
C. localStorage
D. indexedDb
Answer: B
[Page 328]
Q6. A session lasts for ______________________
A. as long as a single browser tab is open.
B. as long as browser is open
C. as long as an user in in the same site
D. None of the above
Answer: A
[Page 329]
Q7. Opening a new tab of the same page will _________________________.
A. keep the previous session.

1
B. start a new browser session.
C. abandon the last session and will start a new session.
D. close the previous session automatically.
Answer: B
[Page 329]
Q8. Cookie is _____________________.
A. specific to session
B. specific to the tab window
C. specific to browser
D. specific to client
Answer: A
[Page 333]
Q9. sessionStorage is _____________________.
A. specific to session
B. specific to the tab window
C. specific to browser
D. specific to client
Answer: B
[Page 333]
Q10. You want to persist form element entries (or any data) in such a way that users can continue where they
left off if the browser crashes, the user accidentally closes the browser, or the internet connection is lost.
Which option should you use?
A. Cookie
B. sessionStorage
C. localStorage
D. Any one of the above
Answer: C
[Page 334]
Q11. Which code is not valid to save data in localStorage?
A. localStorage.setItem('keyName', 'value');
B. localStorage.keyName = 'value';
C. localStorage.key(0) = 'value';
D. localStorage(0) = 'value';
Answer: D
[Page 335]
Q12. ___________object stores data on the client forever, or until specifically removed.
A. localStorage
B. sessionStorage
C. cookie
D. FileReader
Answer: A
[Page 335]
Q13. The size allocated for localStorage ____________.
A. 5mb
B. 10mb
C. unlimited
D. varies by browser, but most are in the 5 mb to 10 mb range
Answer: D
[Page 337]

2
JavaScript Cookbook
Chapter 15: Working with Media

Q1. How can you add JavaScript to a standalone SVG file or element?
A. Add the <script> outside of <svg> element
B. Add the <script> within the <code> element
C. Add <script> in CDATA markup
D. None of the above
Answer: D
[Page 345
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" width="600" height="600">
<script type="text/ecmascript">
<![CDATA[
/* javascript code */
]]>
</script>
<rect id="square" width="400" height="400" fill="#ff0000"
x="10" y="10" />
</svg>
But if your embed <svg> in HTML file, you can use with CDATA]
Q2. Which one is the correct way to embed the svg document in a web page?
A. <media type="image/svg+xml" data="demo.svg">
<img src="demo.svg" /> </media>
B. <object type="image/svg+xml" data="demo.svg">
<img src="demo.svg" />
</object>
C. <figure type="image/svg+xml" data="demo.svg">
<img src="demo.svg" />
</figure>
D. <img type="image/svg+xml" data="demo.svg">
<img src="demo.svg" />
</img>
Answer: B
[Page 347]
Q3. Which method is not supported by the HTML media element?
A. play
B. pause
C. resume
D. load
Answer: C
[Page 359
play
pause
load
canPlayType]
Q4. Which method of the HTML media element if the user agent supports the video type?
A. test
B. canLoad
C. canPlay

1
D. canPlayType
Answer: D
[Page 359]

You might also like