JavaScript Essentials 2 Course Completion – JSE2 Final Test Exam Answers Full 100% 2025
The JavaScript Essentials 2 (JSE2) Final Test Answers is a crucial step for learners aiming to validate their understanding of advanced JavaScript concepts. This certification exam assesses knowledge of functions, objects, error handling, asynchronous programming, and modern ES6+ features. Achieving a 100% score demonstrates strong proficiency in JavaScript, making it a valuable credential for aspiring developers. In this guide, we provide the correct answers for the JSE2 Final Test (2025 edition) to help students review key concepts and ensure they are fully prepared.
Question 1:
You have called the following statement:
console.log(car.make);
What declaration should precede the statement so that the text Jeep appears in the console as a result of its execution?
Correct Answer: let car = {make: 'Jeep', model: 'Cherokee'};
Explanation: In JavaScript, an object is declared using curly braces {}
with key-value pairs. The correct syntax for defining an object with a property make
set to ‘Jeep’ is let car = {make: 'Jeep', model: 'Cherokee'};
. The incorrect options include an array notation []
instead of an object, an improperly formatted object, and a syntax error.
Question 2:
You are working on a web application that handles geometric shapes. You have created a JavaScript object to represent a circle:
let circle = {
center: {
x: 10,
y: 20
},
radius: 30
};
What is the correct formula to calculate the circumference based on the circle object?
Correct Answer: 2 * circle.radius * Math.PI
Explanation:
The formula for the circumference of a circle is 2 * π * radius
.
In this JavaScript object, the radius is stored as circle.radius
, so the correct expression is
2 * circle.radius * Math.PI
. The other options are incorrect because:
circle.radius * circle.radius * Math.PI
calculates the area, not the circumference.2 * circle.center.x * Math.PI
incorrectly uses thex
coordinate instead of the radius.circle.radius + circle.center.y
is an arbitrary sum with no relation to circumference.
Question 3:
You have declared a user
object that has one property: full name
let user = {
'full name': 'Mickey Mouse'
};
Which of the following is the correct way to refer to this property?
Correct Answer: user['full name']
Explanation:
In JavaScript, object properties that contain spaces or special characters must be enclosed in quotes when defined.
Since 'full name'
contains a space, it cannot be accessed using dot notation (i.e., user.full name
is invalid).
Instead, we must use bracket notation with a string key: user['full name']
. The other options are incorrect because:
user.'full name'
is invalid syntax.user[full name]
is incorrect becausefull name
is not defined as a variable.- The statement that you “cannot use a property name consisting of several words” is false, as JavaScript allows it when enclosed in quotes.
Question 4:
What will be the result of executing the following code?
let geoposition = {
latitude: 40.7128,
longitude: -74.0060,
altitude: 100,
city: "New York"
};
Object.keys(geoposition).forEach(key =>
console.log(geoposition[key])
);
Possible answers:
Correct Answer: It will display the values of all the properties.
Explanation:
The Object.keys(geoposition)
method returns an array containing all the keys of the geoposition
object.
Then, the forEach
method iterates over each key, using bracket notation geoposition[key]
to access and log the corresponding value.
This means that the console output will be:
40.7128 -74.006 100 New York
The other options are incorrect because:
forEach
can be used withObject.keys
, so no error occurs.- The code logs property values, not just the property names.
- The syntax is valid, so no syntax error occurs.
Question 5:
You have declared two tree
objects:
let tree1 = {
species: 'oak'
};
let tree2 = {
species: 'oak'
};
Which of the following comparisons will return true
?
Correct Answer: (tree1.species == tree2.species) && (tree1.species == tree2.species)
Explanation:
In JavaScript, objects are compared by reference, not by value. Even though tree1
and tree2
have identical properties,
they are two separate objects in memory. This means:
tree1 == tree2
andtree1 === tree2
both returnfalse
because they reference different objects.- The correct way to compare their property values is using
tree1.species == tree2.species
ortree1.species === tree2.species
, both of which returntrue
because the string values are the same. tree1 same tree2
is not valid JavaScript syntax.
Question 6:
What will be the population of the city stored in largestCity
after executing this code?
let city1 = {
name: 'New York',
population: 8537673
};
let city2 = {
name: 'Los Angeles',
population: 39776830
};
let largestCity = city1.population > city2.population ? { ...city1 } : { ...city2 };
Possible answers:
Correct Answer: 39776830
Explanation:
The ternary operator city1.population > city2.population ? { ...city1 } : { ...city2 }
checks which city has a larger population
and assigns a copy of that city object to largestCity
. Since city2.population (39776830)
is greater than city1.population (8537673)
,
the object assigned to largestCity
is a copy of city2
. Therefore, largestCity.population
is 39776830
.
The other options are incorrect because:
'Los Angeles'
refers to the city name, not the population.124744503
is not relevant to this calculation.8537673
is the population of New York, which is smaller than Los Angeles’ population.
Question 7:
There is one line of code missing in the code below:
let user = {
name: 'Huck',
surname: 'Finn',
// Insert line of code here.
};
user.show();
Select the correct missing line so that the executed code results in the following console output: Huck Finn
Correct Answer: show: function() {console.log(`${this.name} ${this.surname}`);}
Explanation:
In JavaScript, when defining methods inside an object, the this
keyword refers to the object itself.
The correct way to define the show
method inside the user
object is:
show: function() { console.log(`${this.name} ${this.surname}`); }
The other options are incorrect because:
user.show = {console.log(`${this.name} ${this.surname}`)}
incorrectly assigns an object instead of a function.show: function() {console.log(`${name} ${surname}`);}
will cause an error becausename
andsurname
are not defined in the function scope.show: function(this) {console.log(`${this.name} ${this.surname}`);}
has incorrect function syntax, as JavaScript functions do not takethis
as an explicit parameter.
Question 8:
You want to create a setter for the user’s first name, allowing you to set both _firstName
and _lastName
when updating the first name. Which line of code should you insert?
let user = {
_firstName: 'John',
_lastName: 'Doe',
// Insert a line of code here.
};
Select the correct answer:
Correct Answer: set firstName(name) { this._firstName = name; }
Explanation:
In JavaScript, setters are defined using the set
keyword, which allows updating object properties dynamically.
The correct way to define a setter for _firstName
inside the user
object is:
set firstName(name) { this._firstName = name; }
The other options are incorrect because:
_firstName() { this._firstName = name; }
is incorrect because it is a method, not a setter.firstName(name) { this._firstName = name; }
is a regular function, not a setter.this._firstName = name;
is an invalid standalone statement inside an object literal.
Question 9:
There is one line of code missing in the code below:
let mountain = {
name: 'Everest',
range: 'Himalayas'
}
// Insert line of code here.
delete mountain.range;
mountain.name = 'Lhotse';
mountain.height = 8516;
console.log(`${mountain.name} ${mountain.range} ${mountain.height}`);
Select the correct missing line so that the executed code results in the following console output: Lhotse undefined undefined
Question 10:
What should you insert into the function so that the created user object contains the name
and age
properties?
function createUser(name, age) {
/// Insert a line of code here.
}
const user = createUser('Alice', 25);
Select the correct answer:
Correct Answer: return { name: name, age: age };
Explanation:
The function createUser
is designed to return an object containing the name
and age
properties.
The correct way to do this in JavaScript is:
return { name: name, age: age };
The other options are incorrect because:
return { this.name: name, this.age: age };
is incorrect becausethis
is not needed in an object literal.createUser.name = name; createUser.age = age;
attempts to set properties on the function itself, not on a new object.this.name = name; this.age = age;
would work only ifcreateUser
were used as a constructor withnew
, but this is not the case.
Question 11:
There is one line of code missing in the code below:
let Point = function(x, y) {
// Insert line of code here.
this.y = y;
}
let point = new Point(100, 0);
let ColorPoint = function(color) {
this.color = color;
}
ColorPoint.prototype = point;
let cpoint = new ColorPoint('green');
console.log(cpoint.x);
Select the correct missing line so that the executed code results in the following console output: 100
Correct Answer: this.x = x;
Explanation:
The Point
function is a constructor, and when used with the new
keyword, it assigns properties to the newly created object.
To ensure that the x
property is correctly stored in instances of Point
, we must use:
this.x = x;
The other options are incorrect because:
return x;
does not assign the value to the object.Point.x = x;
incorrectly attempts to setx
on the constructor function itself, not on the instance.point.x = x;
is invalid becausepoint
is an instance ofPoint
, butx
is only available inside the constructor.
Question 12:
Which of the following code snippets correctly demonstrates the creation of an anonymous class for a “Person” object with a constructor that initializes the properties name
and age
?
Correct Answer:
let Person = class { constructor(name, age) { this.name = name; this.age = age; } }
Explanation:
In JavaScript, an anonymous class can be assigned to a variable using the class
keyword. The correct way to define a constructor
inside a class is by using the constructor
method, where properties are assigned using this
.
The correct syntax is:
let Person = class { constructor(name, age) { this.name = name; this.age = age; } }
Why are the other options incorrect?
- Option 2:
let Person = (name, age) => { constructor: { this.name = name; this.age = age; } }
– This is an incorrect use of arrow functions. Arrow functions cannot have constructors. - Option 3:
name = this.name; age = this.age;
– This reverses the assignment. It should bethis.name = name;
. - Option 4:
let Person = function(name, age) { this.name = name; this.age = age; }
– This defines a constructor function, not an anonymous class.
Question 13:
You have defined a class Mountain
whose constructor takes two arguments: name
and range
.
Which of the following is the correct way to create a mountain
object of this class?
Correct Answer: let mountain = new Mountain('Manaslu', 8156);
Explanation:
In JavaScript, when creating an object from a class, the new
keyword must be used to invoke the constructor.
The correct way to instantiate a Mountain
object is:
let mountain = new Mountain('Manaslu', 8156);
Why are the other options incorrect?
- Option 1:
let mountain = create Mountain('Manaslu', 8156);
– There is nocreate
keyword in JavaScript for class instantiation. - Option 3:
let mountain = Mountain('Manaslu', 8156);
– Calling a class function withoutnew
results in an error. - Option 4:
Mountain(let mountain, 'Manaslu', 8156);
– This syntax is invalid and does not follow JavaScript class instantiation rules.
Question 14:
What properties and methods does an instance of the “Book” class have when created with the following code?
class Book {
constructor(title, author) {
this.title = title;
this.author = author;
}
setGenre(genre) {
this.genre = genre;
}
}
let book = new Book('The Great Gatsby', 'F. Scott Fitzgerald');
book.setGenre('Fiction');
Correct Answer: Properties: title
, author
, genre
; Methods: setGenre
Explanation:
The Book
class constructor initializes two properties: title
and author
.
The method setGenre
dynamically adds the genre
property when called.
After executing:
let book = new Book('The Great Gatsby', 'F. Scott Fitzgerald'); book.setGenre('Fiction');
The object book
has:
- Properties:
title
,author
,genre
- Methods:
setGenre
Why are the other options incorrect?
- Option 2: Mentions
getGenre
, which does not exist in the class. - Option 3: Omits the
genre
property, which is added whensetGenre
is called. - Option 4: Incorrectly states that only
title
andauthor
exist, missinggenre
.
Question 15:
There is one line missing in the following code:
class Tree {
_species = 'oak';
// Insert line of code here.
}
let tree = new Tree();
tree.species = 'maple';
console.log(tree._species);
Select the correct missing line so that the executed code results in the following console output: maple
Correct Answer: set species (val) { this._species = val; }
Explanation:
In JavaScript, setter methods are defined using the set
keyword. The setter allows controlled modification of a property.
The correct syntax for defining a setter for the species
property while modifying _species
internally is:
set species(val) { this._species = val; }
Why are the other options incorrect?
- Option 1:
set _species (species) { this._species = species; }
– Setter methods should not use private property names (_species
) as their name. - Option 2:
_species set(species) { this._species = species; }
– This is an invalid syntax for defining a setter. - Option 4:
set (species) { this._species = species; }
– This syntax is incorrect since setter methods must have a property name afterset
.
Question 16:
What should you insert into the “Cat” class so that it properly inherits from the “Animal” class?
class Animal {
constructor(legs) {
this.legs = legs;
}
}
class Cat {
// Insert a line of code here.
speak() {
return 'Meow';
}
}
Correct Answer: class Cat extends Animal {}
Explanation:
In JavaScript, class inheritance is implemented using the extends
keyword.
The correct way to make the Cat
class inherit from the Animal
class is:
class Cat extends Animal { }
Why are the other options incorrect?
- Option 2:
class Cat : Animal {}
– This is incorrect syntax in JavaScript. The:
symbol is used in some other programming languages but not in JavaScript. - Option 3:
class Cat inherits from Animal {}
– JavaScript does not use theinherits from
syntax for inheritance. - Option 4:
class Cat inherits Animal {}
– Theinherits
keyword does not exist in JavaScript.
Question 17:
You have declared a Mountain
class and created a mountain
object from it:
class Mountain {
static className() { return 'Mountain'; }
}
mountain = new Mountain();
Select the correct call so that the executed code results in the following console output: Mountain
Correct Answer: Mountain.className()
Explanation:
In JavaScript, the static
keyword defines a method that belongs to the class itself rather than its instances.
Since className()
is a static method of Mountain
, it must be called on the class rather than an instance.
The correct way to call it is:
console.log(Mountain.className()); // Output: Mountain
Why are the other options incorrect?
- Option 2:
mountain ['static className']()
– This is an invalid way of accessing a method in JavaScript. - Option 3:
Mountain.className
– This returns the function reference instead of executing it. - Option 4:
mountain.className()
–mountain
is an instance, and static methods are not accessible on instances.
Question 18:
What will the following code output?
class Animal {}
class Dog extends Animal {}
const dog = new Dog();
const animal = new Animal();
console.log(dog instanceof Dog, dog instanceof Animal);
Correct Answer: true true
Explanation:
The instanceof
operator checks if an object is an instance of a class or its parent class in the prototype chain. Let’s analyze the two checks:
dog instanceof Dog
: Sincedog
was created usingnew Dog()
, it is an instance of theDog
class. This returnstrue
.dog instanceof Animal
: TheDog
class extendsAnimal
, meaning all instances ofDog
also inherit fromAnimal
. This returnstrue
.
Why are the other options incorrect?
- Option 1 (
false true
): Incorrect becausedog
is an instance ofDog
, so the first check should returntrue
. - Option 2 (
false false
): Incorrect because both checks returntrue
, notfalse
. - Option 3 (
true false
): Incorrect becausedog
is an instance of bothDog
andAnimal
.
Question 19:
A value parameter is missing from the Number
constructor in the place indicated in code:
Number(INSERT MISSING CODE HERE).toFixed(2);
Select the correct value so that the executed code results in the following console output: '0.01'
Correct Answer: '12e-3'
Explanation:
The Number()
constructor converts the given input into a number. To produce an output of '0.01'
using toFixed(2)
,
the input must be a number that rounds to 0.01
when formatted to two decimal places. Let’s analyze each option:
0.01e-2
→ This evaluates to0.0001
, which when formatted withtoFixed(2)
would return'0.00'
.'12e-3'
→ This is a string representation of12 × 10⁻³
, which is0.012
. When formatted to two decimal places, it rounds to'0.01'
.'-0x01'
→ This is a string containing a hexadecimal number. TheNumber()
constructor converts it to-1
, which does not produce the expected result.1
→ This is a whole number and would be formatted as'1.00'
, which does not match the expected output.
Final Explanation: '12e-3'
correctly converts to 0.012
, which rounds to '0.01'
when using toFixed(2)
.
Question 20:
You have a JavaScript function processText
that takes a string as input and processes it to return an array of words in reverse order. Fill in the missing line of code:
function processText(str) {
// Insert a line of code here.
}
console.log(processText('This is a sample text to reverse'));
Correct Answer: return str.split(' ').reverse();
Explanation:
The goal is to reverse the order of words in the string. The correct approach involves:
- Using
split(' ')
to convert the string into an array of words. - Applying
reverse()
to reorder the words in reverse.
The correct implementation is:
function processText(str) { return str.split(' ').reverse(); }
Why are the other options incorrect?
return str.join(' ').reverse();
–str
is a string, not an array, sojoin
does not apply.return str.join(' ').split(' ').reverse();
– This incorrectly assumesstr
is already an array.return str.reverse().split(' ');
–reverse()
does not work on strings, only arrays.
Final Output Example:
console.log(processText('This is a sample text to reverse')); // Output: ['reverse', 'to', 'text', 'sample', 'a', 'is', 'This']
Question 21:
The following code places a Date
class object containing the current time into the currentTime
variable:
let currentTime = new Date(Date.now());
The same effect can be achieved by using:
Correct Answer: let currentTime = new Date();
Explanation:
The Date.now()
method returns the current timestamp in milliseconds, which can be passed to the Date
constructor,
but it is unnecessary. The new Date()
constructor, when called without arguments, automatically initializes to the current date and time.
Thus, the following two lines are equivalent:
let currentTime = new Date(Date.now()); let currentTime = new Date();
Why are the other options incorrect?
let currentTime = new Date.now();
– Incorrect becauseDate.now()
returns a number, andnew
cannot be used with it.There is no other way to achieve this effect.
– Incorrect, asnew Date()
achieves the same result.let currentTime = new Date().now();
– Incorrect becausenow()
is not a method ofDate
objects, only of theDate
class.
Question 22:
What will be the value of result3
?
const numbers = [2, 4, 6, 8, 10];
const result1 = numbers.some(num => num % 2 === 1);
const result2 = numbers.every(num => num % 2 === 0);
const result3 = numbers.filter(num => num < 5);
Correct Answer: [2, 4]
Explanation:
The filter()
method iterates over the array and keeps only the elements that satisfy the given condition.
The condition in this case is num < 5
. The numbers
array is [2, 4, 6, 8, 10]
, so:
2
is less than5
→ ✅ Included4
is less than5
→ ✅ Included6
,8
, and10
are greater than5
→ ❌ Not included
Thus, result3
is:
[2, 4]
Why are the other options incorrect?
[2, 4, 6, 8]
– Incorrect because6
and8
are greater than5
.[2, 4, 6]
– Incorrect because6
does not satisfynum < 5
.[1]
– Incorrect because1
is not in the original array.
Question 23:
There is one line missing in the code below:
let points = [{x: 20, y: 20}, {x: 10, y: 30}, {x: 10, y: 100}];
// Insert a line of code here.
console.log(result);
What will appear in the console as a result of code execution?
Correct Answer: let result = points.map(e => e.x + e.y);
Explanation:
The map()
method applies a function to each element of the array and returns a new array with the results.
In this case, we need to sum the x
and y
properties of each object in the points
array.
The correct implementation is:
let result = points.map(e => e.x + e.y); console.log(result);
Expected Output:
[40, 40, 110]
Why are the other options incorrect?
let result = points.map(x + y);
– Incorrect becausex
andy
are not directly accessible, andmap()
requires a function.let result = points.map(e => {e.x + e.y});
– Incorrect because the curly braces `{}` define a function body but do not return a value. It should be written as an arrow function without `{}`.let result = points.map((e,n) => {n = e.x + e.y});
– Incorrect because assigning a value ton
does not return it, so the array would be filled with `undefined`.
Question 24:
Which line of code achieves the following output: red,green,purple,pink,orange
?
let colors = ['red', 'green', 'blue', 'yellow', 'orange'];
colors.splice(2, 2);
// Insert line of code here.
console.log(colors);
Correct Answer: colors.splice(2, 0, 'purple', 'pink');
Explanation:
The splice()
method modifies an array by removing, replacing, or adding elements at a specified index.
The correct approach here is:
- The first call
colors.splice(2, 2);
removes 2 elements starting at index2
('blue'
and'yellow'
). - To insert
'purple'
and'pink'
at index2
, we usecolors.splice(2, 0, 'purple', 'pink');
.
The final colors
array:
['red', 'green', 'purple', 'pink', 'orange']
Why are the other options incorrect?
colors.splice(2, 'purple', 'pink');
– Incorrect because the second argument should be a number (indicating elements to remove).colors.splice(2, 0, 1, 'purple', 'pink');
– Incorrect because1
is incorrectly placed.colors.splice(1, 1, 'purple', 'pink');
– Incorrect because it modifies the wrong index, changing'green'
instead.
Question 25:
Analyze the following code:
let s = new Set([1, 2, '100']);
s.add(2);
s.add('2');
console.log(`${s.has(2)} ${s.has('2')} ${s.size}`);
What will appear in the console as a result of code execution?
Correct Answer: true true 4
Explanation:
A Set
in JavaScript stores unique values. Let’s analyze the code:
new Set([1, 2, '100'])
initializes the set with three elements:1
,2
, and'100'
.s.add(2)
attempts to add2
again, but it’s ignored since2
already exists in the set.s.add('2')
adds the string'2'
as a separate, unique element (different from the number2
).
The final set contents are:
{1, 2, '100', '2'}
Console Output Analysis:
s.has(2)
– true (because2
is in the set)s.has('2')
– true (because'2'
as a string was added)s.size
– 4 (elements are1
,2
,'100'
,'2'
)
Final Output:
true true 4
Why are the other options incorrect?
true false 3
– Incorrect becauses.has('2')
is true and the size is 4.true true undefined
– Incorrect becauses.size
returns 4, not undefined.true false 4
– Incorrect becauses.has('2')
is true.
Question 26:
Considering the following code, what will be the result of accessing fruitColors.get('kiwi')
?
let fruitColors = new Map([
['apple', 'red'],
['banana', 'yellow'],
['grape', 'purple'],
['kiwi', 'green']
]);
fruitColors.set('blueberry', 'blue');
fruitColors.set('apple', 'green');
fruitColors.delete('banana');
console.log(fruitColors.get('kiwi'));
Correct Answer: 'green'
Explanation:
A Map
in JavaScript stores key-value pairs, allowing unique keys to store values.
Let’s analyze the code step by step:
- The initial
Map
contains:{ 'apple' => 'red', 'banana' => 'yellow', 'grape' => 'purple', 'kiwi' => 'green' }
fruitColors.set('blueberry', 'blue')
adds a new key-value pair.fruitColors.set('apple', 'green')
updates the existing key'apple'
to'green'
.fruitColors.delete('banana')
removes the'banana'
key from theMap
.
The final Map
looks like this:
{ 'apple' => 'green', 'grape' => 'purple', 'kiwi' => 'green', 'blueberry' => 'blue' }
Since the key 'kiwi'
still exists and its value was never modified, fruitColors.get('kiwi')
will return ‘green’.
Why are the other options incorrect?
'yellow'
– Incorrect because'banana'
was removed from theMap
.'purple'
– Incorrect because'kiwi'
was never assigned'purple'
; it remained'green'
.undefined
– Incorrect because'kiwi'
still exists in theMap
.
Question 27:
The following data is stored in JSON format:
let strMountain = '{ "name": "Lhotse", "range": "Himalayas" }';
Which statement/command should you use to convert the data to an object that will be written to the mountain
variable?
Correct Answer: let mountain = JSON.parse(strMountain);
Explanation:
JSON (JavaScript Object Notation) is a string-based format used to represent structured data. To convert JSON-formatted data stored as a string into a JavaScript object, the correct method to use is JSON.parse()
.
Breakdown of options:
JSON.parse(strMountain)
– ✅ Correct: This function converts a JSON string into a JavaScript object.JSON(strMountain)
– ❌ Incorrect: There is noJSON()
function in JavaScript.JSON.stringify(strMountain)
– ❌ Incorrect: This function converts a JavaScript object into a JSON string, but we need to do the opposite.Object(strMountain)
– ❌ Incorrect: This would convert the string into an object wrapper, not a JavaScript object parsed from JSON.
Final Output: The mountain
variable will store the following object:
{ name: "Lhotse", range: "Himalayas" }
This makes it possible to access mountain.name
and mountain.range
as JavaScript object properties.
Question 28:
Analyze the following code:
console.log(`${Math.round(2.3)} ${Math.floor(2.6)} ${Math.ceil(2.0)}`);
What will appear in the console as a result of the code execution?
Correct Answer: 2 2 3
Explanation:
Math.round(2.3)
→ Rounds 2.3 to the nearest integer → 2.Math.floor(2.6)
→ Floors 2.6 down to the nearest integer → 2.Math.ceil(2.0)
→ Ceils 2.0 up to the nearest integer → 3.
Final Output:
2 2 3
Breakdown of Incorrect Answers:
2 2 2
❌ → Incorrect becauseMath.ceil(2.0)
returns 3, not 2.3 3 3
❌ → Incorrect becauseMath.round(2.3)
andMath.floor(2.6)
return 2, not 3.3 2 2
❌ → Incorrect becauseMath.round(2.3)
returns 2, not 3.
This JavaScript code demonstrates the differences between Math.round()
, Math.floor()
, and Math.ceil()
, which are frequently used for rounding numbers.
Question 29:
You have created an object of the RegExp
class that you want to use to search for regular expressions:
let r = new RegExp('.\.jpg');
Select the correct alternative form of this declaration:
Correct Answer: let r = /.\.jpg/;
Explanation:
- The **best practice** in JavaScript for defining regular expressions is using **literal notation**:
/pattern/
. - The correct syntax for matching any character before
.jpg
is **/.\.jpg/
**. - The backslash
\
**escapes the dot (.)**, making it match **a literal period (.)** instead of “any character”. - Using **
new RegExp('.\.jpg')
** is incorrect because **escape sequences work differently** inside string literals.
Breakdown of Incorrect Answers:
let r = (.\.jpg);
– Invalid syntax; **regular expressions must be declared using either literals or the RegExp constructor**.let r = RegExp('.\.jpg');
– Incorrect escaping, as\.
inside a string does **not escape properly**.let r = \.\.jpg\;
– Not valid JavaScript syntax.
Thus, the correct answer is: let r = /.\.jpg/;
Question 30:
Analyze the following JavaScript code:
let firstArray = [1, 2];
Array.prototype.customMethod = function() {
console.log('Custom Method');
};
let secondArray = [3, 4];
firstArray.customMethod();
secondArray.customMethod();
What will be the result of executing this code?
Correct Answer: Two 'Custom Method' messages will appear in the console.
Explanation:
- In JavaScript, adding a method to
Array.prototype
makes it available to all array instances. - The method
customMethod
is assigned toArray.prototype
, meaning bothfirstArray
andsecondArray
inherit it. - When
firstArray.customMethod()
andsecondArray.customMethod()
are called, they execute successfully, logging'Custom Method'
twice.
Breakdown of Incorrect Answers:
An error will appear because the customMethod is bound to the Array class...
❌ → Incorrect. Prototype methods are inherited by all instances.An error will appear when trying to execute firstArray.customMethod()
❌ → Incorrect. Methods added to the prototype are available to existing instances.A single message 'Custom Method' will appear...
❌ → Incorrect. Both arrays inherit the method and execute it.
Thus, the correct answer is that two messages 'Custom Method'
will be displayed.
Question 31:
Analyze the following JavaScript code:
let fn = function (a, b, ...rest) {
console.log(`${a.length} ${rest.length}`);
}
fn('1', '2', '3', '4', '5');
What will appear in the console as a result of code execution?
Correct Answer: 1 3
Explanation:
- The function
fn
is defined with three parameters:a
,b
, and...rest
. - When calling
fn('1', '2', '3', '4', '5')
:a
receives the first argument:'1'
.b
receives the second argument:'2'
....rest
collects the remaining arguments:['3', '4', '5']
.
a.length
is1
because'1'
is a string with one character.rest.length
is3
becauserest
contains three elements.
Breakdown of Incorrect Answers:
undefined 3
❌ → Incorrect becausea.length
is defined (notundefined
).1 undefined
❌ → Incorrect becauserest.length
is valid and equals3
.5 undefined
❌ → Incorrect becausea.length
is1
(not5
).
Thus, the correct answer is: 1 3
.
Question 32:
Analyze the following JavaScript code:
let color = 'Red';
let printColor = (function() {
let color = 'Blue';
return color;
})();
console.log(`${color} ${printColor}`);
What will appear in the console as a result of code execution?
Correct Answer: Red Blue
Explanation:
- The variable
color
is globally declared as'Red'
. printColor
is assigned the result of an Immediately Invoked Function Expression (IIFE).- Inside the function, a new
color
variable is declared usinglet
, which is block-scoped. - Since this inner
color
is a different variable from the global one, it does not affect the outercolor
. - The function returns
'Blue'
, which is stored inprintColor
. - Thus, the
console.log(`${color} ${printColor}`)
outputs'Red Blue'
.
Breakdown of Incorrect Answers:
Blue Red
❌ → Incorrect becausecolor
is globally'Red'
, not'Blue'
.Red Red
❌ → Incorrect becauseprintColor
gets the'Blue'
value from the function.Blue Blue
❌ → Incorrect because the globalcolor
remains'Red'
.
Thus, the correct answer is: Red Blue
.
Question 33:
Analyze the following JavaScript code:
let fn = function(msg, n) {
console.log(`${msg}: ${this.a ** n}`);
};
// Insert the missing line here.
bfn(2, 3);
Select the correct missing line so that the executed code results in the following console output: result: 25
Correct Answer: let bfn = fn.bind({a: 5});
Explanation:
- The function
fn
takes two parameters:msg
andn
. - The function uses
this.a
, meaning we need to bind an object containinga
to it. bind()
creates a new function withthis
set to the provided object ({a: 5}
).bfn(2, 3)
calls the bound function with arguments2
and3
.- Since
a = 5
andn = 3
, the function computes5 ** 3 = 25
and logs:result: 25
.
Breakdown of Incorrect Answers:
apply()
andcall()
execute the function immediately, whereas we need to create a bound function.fn.bind({a: 5}, 'result')
would incorrectly bindmsg
too early.
Thus, the correct answer is: let bfn = fn.bind({a: 5});
.
Question 34:
In JavaScript, what is a callback function?
Correct Answer: A function that is called after a specific operation or event occurs.
Explanation:
- A callback function is a function passed as an argument to another function, to be executed later.
- It is often used in asynchronous programming, such as handling API responses, events, or timeouts.
- Example:
function greet(name, callback) { console.log("Hello, " + name); callback(); } function sayGoodbye() { console.log("Goodbye!"); } greet("Alice", sayGoodbye); // Output: // Hello, Alice // Goodbye!
Breakdown of Incorrect Answers:
- A callback is not a special function for declaring variables.
- It is not limited to mathematical operations; it can be used in any context requiring delayed execution.
- It does not convert data types, although it can be used inside functions that do.
Thus, the correct answer is: A function that is called after a specific operation or event occurs.
Question 35:
There is one line missing in the code below:
function* testGenerator() {
// Insert line of code here.
}
let gen = testGenerator();
console.log(`${gen.next().value} ${gen.next().value}`);
Select the correct missing line so that the executed code results in the following console output: a b
Correct Answer: yield ['a', 'b'];
Explanation:
- In JavaScript, generator functions use
yield
to return values one at a time. - Using
yield ['a', 'b'];
returns an array wheregen.next().value
gives ‘a’ and the next call gives ‘b’.
Breakdown of Incorrect Answers:
yield* ['a', 'b', 'c', 'd'];
– This would yield each element individually instead of as an array.yield ['a', 'b', 'c', 'd'];
– This would return the entire array as a single value.return ['a', 'b'];
– Returning terminates the generator and does not allow iteration.
Thus, the correct answer is: yield ['a', 'b'];
.
Question 36:
There is one line missing in the code below:
let printText = msg => console.log(msg);
let delay = 3000;
setTimeout(() => {
// Insert line of code here.
}, delay);
Select the correct missing line to ensure the console displays 'Delayed message'
with a delay of 5 seconds:
Correct Answer: setTimeout(() => printText('Delayed message'), 5000);
Explanation:
- The
setTimeout
function schedules the execution of a function after a given delay. - The correct approach is to use an arrow function
() => printText('Delayed message')
to ensureprintText
is executed with the correct argument. - Using
5000
ensures the message is displayed after 5 seconds.
Breakdown of Incorrect Answers:
printText('Delayed message', 5000);
– Incorrect because it calls the function immediately instead of delaying it.setTimeout(printText, 2000, 'Delayed message');
– Incorrect because it uses an extra argument incorrectly.setTimeout(printText.bind(this, 'Delayed message'), 5000);
– Incorrect because binding is unnecessary in this context.
Thus, the correct answer is: setTimeout(() => printText('Delayed message'), 5000);
.
Question 37:
Analyze the following JavaScript code:
let p = new Promise(function(resolve, reject) {
setTimeout(() => resolve(1), 1000);
});
p.then(a => console.log(`a ${a}`), b => console.log(`b ${b}`));
What will appear in the console as a result of code execution?
Correct Answer: a 1
Explanation:
- A
Promise
is created that resolves with the value1
after 1 second. - The
.then()
method takes two arguments:- The first callback (
a => console.log(`a ${a}`)
) runs when the promise resolves. - The second callback (
b => console.log(`b ${b}`)
) runs if the promise is rejected.
- The first callback (
- Since the promise is resolved, the first function is executed, logging
a 1
. - The second callback is ignored because there is no rejection.
Breakdown of Incorrect Answers:
a
– Incorrect becausea
alone does not log without the resolved value.a 1 b 1
– Incorrect because the rejection callback is not executed.b 1
– Incorrect because the promise is resolved, not rejected.
Thus, the correct answer is: a 1
.
Question 38:
Analyze the following JavaScript code:
let promiseA = new Promise(function(resolve) {
setTimeout(() => resolve('Apple'), 150);
});
let promiseB = new Promise(function(resolve) {
setTimeout(() => resolve('Banana'), 100);
});
promiseA.then(resultA => {
console.log(resultA);
return promiseB;
})
.then(resultB => {
console.log(resultB);
return 'Cherry';
})
.then(resultC => {
console.log(resultC);
});
What will appear in the console as a result of code execution?
Correct Answer: Apple Banana Cherry
Explanation:
promiseA
resolves after **150ms** with'Apple'
, whilepromiseB
resolves after **100ms** with'Banana'
.- The
then()
chain executes sequentially:- The first
then()
logsApple
and returnspromiseB
. - The second
then()
logsBanana
and returns the string'Cherry'
. - The third
then()
logsCherry
.
- The first
- Because
promiseA
starts first but takes longer (150ms), it logs **before**promiseB
in the chain.
Breakdown of Incorrect Answers:
Banana Apple Cherry
– Incorrect becausepromiseB
does not execute beforepromiseA
.Cherry Banana Apple
– Incorrect becauseCherry
is logged last.Banana Cherry Apple
– Incorrect becausepromiseA
executes beforepromiseB
in the chain.
Thus, the correct answer is: Apple Banana Cherry
.
Question 39:
Analyze the following JavaScript code:
let p = new Promise(function (resolve, reject) {
setTimeout(() => resolve('abc'), 100);
});
async function afn() {
console.log('def');
let x = await p;
console.log(x);
}
afn();
console.log('ghi');
What will appear in the console as a result of code execution?
Correct Answer: ghi def abc
Explanation:
p
is a Promise that resolves with'abc'
after **100ms**.- The function
afn()
is **asynchronous**, so when it is called:- It logs
def
immediately. - Then it **awaits**
p
, pausing its execution.
- It logs
- Meanwhile, the **next synchronous line** executes, logging
ghi
. - After 100ms, the promise resolves, and
afn()
resumes, loggingabc
.
Breakdown of Incorrect Answers:
def ghi abc
– Incorrect becauseghi
logs beforedef
finishes.ghi abc def
– Incorrect becauseabc
logs **after**def
.abc ghi def
– Incorrect becauseabc
must wait **100ms** due toawait
.
Thus, the correct answer is: ghi def abc
.
Question 40:
When using XMLHttpRequest (XHR) in JavaScript to make network requests, what is the purpose of the event listener added with the ‘load’ event?
Correct Answer: To listen for successful completion of the XHR request.
Explanation:
- The
'load'
event inXMLHttpRequest
is triggered when the request **successfully completes**. - It fires **only when the entire response has been received** and the request has **not encountered an error**.
- To handle **errors**, the
'error'
event should be used instead. - Monitoring **ready state changes** is done with the
readystatechange
event, not'load'
.
Breakdown of Incorrect Answers:
- “To listen for changes in the ready state of the XHR object” – Incorrect, as
readystatechange
is used for this. - “To listen for user input events related to the request” – Incorrect, as XHR is for network requests, not UI events.
- “To listen for errors that may occur during the request” – Incorrect, as
'error'
is used for errors.
Thus, the correct answer is: To listen for successful completion of the XHR request.