JavaScript quiz 1

This quiz of 122 questions is from Evgenii Bazhanov's project. Special thanks to him and all of the contributors!

I formatted and sometimes improved the questions. I enriched the solutions with my own selection of relevant links and sometimes additional comments.

If you like this quiz, you should consider getting on my mailing list.

Lexical structure 01 (Q28)

Why would you include a 'use strict' statement in a JavaScript file?

  1. To tell parsers to interpret your JavaScript syntax loosely.
  2. To tell parsers to enforce all JavaScript syntax rules when processing your code.
  3. To instruct the browser to automatically fix any errors it finds in the code.
  4. To enable ES6 features in your code.

Solution

  1. To tell parsers to enforce all JavaScript syntax rules when processing your code.

Relevant resource(s):

Lexical structure 02 (Q31)

Which of the following is not a keyword in JavaScript?

  1. this
  2. catch
  3. function
  4. array

Solution

  1. array

Relevant resource(s):

Lexical structure 03 (Q60)

Which of these is a valid variable name?

  1. 5thItem
  2. firstName
  3. grand total
  4. function

Solution

  1. firstName

Relevant resource(s):

Lexical structure 04 (Q66)

How do you add a comment to JavaScript code?

  1. ! This is a comment
  2. # This is a comment
  3. \\ This is a comment
  4. // This is a comment

Solution

  1. // This is a comment

Relevant resource(s):

Types, values and variables 01 (Q4)

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

  1. let rate = 100;
  2. let 100 = rate;
  3. 100 = let rate;
  4. rate = 100;

Solution

  1. let rate = 100;

Relevant resource(s):

Types, values and variables 02 (Q15)

console.log(typeof 42);

What is the result of running the previous statement?

  1. 'float'
  2. 'value'
  3. 'number'
  4. 'integer'

Solution

  1. 'number'

Relevant resource(s):

Types, values and variables 03 (Q29)

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

  1. const
  2. var
  3. let
  4. var and let

Solution

  1. var

Relevant resource(s):

Types, values and variables 04 (Q30, Q132, Q151)

Which expression evaluates to true?

  1. Boolean(0)
  2. Boolean('')
  3. Boolean(NaN)
  4. Boolean('false')

Solution

  1. Boolean('false')

Relevant resource(s):

Types, values and variables 05 (Q79)

let obj;
console.log(obj);

What does the previous code print to the screen?

  1. ReferenceError: obj is not defined
  2. {}
  3. undefined
  4. null

Solution

  1. undefined

Relevant resource(s):

Types, values and variables 06 (Q123)

console.log(typeof 41.1);

What does the previous code print to the screen?

  1. ReferenceError
  2. 'decimal'
  3. float
  4. 'number'

Solution

  1. 'number'

Relevant resource(s):

Types, values and variables 07 (Q145)

console.log(typeof NaN);

What does the previous code print to the screen?

  1. 'object'.
  2. Number.
  3. String.
  4. None of the other solutions.

Solution

  1. None of the other solutions.

Explanation

This question is a bit tricky. The typeof operator always return a string. So the initial code would return the string 'number' and not Number.

Relevant resource(s):

Types, values and variables 08 (Q45)

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

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

  1. conditional
  2. block
  3. global
  4. function

Solution

  1. block

Relevant resource(s):

Types, values and variables 09 (Q98)

let x = 6 + 3 + '3';
console.log(x);

What does the previous code print to the screen?

  1. '93'
  2. 93
  3. '633'
  4. '66'

Solution

  1. '93'

Relevant resource(s):

Types, values and variables 10 (Q107)

console.log(typeof 'blueberry');

What does the previous code print to the screen?

  1. 'string'
  2. String
  3. [String]
  4. ['string']

Solution

  1. 'string'

Relevant resource(s):

Types, values and variables 11 (Q115)

const lion = 1; // line 1
let tiger = 2; // line 2
var bear; // line 3

++lion; // line 5
bear += lion + tiger; // line 6
tiger++;  // line 7

What line of code causes the previous code to throw an error?

  1. line 5, because lion cannot be reassigned a value.
  2. line 6, because the += operator cannot be used with the undefined variable bear.
  3. line 5, because the prefix (++) operator does not exist in JavaScript.
  4. line 3, because the variable bear is left undefined.

Solution

  1. line 5, because lion cannot be reassigned a value.

Relevant resource(s):

Types, values and variables 12 (Q120)

if (true) {
  var x = 5;
  const y = 6;
  let z = 7;
}
console.log(x + y + z);

What happens when you run the previous code?

  1. It will throw a ReferenceError about x.
  2. It will print 18.
  3. It will print undefined.
  4. It will throw a ReferenceError about y.

Solution

  1. It will throw a ReferenceError about y.

Relevant resource(s):

Explanation

The var statement declares a variable x that is not block-scoped. So, x will be accessible within the console.log() statement. Its value will be 5.

On the other hand, the let statement declares a variable y that is block-scoped. So, it won't be accessibe from outside the curly braces of the if statement. Within the console.log() statement, the JavaScript parser will throw a ReferenceError when trying to get the value of y, since y doesn't exist in the current scope (global scope).

Types, values and variables 13 (Q126)

const cat = { name: 'Athena' };

function swap(feline) {
  feline.name = 'Wild';
  feline = { name: 'Tabby' };
}

swap(cat);
console.log(cat.name);

What does the previous code print to the screen?

  1. undefined
  2. 'Wild'
  3. 'Tabby'
  4. 'Athena'

Solution

  1. 'Wild'

Explanation

When swap(cat); is executed, the local variable feline, scoped to the function swap, is assigned the object { name: 'Athena' }.

Therefore, the variables feline and cat reference the same object.

On the first line of the function, the name property of feline is changed to 'Wild'. Since feline and cat reference the same object, the name of the object referenced by the variable cat is also changed to 'Wild'.

