Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

Solve On Your Own

1. Which operator returns true if the two compared values are not equal?

a) <>
b) ~
c) ==!
d) !==

2. How is a forEach statement different from a for statement?

a) Only a for statement uses a callback function.


b) A for statement is generic, but a forEach statement can be used only with an array.
c) Only a forEach statement lets you specify your own iterator.
d) A forEach statement is generic, but a for statement can be used only with an array.

3. Review the code below. Which statement calls the addTax function and passes 50 as an argument?
function addTax(total) {
return total * 1.05;
}

a) addTax = 50;
b) return addTax 50;
c) addTax(50);
d) addTax 50;

4. How would you use this function to find out how much tax should be paid on $50?

function addTax(total) {
return total * 1.05;
}

a) addTax = 50;
b) return addTax 50;
c) addTax(50);
d) addTax 50 ;

5. Which statement is the correct way to create a variable called rate and assign it the value 100?

a) let rate = 100;


b) let 100 = rate
c) 100 = let rate
d) rate = 100

6. Which statement creates a new Person object called “student”?

a) var student = new Person();


b) var student = construct Person;
c) var student = Person();
d) var student = Person();

7. When would the final statement in the code shown be logged to the console?

let modal = document.querySelector(‘#result’);


setTimeout(function(){
modal.classList.remove(‘hidden);
}, 10000);
console.log(‘Results shown’);

a) after 10 second
b) after results are received from the HTTP request
c) after 10000 seconds
d) immediately

*8. You’ve written the code shown to log a set of consecutive values, but it instead results in the value 5,
5, 5, and 5 being logged to the console. Which revised version of the code would result in the value 1, 2,
3 and 4 being logged?

for (var i = 1; i <= 4; i++) {


setTimeout(function () {
console.log(i);
}, i * 10000);
}

a) for (var i=1; i<=4; i++){ (function(i){ setTimeout(function(){ console.log(j); }, j*1000); })(j) }
b) while (var i=1; i<=4; i++) { setTimeout(function() { console.log(i); }, i*1000); }
c) for (var i=1; i<=4; i++) { (function(j) { setTimeout(function(){ console.log(j); }, j*1000); })(i) }
d) for (var j=1; j<=4; j++) { setTimeout(function() { console.log(j); }, j*1000); }

9. How does a function create a closure?

a) It reloads the document whenever the value changes.


b) It returns a reference to a variable in its parent scope.
c) It completes execution without returning.
d) It copies a local variable to the global scope.

Explanation: A closure gives you access to an outer function’s scope from an inner function. In
JavaScript, closures are created every time a function is created, at function creation time.

function init() {
var name = 'Mozilla'; // name is a local variable created by init
function displayName() { // displayName() is the inner function, a closure
alert(name); // use variable declared in the parent function
}
displayName();
}
init();

10. Which statement creates a new function called discountPrice?

a) let discountPrice = function(price) { return price * 0.85; };


b) let discountPrice(price) { return price * 0.85; };
c) let function = discountPrice(price) { return price * 0.85; };
d) discountPrice = function(price) { return price * 0.85; };

11. What is the result in the console of running the code shown?

var Storm = function () {};


Storm.prototype.precip = ‘rain’;
var WinterStorm = function () {};
WinterStorm.prototype = new Storm();
WinterStorm.prototype.precip = ‘snow’;
var bob = new WinterStorm();
console.log(bob.precip);
a) storm()
b) undefined
c) ‘rain’
d) ‘snow’

Explanation: Sometimes you want to add new properties (or methods) to an object constructor. The
JavaScript property allows you to add new properties to object constructors:

function Person() {}
Person.prototype.nationality = "English";
var aPerson = new Person();
console.log(aPerson.nationality)

12. You need to match a time value such as 12:00:32. Which of the following regular expressions would
work for your code?

a) /[0-9]{2,}:[0-9]{2,}:[0-9]{2,}/
b) /\d\d:\d\d:\d\d/
c) /[0-9]+:[0-9]+:[0-9]+/
d) /::/

