Javascript Merged
Javascript Merged
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
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
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
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
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
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
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
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]