On the following line of the function, the local variable feline is assigned a new object. The variables feline and cat stop referencing the same object. The object referenced by the variable cat stays as it is. It is the object { name: 'Wild' }.

Therefore, the console.log(cat.name) prints 'Wild'.

Types, values and variables 14 (Q128)

const myFunc = () => {
  const a = 2;
  return () => console.log('a is ' + a);
};
const a = 1;
const test = myFunc();
test();

What does the previous code print to the screen?

  1. a is 1.
  2. a is undefined.
  3. It won't print anything.
  4. a is 2.

Solution

  1. a is 2.

Relevant resource(s):

Types, values and variables 15 (Q152)

How would you check if the word 'pot' is in the word 'potato'?

  1. 'pot'.indexOf('potato') !== -1
  2. 'potato'.includes('Pot')
  3. 'potato'.includes('pot')
  4. 'potato'.contains('pot')

Solution

  1. 'potato'.includes('pot')

Relevant resource(s):

Types, values and variables 16 (Q114)

Which value is not falsy?

  1. []
  2. undefined
  3. 0
  4. null

Solution

  1. []

Relevant resource(s):

Types, values and variables 17 (Q67)

const a = 'Not a function';
a();

If you attempt to call a value as a function but the value is not a function (like in the previous code), what kind of error would you get?

  1. TypeError
  2. SystemError
  3. SyntaxError
  4. LogicError

Solution

  1. TypeError

Relevant resource(s):

var 01 (Q8)

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?

  1. for (var i = 1; i <= 4; i++) {
      setTimeout(function () {
        console.log(i);
      }, i * 10000);
    }
  2. for (var i = 1; i <= 4; i++) {
      (function (i) {
        setTimeout(function () {
          console.log(j);
        }, j * 1000);
      })(j);
    }
  3. for (var i = 1; i <= 4; i++) {
      setTimeout(function () {
        console.log(i);
      }, i * 1000);
    }
  4. for (var i = 1; i <= 4; i++) {
      (function (j) {
        setTimeout(function () {
          console.log(j);
        }, j * 1000);
      })(i);
    }
  5. for (var j = 1; j <= 4; j++) {
      setTimeout(function () {
        console.log(j);
      }, j * 1000);
    }

Solution

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

Relevant resource(s):

This question is quite tricky, and the concepts behind the solutions are challenging. Take the time to read the resources I mention. Don't worry if you don't get it straight away, these are quite advanced concepts.

var 02 (Q52)

var start = 1;
function setEnd() {
  var end = 10;
}
setEnd();
console.log(end);

What does the previous code print to the screen?

  1. 1
  2. 10
  3. ReferenceError
  4. undefined

Solution

  1. ReferenceError

Relevant resource(s):

Expressions and operators 01 (Q1)

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

  1. <>
  2. ~
  3. ==!
  4. !==

Solution

  1. !==

Relevant resource(s):

Expressions and operators 02 (Q25)

const result = 0 && 'hi';
console.log(result);

What does the previous code print to the screen?

  1. ReferenceError
  2. true
  3. 0
  4. false

Solution

  1. 0

Relevant resource(s):

Expressions and operators 03 (Q26)

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

  1. ++
  2. --
  3. ==
  4. ||

Solution

  1. ||

Relevant resource(s):

Expressions and operators 04 (Q38)

[] == [];

What does the following expression evaluate to?

  1. true
  2. undefined
  3. []
  4. false

Solution

  1. false

Relevant resource(s):

Note: in JavaScript, arrays are objects.

Expressions and operators 06 (Q46)

const x = 6 % 2;
const y = x ? 'One' : 'Two';

What is the value of y in the previous code?

  1. 'One'
  2. undefined
  3. true
  4. 'Two'

Solution

  1. 'Two'

Explanation

The expression 6 % 2 produces (or evalutes to) 0. Therefore, the variable x is assigned the integer 0.

0 is a falsy value in JavaScript. Therefore, the second part of the ternary operator applies. The variable y is assigned the string 'Two'.

Relevant resource(s):

Expressions and operators 07 (Q49)

let a;
const b = (a = 3) ? true : false;

The previous program has a problem. What is it?

  1. The condition in the ternary is using the assignment operator.
  2. You can't define a variable without initializing it.
  3. You can't use a ternary in the right-hand side of an assignment operator.
  4. The variable a is not initialized with a value.

Solution

  1. The condition in the ternary is using the assignment operator.

Explanation

There is no point in using a ternary operator if the condition always evaluates to true. The assignment expression (a = 3) always evaluates to 3 (the assigned value), which is a truthy value.

Note that the assigment expression (a = 0) always evaluate to false, since 0 is a falsy value.

Relevant resource(s):

Expressions and operators 08 (Q59)

Which expression evaluates to true?

  1. [3] == [3]
  2. 3 == '3'
  3. 3 != '3'
  4. 3 === '3'

Solution

  1. 3 == '3'

Relevant resource(s):

Expressions and operators 09 (Q69)

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

What does the previous code print to the screen?

  1. 4
  2. 10
  3. 6
  4. 5

Solution

  1. 6

Relevant resource(s):

My advice: don't use the increment operator in your code. It's best to use +=. It clarifies the intent of your code and prevents from any undesired or forgotten side-effect.

Expressions and operators 10 (Q122)

const a = { x: 1 };
const b = { x: 1 };

Given the previous code, which statement will evaluate to false?

  1. a['x'] === b['x']
  2. a != b
  3. a === b
  4. a.x === b.x

Solution

  1. a === b

Relevant resource(s):

Expressions and operators 11 (Q131)

let conservation = true;
let deforestation = false;
let acresOfRainForest = 100;
if (/* Snipped goes here */){
    ++acresOfRainForest;
}