13. What is the result in the console of running this code?

‘use strict’;
function logThis() {
this.desc = ‘logger’;
console.log(this);
}
new logThis();
a) undefined
b) window
c) {desc: “logger”}
d) function

14. How would you reference the text ‘avenue’ in the code shown?
let roadTypes = [‘street’, ‘road’, ‘avenue’, ‘circle’];

a) roadTypes.2
b) roadTypes[3]
c) roadTypes.3
d) roadTypes[2]

15. What is the result of running this statement?


console.log(typeof(42));

a) ‘float’
b) ‘value’
c) ‘number’
d) ‘integer’

16. Which property references the DOM object that dispatched an event?

a) self
b) object
c) target
d) source

17. You’re adding error handling to the code shown. Which code would you include within the if
statement to specify an error message?

function addNumbers(x, y) {
if (isNaN(x) || isNaN(y)) {
}
}

a) exception(‘One or both parameters are not numbers’)


b) catch(‘One or both parameters are not numbers’)
c) error(‘One or both parameters are not numbers’)
d) throw(‘One or both parameters are not numbers’)

18. Which method converts JSON data to a JavaScript object?

a) JSON.fromString();
b) JSON.parse()
c) JSON.toObject()
d) JSON.stringify()

19. When would you use a conditional statement?

a) When you want to reuse a set of statements multiple times.


b) When you want your code to choose between multiple options.
c) When you want to group data together.
d) When you want to loop through a group of statement.

20. What would be the result in the console of running this code?

for (var i = 0; i < 5; i++) {


console.log(i);
}
a) 12345
b) 1234
c) 01234
d) 012345

21. Which Object method returns an iterable that can be used to iterate over the properties of an
object?

a) Object.get()
b) Object.loop()
c) Object.each()
d) Object.keys()

22. After the following code, what is the value of a.length?

var a = [‘dog’, ‘cat’, ‘hen’];


a[100] = ‘fox’;
console.log(a.length);

a) 101
b) 3
c) 4
d) 100

*23. What is one difference between collections created with Map and collections created with Object?

a) You can iterate over values in a Map in their insertion order.


b) You can count the records in a Map with a single method call.
c) Keys in Maps can be strings.
d) You can access values in a Map without iterating over the whole collection.
e) Map.prototype.size returns the number of elements in a Map, whereas Object does not have a
built-in method to return its size.

Explanation: You can get the size of a Map easily while you have to manually keep track of size for an
Object. Link: https://stackoverflow.com/questions/18541940/map-vs-object-in-javascript

24. What is the value of dessert.type after executing this code?

const dessert = { type: ‘pie’ };


dessert.type = ‘pudding’;

a) pie
b) The code will throw an error.
c) pudding
d) undefined

25. 0 && hi

a) ReferenceError
b) True
c) 0
d) false

Explanation: When the first argument of the AND function evaluates to false , the overall value must
be false

26. Which of the following operators can be used to do a short-circuit evaluation?

a) ++
b) —
c) ==
d) ||

Explanation: The && and || operators are short circuit operators. A short circuit operator is one that
doesn't necessarily evaluate all of its operands. Realize that the condition (0 == 1 && whatever) can't
possibly be true, no matter what the whatever condition happens to be.

27. Which statement sets the Person constructor as the parent of the Student constructor in the
prototype chain?

a) Student.parent = Person;
b) Student.prototype = new Person();
c) Student.prototype = Person;
d) Student.prototype = Person();

28. Why would you include a “use strict” statement in a JavaScript file?

a) to tell parsers to interpret your JavaScript syntax loosely


b) to tell parsers to enforce all JavaScript syntax rules when processing your code
c) to instruct the browser to automatically fix any errors it finds in the code
d) to enable ES6 features in your code

29. Which Variable-defining keyword allows its variable to be accessed (as undefined) before the line
that defines it?

a) all of them
b) const
c) var
d) let

30. Which of the following values is not a Boolean false?

a) Boolean(0)
b) Boolean(“”)
c) Boolean(NaN)
d) Boolean(“false”)

31. Which of the following is not a keyword in JavaScript?

a) this
b) catch
c) function
d) array

32. Which variable is an implicit parameter for every function in JavaScript?

a) Arguments
b) args
c) argsArray
d) argumentsList

33. For the following class, how do you get the value of 42 from an instance of X?

class X {
get Y() {
return 42;
}
}

a) x.get(‘Y’)
b) x.Y
c) x.Y()
d) x.get().Y

Explain:

var x = new X();


console.log(x.Y)

34. What is the result of running this code?

sum(10, 20);
diff(10, 20);
function sum(x, y) {
return x + y;
}
let diff = function (x, y) {
return x – y;
};

a) 30, ReferenceError, 30, -10


b) 30, ReferenceError
c) 30, -10
d) ReferenceError, -10

Explain: cannot access before initialization

35. Why is it usually better to work with Objects instead of Arrays to store a collection of records?

a) Objects are more efficient in terms of storage.


b) Adding a record to an object is significantly faster than pushing a record into an array.
c) Most operations involve looking up a record, and objects can do that better than arrays.
d) Working with objects makes the code more readable.
36. Which statement is true about the “async” attribute for the HTML script tag?

a) It can be used for both internal and external JavaScript code.


b) It can be used only for internal JavaScript code.
c) It can be used only for internal or external JavaScript code that exports a promise.
d) It can be used only for external JavaScript code.

Explanation: <script src="demo_async.js" async></script>

If the async attribute is set, the script is downloaded in parallel to parsing the page, and executed as
soon as it is available. The async attribute is only for external scripts

37. How do you import the lodash library making it top-level Api available as the “_” variable?

a) import _ from ‘lodash’;


b) import ‘lodash’ as _;
c) import ‘_’ from ‘lodash;
d) import lodash as _ from ‘lodash’;

Explanation: Lodash is a JavaScript library that helps programmers write more concise and maintainable
JavaScript. Lodash makes JavaScript easier by taking the hassle out of working with arrays, numbers,
objects, strings, etc. Lodash’s modular methods are great for: Iterating arrays, objects, & strings.
Manipulating & testing values etc. Visit: https://lodash.com/

If you use various 3rd-party libraries when developing, you might have encountered several unpleasant
effects, for example: increasing build time and complexity, our bundle size grows exponentially etc.
There are many ways to optimize our code to overcome these problems. Read to optimize imports of
the Lodash library: https://www.blazemeter.com/blog/the-correct-way-to-import-lodash-libraries-a-
benchmark

38. What does the following expression evaluate to?


[] == [];

a) True
b) undefined
c) []
d) False

39. What is the name of a function whose execution can be suspended and resumed at a later point?

a) Generator function
b) Arrow function
c) Async/ Await function
d) Promise function

Explanation: A generator is a function that can stop midway and then continue from where it
stopped. In short, a generator appears to be a function but it behaves like an iterator. A generator is a
function which returns an object on which you can call next(). Every invocation of next() will return an
object of shape.
40. Which statement is true about Functional Programming?

a) Every object in the program has to be a function.


b) Code is grouped with the state it modifies.
c) Date fields and methods are kept in units.
d) Side effects are not allowed.

Explanation: It was React which encourages functional-based design when using their library since it
enforces you not to mutate your objects and not introduce side-effects as well. Functional Programming
is a programming paradigm where you mostly construct and structure your code using functions. You
could also say that Functional Programming was simply a bunch of functions that don’t allow outside
scope nor mutation of objects. Benefits: https://blog.bitsrc.io/functional-programming-in-javascript-
how-and-why-94e7a97343b

41. Your code is producing the error: TypeError: Cannot read property ‘reduce’ of undefined. What does
that mean?

a) You are calling a method named reduce on an object that’s declared but has no value.
b) You are calling a method named reduce on an object that does not exist.
c) You are calling a method named reduce on an empty array.
d) You are calling a method named reduce on an object that’s has a null value.