Which snippet allows the acresOfRainForest variable to increase?

  1. conservation && !deforestation
  2. !deforestation && !conservation
  3. !conservation || deforestation
  4. deforestation && conservation || deforestation

Solution

  1. conservation && !deforestation

Relevant resource(s):

Expressions and operators 12 (Q136)

a = 5;
b = 4;
console.log(a++(+(+(+b))));

What does the previous code print to the screen?

  1. 18
  2. 10
  3. 9
  4. 20

Solution

  1. 9

Explanation

First, the expression a++ is evaluated. It evaluates to the integer 5.

Then, the expression (+(+(+b))) is evaluated, from the most inner parenthesis to the most outer ones.

(+b) evaluates to the positive integer +4, which is the same as 4.

Similarly, (+(4)) evaluates to +4, which is the same as 4.

Finally, the expression (5(+4)) evaluates to (5 + 4), which is 9.

Relevant resource(s):

Expressions and operators 13 (Q143)

What does the ... operator do in JavaScript?

  1. It is used to spread iterables to individual elements.
  2. It describe the datatype of undefined.
  3. No such operator exists.

Solution

  1. It is used to spread iterables to individual elements.

Relevant resource(s):

Expressions and operators 14 (Q155)

const compare = function (test1, test2) {
  // Missing line
};

compare(1078, '1078'); // returns true

Which line is missing from the previous code if you expect the code to evaluate to true?

  1. test1 == test2;
  2. return test1 === test2;
  3. return test1 == test2;
  4. return test1 != test2;

Solution

  1. return test1 == test2;

Relevant resource(s):

Statements 01 (Q17)

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

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

  1. exception('One or both parameters are not numbers');
  2. catch('One or both parameters are not numbers');
  3. error('One or both parameters are not numbers');
  4. throw('One or both parameters are not numbers');

Solution

  1. throw('One or both parameters are not numbers');

Relevant resource(s):

When using throw, it is common to throw an Error object rather than a string:

throw new Error('One or both parameters are not numbers');

However, the syntax with the string as used above is correct:

throw('One or both parameters are not numbers');

Statements 02 (Q19)

When would you use a conditional statement?

  1. When you want to reuse a set of statements multiple times.
  2. When you want your code to choose between multiple options.
  3. When you want to group data together.
  4. When you want to loop through a group of statement.

Solution

  1. When you want your code to choose between multiple options.

Relevant resource(s):

Statements 03 (Q20)

for (var i = 0; i < 5; i++) {
  console.log(i);
}

What does the previous code print to the screen?

  1. 1 2 3 4 5
  2. 1 2 3 4
  3. 0 1 2 3 4
  4. 0 1 2 3 4 5

Solution

  1. 0 1 2 3 4

Relevant resource(s):

  • The for statement.

Statements 04 (Q47)

Which keyword is used to create an error?

  1. throw
  2. exception
  3. catch
  4. error

Solution

  1. throw

Relevant resource(s):

Statements 05 (Q51)

let answer = true;
if (answer === false) {
  return 0;
} else {
  return 10;
}

What value does the previous code return?

  1. 10
  2. true
  3. false
  4. 0

Solution

  1. 10

Relevant resource(s):

Statements 06 (Q63)

What statement can be used to skip an iteration in a loop?

  1. break
  2. pass
  3. skip
  4. continue

Solution

  1. continue

Relevant resource(s):

Statements 07 (Q99)

Which statement can take a single expression as input and then look through a number of choices until one that matches that value is found?

  1. else
  2. when
  3. if
  4. switch

Solution

  1. switch

Relevant resource(s):

Statements 08 (Q106)

Which JavaScript loop ensures that at least a singular iteration will happen?

  1. do…while
  2. forEach
  3. while
  4. for

Solution

  1. do…while

Relevant resource(s):

Statements 09 (Q94)

// Missing Line
for (let i = 0; i < vowels.length; i += 1) {
  console.log(vowels[i]);
}
// Each letter printed on a separate line as follows:
// a
// e
// i
// o
// u

What line is missing from the previous code?

  1. const vowels = 'aeiou'.toArray();
  2. const vowels = Array.of('aeiou');
  3. const vowels = {'a', 'e', 'i', 'o', 'u'};
  4. const vowels = 'aeiou';

Solution

  1. const vowels = 'aeiou';

Relevant resource(s):

Statements 10 (Q110)

let rainForestAcres = 10;
let animals = 0;

while (rainForestAcres < 13 || animals <= 2) {
  rainForestAcres++;
  animals += 2;
}

console.log(animals);

What does the previous code print ot the screen?

  1. 2
  2. 4
  3. 6
  4. 8

Solution

  1. 6

Explanation

The key is to know how many iterations the while loop allows. This depends on the values of rainForestAcres and animals before each iteration:

  1. Before 1st iteration. rainForestAcres: 10, animals: 0.
  2. Before 2nd iteration. rainForestAcres: 11, animals: 2.
  3. Before 3rd iteration. rainForestAcres: 12, animals: 4.
  4. Before theoritical 4th iteration. rainForestAcres: 13, animals: 6. Since rainForestAcres < 13 is false, there is no 4th iteration.

Objects 01 (Q21)

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

  1. Object.get()
  2. Object.loop()
  3. Object.each()
  4. Object.keys()

Solution

  1. Object.keys()

Relevant resource(s):

Objects 02 (Q24)

const dessert = { type: 'pie' };
dessert.type = 'pudding';

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

  1. 'pie'
  2. The code will throw an error.
  3. 'pudding'
  4. undefined

Solution

  1. 'pudding'

Relevant resource(s):

Objects 03 (Q76)

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

What does the previous code print to the screen?

  1. function
  2. undefined
  3. Function.prototype
  4. The global object

Solution

  1. The global object

Relevant resource(s):

Objects 04 (Q81)

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

What is wrong with the previous code?

  1. The function bar needs to be defined as a key/value pair.
  2. Trailing commas are not allowed in JavaScript.
  3. Functions cannot be declared as properties of objects.
  4. Nothing, everything is fine.

Solution

  1. Nothing, everything is fine.

Relevant resource(s):

Objects 05 (Q84)

const foo = {
  name: 'Albert',
};

How do you remove the property name from the foo object?

  1. delete name from foo;
  2. delete foo.name;
  3. del foo.name;
  4. remove foo.name;

Solution

  1. delete foo.name;

Relevant resource(s):

Objects 06 (Q92)

const obj = {
  a: 1,
  b: 2,
  c: 3,
};

const obj2 = {
  ...obj,
  a: 0,
};

console.log(obj2.a, obj2.b);

What does the previous code print to the screen?

  1. Nothing, it throws an error.
  2. 0 2
  3. undefined 2
  4. 1 2

Solution

  1. 0 2

Relevant resource(s):

Objects 07 (Q35)

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

  1. Objects are more efficient in terms of storage.
  2. Adding a record to an object is significantly faster than pushing a record into an array.
  3. Most operations involve looking up a record, and objects are more adpated than arrays to do this.
  4. Working with objects makes the code more readable.

Solution

  1. Most operations involve looking up a record, and objects are more adpated than arrays to do this.
  2. Working with objects makes the code more readable.

Explanation

Records in an object can be retrieved using their key which can be any given value (e.g. an employee ID, a city name, etc.), whereas to retrieve a record from an array we need to know its index.

Objects 08 (Q116)

const person = { name: 'Dave', age: 40, hairColor: 'blue' };
const result = Object.keys(person).map((x) => x.toUpperCase());

What will be the value of result after running the previous code?

  1. It will throw a TypeError.
  2. ["Name", "Age", "HairColor"]
  3. ["DAVE", 40, "BLUE"]
  4. ["NAME", "AGE", "HAIRCOLOR"]

Solution

  1. ["NAME", "AGE", "HAIRCOLOR"]

Relevant resource(s):

Objects 09 (Q119)

let obj = {};

How can you attempt to access the property a.b on obj without throwing an error if a is undefined?

  1. obj?.a.b
  2. obj.a?.b
  3. obj[a][b]
  4. obj.?a.?b

Solution

  1. obj.a?.b

Relevant resource(s):

Objects 10 (Q125)

let bear = {
  sound: 'roar',
  roar() {
    console.log(this.sound);
  },
};

bear.sound = 'grunt';
let bearSound = bear.roar;
bearSound();

What does the previous code print to the screen?

  1. Nothing is printed to the console.
  2. 'grunt'
  3. undefined
  4. 'roar'

Solution

  1. undefined

Explanation

When the function bearSound() is executed, the property sound of the object referred by this is printed to the screen.

In the global scope in which bearSound() is executed, this refers to the global object, either window or global depending on where you are running the code (in a browser or on Node).

Since the global object doesn't have a sound property, undefined is printed to the screen.

Relevant resource(s):

Objects 11 (Q134)

let cat = Object.create({ type: 'lion' });
cat.size = 'large';

let copyCat = { ...cat };
cat.type = 'tiger';

console.log(copyCat.type, copyCat.size);

What does the previous code print to the screen?

  1. 'tiger' 'large'
  2. 'lion' undefined
  3. undefined 'large'
  4. 'lion' 'large'

Solution

  1. undefined 'large'

Explanation

On the first line, an object cat is created. Its prototype is the object { type: 'lion' }, i.e. the argument of Object.create().

This means that cat.type returns the string 'lion', thanks to prototypal inheritance. The JavaScript engine first looks for a property named type on the cat object. If it doesn't find one, it looks in the prototype. Here, the prototype happens to have a property named type, so the JavaScript engine stops climbing up the prototype chain. But note that the type property is not an own property of cat. It is "inherited" from its prototype. In other words, at this point of the code, the object cat doesn't have any own property, i.e. properties defined at its "level".

The second line of the code adds an own property named size to the cat object. At this point, the cat object looks like this: { size: 'large' }.

Then, a copyCat object is created by using the spread operator (...). At this point, the copyCat object looks like this: { size: 'large' }. Thanks to the use of the spread operator and to the fact that the size property has a primitive value (a string), the copyCat object happens to be a deep copy of the cat object. In other words, the 2 objects are totally independent from one another: an update of the value of the property size on 1 object doesn't affect the other object and vice versa.

Then, a property named type is added to the cat object. This doesn't change the copyCat object. Also, the cat object now has an own property named type. This own property overrides the type property defined on the prototype of cat. A this point, cat.type now returns the string 'tiger' instead of the string 'lion'.

To sum up, this is what the 2 objects look like:

  1. cat: { size: 'large', type: 'tiger' }.
  2. copyCat: { size: 'large' }.

copyCat doesn't have a type property, and none of its prototypes do. Note that the prototypes of copyCat are: Object.prototype then null. So copyCat.type returns the primitive value undefined.

copyCat has an own property size. copyCat.size returns the string 'large'.

Relevant resource(s):

Objects 12 (Q141)

const obj1 = { first: 20, second: 30, first: 50 };
console.log(obj1);

What does the previous code print to the screen?

  1. first: 30 , second: 50.
  2. first: 50 , second: 30.
  3. first: 30 , second: 20.
  4. None of the other solutions.

Solution

  1. first: 50 , second: 30.

Relevant resource(s):

Objects 13 (Q42)

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

  1. You are calling a method named reduce on undefined.
  2. You are calling a method named reduce on an object that does not exist.
  3. You are calling a method named reduce on an empty array.
  4. You are calling a method named reduce on null.

Solution

  1. You are calling a method named reduce on undefined.

Relevant resource(s):

Arrays 01 (Q2, Q56)