42. Which choice is not a unary operator?

a) typeof
b) delete
c) instanceof
d) void

Explanation: +, -, ++, --, ! , typeof, delete, void all are unary

43. What type of scope does the end variable have in the code shown?’

var start = 1;
if (start === 1) {
let end = 2;
}

a) conditional
b) block
c) global
d) function

Explanation: A block statement is used to group zero or more statements.

44. What will the value of y be in this code:

const x = 6 % 2;
const y = x ? ‘One’ : ‘Two’;
a) One
b) undefined
c) TRUE
d) Two

45. Which keyword is used to create an error?

a) throw
b) exception
c) catch
d) error

46. What’s one difference between the async and defer attributes of the HTML script tag?

a) The defer attribute can work synchronously.


b) The defer attribute works only with generators.
c) The defer attribute works only with promises.
d) The defer attribute will asynchronously load the scripts in order.

Explanation: Async scripts are executed as soon as the script is loaded, so it doesn't guarantee the order
of execution. Defer scripts guarantees the order of execution in which they appear in the page.
With async, the file gets downloaded asynchronously and then executed as soon as it’s downloaded.

With defer, the file gets downloaded asynchronously, but executed only when the document parsing is
completed.

47. This program has a problem. What is it?

var a;
var b = (a = 3) ? true : false;

a) You cannot use a ternary operator in the right-hand side of an assignment.


b) You cannot define a variable without initializing it first.
c) The condition in the ternary statement is using the assignment operator.
d) The code is using the deprecated var keyword.

48. Which statement references the DOM node created by the code shown?
<p class=”pull”>lorem ipsum</p>

a) Document.querySelector(‘class.pull’)
b) document.querySelector(‘.pull’);
c) Document.querySelector(‘pull’)
d) Document.querySelector(‘#pull’)

49. What is the result in the console of running the code shown?
var start = 1;
function setEnd() {
var end = 10;
}
setEnd();
console.log(end);
a) 10
b) 0
c) ReferenceError
d) Undefined

50. What will this code log in the console?

function sayHello() {
console.log(‘hello’);
}console.log(sayHello.prototype);

a) undefined
b) “hello”
c) an object with a constructor property
d) an error message

51. Which collection object allows unique value to be inserted only once?

a) Object
b) Set
c) Array
d) Map

52. What two values will this code print?

function printA() {
console.log(answer);
var answer = 1;
}
printA();
printA();
a) 1 then 1
b) 1 then undefined
c) undefined then undefined
d) undefined the 1

53. How does the forEach() method differ from a for statement?

a) forEach allows you to specify your own iterator, whereas for does not.
b) forEach can be used only with strings, whereas for can be used with additional data types.
c) forEach can be used only with an array, whereas for can be used with additional data types.
d) for loops can be nested; whereas forEach loops cannot.

54. Which choice is an incorrect way to define an arrow function that returns an empty object?

a) => ({})
b) => {}
c) => { return {};}
d) => (({}))

Explanation: arrow = () => ({}); Here arrow function have to write this way

*55. Why might you choose to make your code asynchronous?

a) to start tasks that might take some time without blocking subsequent tasks from executing
immediately
b) to ensure that tasks further down in your code are not initiated until earlier tasks have
completed
c) to make your code faster
d) to ensure that the call stack maintains a LIFO (Last in, First Out) structure

Explanation: In a single threaded synchronous environment, only one piece of code can run at a time. If
your code is waiting for a response, it can delay the execution of the program and therefore delay what
the user sees on their end.

56. Which expression evaluates to true?

a) [3] == [3]
b) 3 == ‘3’
c) 3 != ‘3’
d) 3 === ‘3’

57. Which of these is a valid variable name?

a) 5thItem
b) firstName
c) grand total
d) function

58. Which method cancels event default behavior?

a) cancel()
b) stop()
c) preventDefault()
d) prevent()

59. Which method do you use to attach one DOM node to another?

a) attachNode()
b) getNode()
c) querySelector()
d) appendChild()