How is a forEach statement different from a for statement?

  1. Only a for statement uses a callback function.
  2. A for statement is generic, but a forEach statement can be used only with an array.
  3. Only a forEach statement lets you specify your own iterator.
  4. A forEach statement is generic, but a for statement can be used only with an array.

Solution

  1. A for statement is generic, but a forEach statement can be used only with an array.

Relevant resource(s):

Arrays 02 (Q14)

let roadTypes = ['street', 'road', 'avenue', 'circle'];

How would you reference the text 'avenue' in the code above?

  1. roadTypes.2
  2. roadTypes[3]
  3. roadTypes.3
  4. roadTypes[2]

Solution

  1. roadTypes[2]

Relevant resource(s):

Arrays 03 (Q22)

const a = ['dog', 'cat', 'hen'];
a[100] = 'fox';
console.log(a.length);

What does the previous code print to the screen?

  1. 101
  2. 3
  3. 4
  4. 100

Solution

  1. 101

Relevant resource(s):

Arrays 04 (Q83)

const foo = [1, 2, 3];
const [n] = foo;
console.log(n);

What does the previous code print to the screen?

  1. 1
  2. undefined
  3. NaN
  4. This is not proper JavaScript syntax and an error is thrown.

Solution

  1. 1

Relevant resource(s):

Arrays 05 (Q85)

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

  1. The forEach() method returns a new array with a transformation applied on each item in the original array, whereas the map() method iterates through an array with no return value.
  2. The forEach() method returns a single output value, whereas the map() method performs operation on each value in the array.
  3. 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.
  4. None of the other solutions.

Solution

  1. None of the other solutions.

Explanation

The following answer is almost right: 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.

Almost, because the forEach() method, like every other methods in JavaScript, does return a value. In this case, it returns the primitive value undefined.

Relevant resource(s):

Arrays 06 (Q90)

let rainForests = ['Amazon', 'Borneo', 'Cerrado', 'Congo'];
rainForests.splice(0, 2);
console.log(rainForests);

What does the previous code print to the screen?

  1. ["Amazon","Borneo","Cerrado","Congo"]
  2. ["Cerrado", "Congo"]
  3. ["Congo"]
  4. ["Amazon","Borneo"]

Solution

  1. ["Cerrado", "Congo"]

Relevant resource(s):

Arrays 07 (Q91)

const numbers = [1, 2, 3, 4, 5];
//MISSING LINE

Which missing line would allow you to create five variables (one, two, three, four, five) that correspond to their numerical values (1, 2, 3, 4, 5)?

  1. const [one, two, three, four, five] = numbers;
  2. const { one, two, three, four, five } = numbers;
  3. const [one, two, three, four, five] = [numbers];
  4. const { one, two, three, four, five } = { numbers };

Solution

  1. const [one, two, three, four, five] = numbers;

Relevant resource(s):

Arrays 08 (Q93)

let animals = ['jaguar', 'eagle'];
// Missing Line
console.log(animals.pop()); // Prints 'jaguar'

Which line could you add to the previous code to print 'jaguar' to the console?

  1. animals.filter(e => e === "jaguar");
  2. animals.reverse();
  3. animals.shift();
  4. animals.pop();

Solution

  1. animals.pop();

Relevant resource(s):

Arrays 09 (Q96)

let matrix = [['You','Can'],['Do','It'],['!','!','!']];

How would you access the word 'It' from this multidimensional array?

  1. matrix[2][2]
  2. matrix[1][1]
  3. matrix[1,2]
  4. matrix[1][2]

Solution

  1. matrix[1][1]

Relevant resource(s):

Arrays 10 (Q97)

const animals = ['Rabbit', 'Dog', 'Cat'];
animals.unshift('Lizard');

What does the previous code do?

  1. It adds 'Lizard' to the start of the animals array.
  2. It adds 'Lizard' to the end of the animals array.
  3. It replaces 'Rabbit' with 'Lizard' in the animals array.
  4. It replaces 'Cat' with 'Lizard' in the animals array.

Solution

  1. It adds 'Lizard' to the start of the animals array.

Relevant resource(s):

Arrays 11 (Q103, Q121)

const arr1 = [2, 4, 6];
const arr2 = [3, 5, 7];

console.log([...arr1, ...arr2]);

What does the previoux code print to the screen?

  1. [2, 3, 4, 5, 6, 7]
  2. [3, 5, 7, 2, 4, 6]
  3. [[2, 4, 6], [3, 5, 7]]
  4. [2, 4, 6, 3, 5, 7]

Solution

  1. [2, 4, 6, 3, 5, 7]

Relevant resource(s):

Arrays 12 (Q105)

Which choice is not an array method?

  1. array.slice()
  2. array.shift()
  3. array.push()
  4. array.replace()

Solution

  1. array.replace()

Relevant resource(s):

Arrays 13 (Q109)

const myNumbers = [1, 2, 3, 4, 5, 6, 7];
const myFunction = (arr) => {
  return arr.map((x) => x + 3).filter((x) => x < 7);
};
console.log(myFunction(myNumbers));

What does the previous code print to the screen?

  1. [4, 5, 6, 7, 8, 9, 10]
  2. [4, 5, 6, 7]
  3. [1, 2, 3, 4, 5, 6]
  4. [4, 5, 6]

Solution

  1. [4, 5, 6]

Relevant resource(s):

Arrays 14 (Q111)

let cipherText = [...'YZOGUT QGMORTZ MTRHTILS'];
let plainText = '';

/* Missing Snippet */

console.log(plainText); // YOU GOT THIS

Which snippet could you add to the previous code to print "YOU GOT THIS" to the console?

  1. for (let key of cipherText.keys()) {
      plainText += key % 2 === 0 ? key : ' ';
    }
  2. for (let [index, value] of cipherText.entries()) {
      plainText += index % 2 !== 0 ? value : '';
    }
  3. for (let [index, value] of cipherText.entries()) {
      plainText += index % 2 === 0 ? value : '';
    }
  4. for (let value of cipherText) {
      plainText += value;
    }

Solution

  1. for (let [index, value] of cipherText.entries()) {
      plainText += index % 2 === 0 ? value : '';
    }

Relevant resource(s):

Arrays 15 (Q112)

const pokedex = ['Snorlax', 'Jigglypuff', 'Charmander', 'Squirtle'];
pokedex.pop();
console.log(pokedex.pop());

Which Pokemon does the previous code print to the screen?

  1. 'Snorlax'
  2. 'Jigglypuff'
  3. 'Charmander'
  4. 'Squirtle'

Solution

  1. 'Charmander'

Relevant resource(s):

Arrays 16 (Q117)

let animals = ['eagle', 'osprey', 'salmon'];
let key = animal => animal === 'salmon';

if(/* Insert Snippet Here */){
  console.log('swim');
}>

Which snippet could you insert to the previous code to print 'swim' to the console?

  1. animals.every(key)
  2. animals.some(key).length === 1
  3. animals.filter(key) === true
  4. animals.some(key)

Solution

  1. animals.some(key)

Relevant resource(s):

Arrays 18 (Q135)

let animals = [{ type: 'lion' }, 'tiger'];
let clones = animals.slice();

clones[0].type = 'bear';
clones[1] = 'sheep';

console.log(animals[0].type, clones[0].type);
console.log(animals[1], clones[1]);

What does the previous code print to the screen?

  1. 'bear' 'bear' 'tiger' 'sheep'.
  2. 'lion' 'bear' 'sheep' 'sheep'.
  3. 'bear' 'bear' 'tiger' 'tiger'.
  4. 'lion' 'bear' 'tiger' 'sheep'.

Solution

  1. 'bear' 'bear' 'tiger' 'sheep'.

Explanation

On line 2, the method slice() creates a shallow copy of animals which is assigned to the variable clones.

animals[0] and clones[0] reference (or point to) the same object. In other words, any change of the object referenced by animals[0] or clones[0] will impact both arrays.

On the other hand, animals[1] and clones[1] point to 2 different primitive values. So index 1 of an array can be reassigned a new value with no consequence on index 1 of the other array.

Relevant resource(s):

Functions 01 (Q3)

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

In the previous code, which statement calls the addTax function and passes 50 as an argument?

  1. addTax = 50;
  2. return addTax 50;
  3. addTax(50);
  4. addTax 50;

Solution

  1. addTax(50);

Relevant resource(s):

Functions 02 (Q9)

How does a function create a closure?

  1. It reloads the document whenever the value changes.
  2. It returns a reference to a variable in its parent scope.
  3. It completes execution without returning.
  4. It copies a local variable to the global scope.

Solution

  1. It returns a reference to a variable in its parent scope.

Relevant resource(s):

Functions 03 (Q10)

Which statement creates a new function called discountPrice?

  1. let discountPrice = function (price) {
      return price * 0.85;
    };
  2. let discountPrice(price) {
      return price * 0.85;
    };
  3. let function = discountPrice(price) {
      return price * 0.85;
    };
  4. discountPrice = function (price) {
      return price * 0.85;
    };

Solution

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

Relevant resource(s):

Functions 04 (Q32)

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

  1. arguments
  2. args
  3. argsArray
  4. argumentsList

Solution

  1. arguments

Relevant resource(s):

Functions 05 (Q34)

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

let diff = function (x, y) {
  return x - y;
};

What does the previous code print to the screen?

  1. 30, ReferenceError, 30, -10
  2. 30, ReferenceError
  3. 30, -10
  4. ReferenceError, -10

Solution

  1. 30, ReferenceError

Relevant resource(s):

Functions 06 (Q39)

What type of function can have its execution suspended and then resumed at a later point?

  1. Generator function
  2. Async function
  3. Arrow function
  4. Promise function

Solution

  1. Generator function

Relevant resource(s):

Functions 07 (Q40)

const v = 1;
const f1 = function () {
  console.log(v);
};

const f2 = function () {
  const v = 2;
  f1();
};

f2();

What does the previous code print to the screen?

  1. 2
  2. 1
  3. Nothing - this code will throw an error.
  4. undefined

Solution

  1. 1

Relevant resource(s):

Functions 08 (Q57)

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

  1. => ({})
  2. => {}
  3. => { return {};}
  4. => (({}))

Solution

  1. => {}

Relevant resource(s):

Functions 09 (Q64)

Which choice is a valid example for an arrow function?

  1. (a, b) => c
  2. a, b => {return c;}
  3. a, b => c
  4. { a, b } => c

Solution

  1. (a, b) => c

Relevant resource(s):

Functions 10 (Q71)

Which statement represents an IIFE (Immediately Invoked Function Expression)?

  1. function() { console.log('lorem ipsum'); }()();
  2. function() { console.log('lorem ipsum'); }();
  3. (function() { console.log('lorem ipsum'); })();

Solution

  1. (function() { console.log('lorem ipsum'); })();

Relevant resource(s):

Functions 11 (Q100)

const sound = 'grunt';
const  bear = { sound: 'roar' };
function roar() {
  console.log(this.sound);
}

Which statement prints 'roar' to the screen?

  1. bear.bind(roar);
  2. roar.bind(bear);
  3. roar.apply(bear);
  4. bear[roar]();

Solution

  1. roar.apply(bear);

Relevant resource(s):

Functions 12 (Q127)

let thing;
let func = (str = 'no arg') => {
  console.log(str);
};
func(thing);
func(null);

What does the previous code print to the screen?

  1. null 'no arg'
  2. 'no arg' 'no arg'
  3. null null
  4. 'no arg' null

Solution

  1. 'no arg' null

Relevant resource(s):

Functions 13 (Q129, Q148)