60. Which statement is used to skip iteration of the loop?

a) break
b) pass
c) skip
d) continue

61. Which choice is valid example for an arrow function?

a) (a,b) => c
b) a, b => {return c;}
c) a, b => c
d) { a, b } => c

62. Which concept is defined as a template that can be used to generate different objects that share
some shape and/or behavior?

a) class
b) generator function
c) map
d) proxy

63. If you attempt to call a value as a function but the value is not a function, what kind of error would
you get?

a) TypeError
b) SystemError
c) SyntaxError
d) LogicError

Explanation:

var a = [1, 2]
a();

64. Which method is called automatically when an object is initialized?

a) create()
b) new()
c) constructor()
d) init()

65. What is the result of running the statement shown?

let a = 5;
console.log(++a);

a) 4
b) 10
c) 6
d) 5
66. You’ve written the event listener shown below for a form button, but each time you click the button,
the page reloads. Which statement would stop this from happening?

button.addEventListener(
‘click’,
function (e) {
button.className = ‘clicked’;
},
false,
);

a) e.blockReload();
b) button.preventDefault();
c) button.blockReload();
d) e.preventDefault();

67. Which statement represents the starting code converted to an IIFE?

a) function() { console.log(‘lorem ipsum’); }()();


b) function() { console.log(‘lorem ipsum’); }();
c) (function() { console.log(‘lorem ipsum’); })();

Explanation: An Immediately-invoked Function Expression (IIFE) is a way to execute functions


immediately, as soon as they are created. IIFEs are very useful because they don't pollute the global
object, and they are a simple way to isolate variables declarations

(() => {
// statements
})();

68. Which statement selects all img elements in the DOM tree?

a) Document.querySelector(‘img’)
b) Document.querySelectorAll(‘<img>’)
c) Document.querySelectorAll(‘img’)
d) Document.querySelector(‘<img>’)

69. Why would you choose an asynchronous structure for your code?

a) To use ES6 syntax


b) To start tasks that might take some time without blocking subsequent tasks from executing
immediately
c) To ensure that parsers enforce all JavaScript syntax rules when processing your code
d) To ensure that tasks further down in your code aren’t initiated until earlier tasks have
completed

70. What is the HTTP verb to request the contents of an existing resource?

a) DELETE
b) GET
c) PATCH
d) POST

Explanation: HTTP defines a set of request methods to indicate the desired action to be performed for a
given resource. These request methods are sometimes referred to as HTTP verbs e.g: GET, HEAD, POST,
DELETE, CONNECT, PATCH

GET: The GET method requests a representation of the specified resource. Requests using GET should
only retrieve data.

const Http = new XMLHttpRequest();


const url = “https://jsonplaceholder.typicode.com/posts”;
Http.open(“GET”,url);
Http.send();
Http.onreadystatechange=(e)=>{
console.log(Http.responseText);
}

71. Which event is fired on a text field within a form when a user tabs to it, or clicks or touches it?

a) focus
b) blur
c) hover
d) enter

72. What is the result in the console of running this code?

function logThis() {
console.log(this);
}
logThis();

a) function
b) undefined
c) Function.prototype
d) window

*73. Which class-based lifecycle method would be called at the same time as this effect Hook?

useEffect(() => {
// do things
}, []);

a) componentWillUnmount
b) componentDidUpdate
c) render
d) componentDidMount

Explanation: The componentDidMount() method allows us to execute the React code when the
component is already placed in the DOM (Document Object Model).
componentDidMount() {
setTimeout(() => {
this.setState({ color: 'wheat' });
}, 2000);
}

74. How would you use the TaxCalculator to determine the amount of tax on $50?

class TaxCalculator {
static calculate(total) {
return total * 0.05;
}
}

a) calculate(50);
b) new TaxCalculator().calculate($50);
c) TaxCalculator.calculate(50);
d) new TaxCalculator().calculate(50);

Explanation: If calculate wasn’t static then answer d

75. What is the value of dessert.type after executing this code?