const myFunc = (num1, num2 = 2, num3 = 2) => {
  return num1 + num2 + num3;
};
let values = [1, 5];
const test = myFunc(2, ...values);
console.log(test);

What does the previous code print to the screen?

  1. 8
  2. 6
  3. 2
  4. 12

Solution

  1. 8

Relevant resource(s):

OOP 01 (Q5)

Which statement creates a new Person object called "student"?

  1. const student = new Person();
  2. const student = construct Person;
  3. const student = Person();
  4. const student = construct Person();

Solution

  1. const student = new Person();

Relevant resource(s):

OOP 02 (Q7)

class Animal {
  static belly = [];
  eat() {
    Animal.belly.push('food');
  }
}
let a = new Animal();
a.eat();
console.log(/* Snippet Here */); // Prints food

Which snippet could you add to the previous code to print 'food' to the screen?

  1. a.prototype.belly[0]
  2. Object.getPrototype0f (a).belly[0]
  3. Animal.belly[0]
  4. a.belly[0]

Solution

  1. Animal.belly[0]

Relevant resource(s):

OOP 03 (Q11)

const Storm = function () {};
Storm.prototype.precip = 'rain';
const WinterStorm = function () {};
WinterStorm.prototype = new Storm();
WinterStorm.prototype.precip = 'snow';
const bob = new WinterStorm();
console.log(bob.precip);

What does the previous code print to the screen?

  1. Storm()
  2. undefined
  3. 'rain'
  4. 'snow'

Solution

  1. 'snow'

Explanation

The key for answering this question correctly is to have a clear view of the prototype chain. Here it is, from bottom to top:

  1. the bob object, which happens to be a WinterStorm instance.
  2. WinterStorm.prototype, which happens to be a Storm instance.
  3. Storm.prototype.

To return the value of bob.precip, the JavaScript engine climbs up the prototype chain, checking at each "level" if the object has an own property named precip.

bob doesn't have an own property named precip, so the JavaScript goes 1 level up to look for it.

WinterStorm.prototype has an own property precip, with the value 'snow'. The JavaScript engine has found what it was looking for and stops going up the prototype chain.

Relevant resource(s):

OOP 04 (Q13)

'use strict';
function logThis() {
  this.desc = 'logger';
  console.log(this);
}
new logThis();

What does the previous code print to the screen?

  1. undefined
  2. window
  3. {desc: "logger"}
  4. function

Solution

  1. {desc: "logger"}

Relevant resource(s):

OOP 05 (Q27)

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

  1. Student.parent = Person;
  2. Student.prototype = new Person();
  3. Student.prototype = Person;
  4. Student.prototype = Person();

Solution

  1. Student.prototype = new Person();

Relevant resource(s):

OOP 06 (Q33)

class X {
  get Y() {
    return 42;
  }
}
const x = new X();

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

  1. x.get('Y')
  2. x.Y
  3. x.Y()
  4. x.get().Y

Solution

  1. x.Y

Relevant resource(s):

OOP 07 (Q53)

function sayHello() {
  console.log('hello');
}

console.log(sayHello.prototype);

What does the previous code print to the screen?

  1. undefined.
  2. 'hello'.
  3. an object.
  4. an error message.

Solution

  1. an object.

Explanation

The sayHello() function, like any other JavaScript function, is an object which is an instance of the Function object.

The prototype of sayHello() is Function.prototype, which is an object.

That is why the following statement prints true:

console.log(Object.getPrototypeOf(sayHello) === Function.prototype);
// prints true

Relevant resource(s):

OOP 08 (Q65)

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

  1. class
  2. generator function
  3. map
  4. proxy

Solution

  1. class

Relevant resource(s):

OOP 09 (Q68)

Which method is called automatically when an object is initialized?

  1. create()
  2. new()
  3. constructor()
  4. init()

Solution

  1. constructor()

Relevant resource(s):

OOP 10 (Q80)

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

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

  1. calculate(50);
  2. new TaxCalculator.calculate(50);
  3. TaxCalculator.calculate(50);
  4. new TaxCalculator().calculate(50);

Solution

  1. TaxCalculator.calculate(50);

Relevant resource(s):

OOP 11 (Q118)

class RainForest {
  static minimumRainFall = 60;
}

let congo = new RainForest();
RainForest.minimumRainFall = 80;
console.log(congo.minimumRainFall);

What does the previous code print ot the screen?

  1. undefined
  2. 60
  3. 80
  4. null

Solution

  1. undefined

Relevant resource(s):

OOP 12 (Q142)

Which object in Javascript doesn't have a prototype?

  1. Object.prototype.
  2. All objects have prototype.
  3. None of the objects have prototype.
  4. Object.

Solution

  1. Object.prototype.

Relevant resource(s):

OOP 13 (Q43)

let arr = [];

How many prototype objects are in the chain for the previous array?

  1. 3
  2. 2
  3. 0
  4. 1

Solution

  1. 2

Explanation

Here is the prototype chain for the array arr, from bottom to up:

  1. Array.prototype. Since arr is an instance of the Array object, its prototype is Array.prototype.
  2. Object.prototype. Since Array.prototype is an object, its prototype is Object.prototype
  3. null, which is the prototype of Object.prototype, but it doesn't count as a prototype in the prototype chain.

So arr has 2 prototypes in its prototype chain.

Relevant resource(s):

OOP 14 (Q139)

In JavaScript, all objects inherit built-in properties from:

  1. a node.
  2. an instance variable.
  3. a prototype.
  4. an accessor.

Solution

  1. a prototype.

Relevant resource(s):

Other built-in objects 01 (Q12)

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

  1. /[0-9]{2,}:[0-9]{2,}:[0-9]{2,}/
  2. /\d\d:\d\d:\d\d/
  3. /[0-9]+:[0-9]+:[0-9]+/
  4. / : : /

Solution

  1. /\d\d:\d\d:\d\d/

Explanation

The regular expression /\d\d:\d\d:\d\d/ is the most correct because it will only match 2 digit time values. For example: '12:00:32'.

The regular expression /[0-9]{2,}:[0-9]{2,}:[0-9]{2,}/ would have worked if the repetitions range looked like [0-9]{2}. However, because of the comma, it will select 2 or more digits. For example, '120:000:321' matches.

The regular expression /[0-9]+:[0-9]+:[0-9]+/ will match any range of time digits, single and multiple. For instance, '1:2:3' and '111:222:333' match.

Relevant resource(s):

Other built-in objects 02 (Q18)

Which method converts JSON data to a JavaScript object?

  1. JSON.fromString();
  2. JSON.parse()
  3. JSON.toObject()
  4. JSON.stringify()

Solution

  1. JSON.parse()

Relevant resource(s):

Other built-in objects 03 (Q23)

Which statement(s) indicate a difference between collections created with Map and collections created with Object?

  1. You can iterate over values in a Map in their insertion order.
  2. You can count the records in a Map with a single method call.
  3. Keys in Maps can be strings.
  4. You can access values in a Map without iterating over the whole collection.

Solution

  1. You can iterate over values in a Map in their insertion order.
  2. You can count the records in a Map with a single method call.

Relevant resource(s):

Other built-in objects 04 (Q54, Q153)

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

  1. Object
  2. Set
  3. Array
  4. Map

Solution

  1. Set

Relevant resource(s):

Other built-in objects 05 (Q130)

const flagsJSON =
'{ "countries" : [' +
'{ "country":"Ireland" , "flag":"🇮🇪" },' +
'{ "country":"Serbia" , "flag":"🇷🇸" },' +
'{ "country":"Peru" , "flag":"🇵🇪" } ]}';

const flagDatabase = JSON.parse(flagsJSON);

Which code would you use to access the Irish flag?

  1. flagDatabase.countries[1].flag
  2. flagDatabase.countries[0].flag
  3. flagDatabase[1].flag
  4. flagsJSON.countries[0].flag

Solution

  1. flagDatabase.countries[0].flag

Relevant resource(s):

Other built-in objects 06 (Q137)

let cat = { type: 'tiger', size: 'large' };

let json = /* Snippet here */;

console.log(json); // '{"type":"tiger"}'

Which snippet could you add to this code to print '{"type": "tiger"}' to the console?

  1. cat.toJSON('type');
  2. JSON.stringify(cat, ['type']);
  3. JSON.stringify(cat);
  4. JSON.stringify(cat, /type/);

Solution

  1. JSON.stringify(cat, ['type']);

Relevant resource(s):

Other built-in objects 07 (Q140)

Which of the following are not server-side JavaScript objects?

  1. Date.
  2. FileUpload.
  3. Function.
  4. All of the other solutions.

Solution

  1. FileUpload.

Other built-in objects 08 (Q144)

How to stop an interval timer in Javascript?

  1. clearInterval.
  2. clearTimer.
  3. intervalOver.
  4. None of the other solutions.

Solution

  1. clearInterval.

Relevant resource(s):

Modules 01 (Q37)

How do you import the lodash library making it top-level API available as the "_" variable?

  1. import _ from 'lodash';
  2. import 'lodash' as _;
  3. import '_' from 'lodash;
  4. import lodash as _ from 'lodash';

Solution

  1. import _ from 'lodash';

Relevant resource(s):

Modules 02 (Q102)

// some-file.js
export const printMe = (str) => console.log(str);

Which statement correctly imports the previous code from some-file.js?

  1. import printMe from './some-file';
  2. import { printMe } from './some-file'
  3. import default as printMe from './some-file';
  4. const printMe = import './some-file';

Solution

  1. import { printMe } from './some-file';

Relevant resource(s):

Asynchronous 01 (Q6)

setTimeout(function () {
  console.log('Pending');
}, 10000);

console.log('Results shown');

In the previous code, when would 'results shown' be printed to the screen?

  1. after 10 seconds and after 'Pending'
  2. after 10 seconds but before 'Pending'
  3. after 10000 seconds and after 'Pending'
  4. immediately and before 'Pending'

Solution

  1. immediately and before 'Pending'

Relevant resource(s):

Asynchronous 02 (Q58, Q73)

Why might you choose to make your code asynchronous?

  1. to start tasks that might take some time without blocking subsequent tasks from executing immediately.
  2. to ensure that tasks further down in your code are not initiated until earlier tasks have completed.
  3. to make your code faster.
  4. It is not possible to make code asynchronous. Either it already is or it isn't. We have to deal with it as it is.

Solution

  1. to start tasks that might take some time without blocking subsequent tasks from executing immediately.

Relevant resource(s):

Asynchronous 03 (Q82)

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

What does the previous code print to the screen?

  1. I
    JavaScript!
    love
  2. love
    I
    JavaScript!
  3. I
    love
    JavaScript!
  4. The output may change with each execution of code and cannot be determined.

Solution

  1. I
    JavaScript!
    love

Relevant resource(s):

Asynchronous 04 (Q104)

Which method call is chained to handle a successful response returned by fetch()?

  1. done()
  2. then()
  3. finally()
  4. catch()

Solution

  1. then()

Relevant resource(s):

Functional programming 01 (Q41)

Which statement is true about functional programming?

  1. Every object in the program has to be a function.
  2. Code is grouped with the state it modifies.
  3. Date fields and methods are kept in units.
  4. Side effects are not allowed.

Solution

  1. Side effects are not allowed.

Relevant resource(s):

Functional programming 02 (Q86)

function makeAdder(x) {
  return function (y) {
    return x + y;
  };
}

const addFive = makeAdder(5);
console.log(addFive(3));

Which concept does the previous code illustrate?

  1. overloading
  2. closure
  3. currying
  4. overriding

Solution

  1. currying

Relevant resource(s):