const dessert = { type: ‘pie’};


dessert.type = ‘pudding’;
const seconds = dessert;
seconds.type = ‘fruit’;

a) pie
b) undefined
c) fruit
d) pudding

76. What is the output of this code?

let rainForests = [“Amazon”,”Borneo”,”Cerrado”,”Congo”];


rainForests.splice(0,2);
console.log(rainForests);

a) [‘Cerrado’, ‘Congo’]
b) [‘Amazon’, ‘Borneo’, ‘Cerrado’, ‘Congo’]
c) [‘Amazon’, ‘Borneo’, ‘Cerrado’]
d) [‘Amazon’, ‘Borneo’]

77. What will this code print?

var v = 1;
var f1 = function(){
console.log(v);
}
var f2 = function(){
var v = 2;
f1();
};
f2();
a) 2
b) 1
c) undefined
d) Nothing –this code will throw an Error

*78 What is wrong with this code?

const foo = {
bar(){
console.log(“Hello, World!)”;
},
name: “Albert”,
age: 26,
}

a) Functions cannot be declared as properties of objects;


b) The function bar needs to be defined as key/value pair;
c) Nothing. There are no errors
d) Trailing commas are not allowed in JavaScript

79. What will be logged to the console?

console.log("I");
setTimeout(() => {
console.log("love");
}, 0);
console.log("JavaScript!");

a) I love JavaScript
b) love I JavaScript
c) I JavaScript love
d) The output may change with each execution of the code and cannot be determined

80. How do you remove the property name from this object?

const foo = {
name: “Albert”
};

a) delete foo.name;
b) remove foo.name;
c) delete name from foo;
d) del foo.name;

*81(a) What is the difference between the map() and the forEach() methods on the Array prototype?

a) There is no difference
b) The forEach() method returns null, whereas the map() performs operations on each value in the
array.
c) The Map() method returns a new array with a transformation applied on each item in the
original array, whereas the forEach method iterates through an array with no return value
d) The forEach method returns a new array with a transformation applied to each item in the
original array, whereas the map method iterates through an array with no return value

Explanation: forEach always returns undefined. map() creates a new array from calling a function for
every array element. There is no way to stop or break a forEach() loop other than by throwing an
exception.

82. What line is missing from the code?

for(var i=0; i<vowels.length; i++){


console.log(vowels[i]);
}
//Print on a separate line
//a
//e
//i …

a) let vowels = “aeiou”.toArray();


b) let vowels = {“a”, “e”, “i", “o”, “u”};
c) let vowels = Array.of(“aeiou”);
d) let vowels = “aeiou”;

*83. What will this code log to the console?

const foo = [1, 2, 3];


const [n] = foo;
console.log(n);

a) NaN
b) Nothing. This is not proper JavaScript syntax and will throw an error
c) 1
d) undefined

©SAZZAD SAJU
Email: sazzadsaju17@gmail.com
Answer given guess where...

[END OF QUIZ]
1(d) 2(b) 3(c) 4(c) 5(a) 6(a) 7(d) 8(c) 9(b) 10(a) 11(d) 12(b) 13(c) 14(d) 15(c) 16(c) 17(d) 18(b) 19(b) 20(c)
21(d) 22(a) 23(b) 24(c) 25(c) 26(d) 27(b) 28(b) 29(c) 30(d) 31(d) 32(a) 33(b) 34(a) 35(c) 36(d) 37(a) 38(d)
39(a) 40(d) 41(b) 42(c) 43(b) 44(d) 45(a) 46(d) 47(c) 48(b) 49(c) 50(c) 51(b) 52(c) 53(c) 54(b) 55(b) 56(b)
57(b) 58(c) 59(d) 60(d) 61(a) 62(a) 63(a) 64(c) 65(c) 66(d) 67(c) 68(c) 69(d) 70(b) 71(a) 72(c) 73(d) 74(c)
75(c) 76(a) 77(b) 78(c) 79(c) 80(a) 81(c) 82(d) 83(c)

You might also like