50 JavaScript Multiple Choice Questions with Answers

Introduction to Javascript

Javascript is currently one of the most popular programming languages in the world, serving as the backbone of modern web development. It is a lightweight, cross-platform, and interpreted language that is employed for both front-end and back-end development purposes. Thanks to its vast standard library, Javascript offers developers a comprehensive selection of functions and methods that simplify the development process and make it far more accessible.

Integrating Javascript with HTML

There are two major methods for adding Javascript to HTML code:

  1. Internal Javascript: Javascript is added directly to the HTML code via the addition of JS code within the
    <script>

    tag, which can be placed either inside the

    <head>

    or the

    <body>

    tags based on the user's requirements.

  2. External Javascript: In this case, Javascript code is stored within an external file (e.g. "file_name.js"), which is then linked to the HTML file using the
    <script>

    tag.

Features of Javascript

Javascript is a highly flexible language with many useful features, including:

  • Lightweight, cross-platform, and interpreted language
  • Developed for DOM manipulation, enabling the creation of dynamic websites
  • Functions are objects that can be passed to other functions as parameters
  • Handles date and time manipulation
  • Performs form validation
  • No compiler is required

Javascript Multiple Choice Questions

Identifying Javascript as an Object-Oriented Language

 
// This code snippet demonstrates a Javascript object
let person = {
  name: "John Doe",
  age: 30,
  occupation: "Web Developer",
  greet: function() {
    console.log("Hello, my name is " + this.name + ". Nice to meet you!");
  }
};

// Calling the greet() method of the person object
person.greet();

Based on the above code snippet, it can be concluded that Javascript is an Object-Oriented language because it allows the creation of objects with properties and methods that can be accessed and manipulated.

JavaScript Variables

In JavaScript, the keywords `var` and `let` are used to declare variables.

- `var` keyword was used in older versions of JavaScript to declare variables. It is still used in some cases, but the newer keyword `let` is preferred.

- `let` keyword was introduced in ECMAScript 6 (ES6) and is now commonly used to declare variables.

Therefore, the correct answer is option C, "Both A and B".

Identifying HTML elements with JavaScript

JavaScript provides various methods to access HTML elements. Two commonly used methods are: getElementById(): This method returns an element with the specified ID from the HTML document. getElementsByClassName(): This method returns a collection of elements with the specified class name from the HTML document. Therefore, the correct answer is option C: Both A and B.

Handling Empty Statements in JavaScript

In JavaScript, empty statements do not have any effect on program execution. When the JavaScript interpreter encounters an empty statement, it simply ignores it and moves on to the next statement. Therefore, the correct answer to the given question is:

Option 2: Ignores the statements

It is important to note that empty statements are not recommended in your code and should be avoided to improve code readability and maintainability.

Ways to display data using JavaScript

In JavaScript, there are numerous ways to display data. Some methods include:

document.write();
console.log();
window.alert();

All of the above-mentioned methods can be used to display data in some form using JavaScript.

Declaring Constants in JavaScript

In JavaScript, a datatype can be declared as a constant type by using the "const" keyword. This tells the compiler that the value of the variable cannot be changed later in the program.

Example:

const PI = 3.14159; console.log(PI);

The above code declares "PI" as a constant and assigns it the value of 3.14159. As it is declared as a constant, the value of PI cannot be changed in the program.

In contrast, if we were to use the "var" or "let" keywords to declare a variable, its value could be changed later in the program.

Therefore, if you want to declare a variable in JavaScript that cannot have its value changed later, always use the "const" keyword to declare it as a constant type.H3. Understanding Type Conversion in JavaScript

Code:

javascript
let num1 = 5;
let str1 = "9";
let result = num1 + str1;
document.write(result);

Output:


59

Explanation: Since we are concatenating a string with a number using the `+` operator, JavaScript automatically converts the number into a string and concatenates the strings instead of adding the numbers. Therefore, the output of this code is "59", which is the result of concatenating the string "9" with the string version of the number 5, which is "5".

Understanding JavaScript's Substring Function


var str = "IQCode";
var res = str.substring(2, 4);
document.write(res);

The output of this code will be "al".

Explanation:

The substring() method extracts the characters from a string, between two specified indices, and returns the new sub-string. In this case, we've assigned a string "IQCode" to a variable 'str' and used the substring() method to take the characters from index 2 to 4 (excluding index 4), which are "C" and "o". So, the output will be "al".Code:

javascript
var x = 12;
var y = 8;
var res = eval("x + y");
document.write(res); 

Output:

20

Explanation:

The `eval()` function takes the string argument `"x + y"`, evaluates it as a JavaScript expression, and returns the result `20` by adding the values assigned to `x` and `y`. The output is then displayed on the document using `document.write()`.

Comparison in Switch Statement

In a switch statement, the comparison is done by both the datatype and value of the expression using the '===' operator. This means that the expression's datatype and value are compared with the provided labels. Therefore, the correct answer is:

Both the datatype and the result of the expression are compared.

Using the 'in' Keyword in JavaScript

In JavaScript, the 'in' keyword is used to check the validity of a given property. It is used to test whether a property exists in an object or an array. Here is an example of how to use it:

const myObject = {name: 'John', age: 30, city: 'New York'};
if ('name' in myObject) {
  console.log('Name property exists in myObject');
}

In this example, we have an object called 'myObject' with three properties: name, age, and city. We are using the 'in' keyword to check whether the 'name' property exists in 'myObject'. If it does, we will see the message 'Name property exists in myObject' in the console.

Remember, the 'in' keyword is case-sensitive and only checks for the existence of properties, not the value of the property itself.

Explanation:

The

<noscript>

tag is used in HTML to provide an alternate content for users who have disabled JavaScript or for browsers that do not support JavaScript. The content inside the

<noscript>

tag will be displayed when the JavaScript in the web page cannot be executed or is disabled. Therefore, option A is correct and option B and C are incorrect.

Option D is incorrect because although the content is displayed for non-JavaScript browsers, it is not the use of the

<noscript>

tag.

Understanding setTimeout in JavaScript

(function(){
setTimeout(()=> console.log(1),2000);
console.log(2);
setTimeout(()=> console.log(3),0);
console.log(4);
})();


The correct answer is: 2 4 3 1


When the function is executed, the following events occur:

  • The first setTimeout is called with a delay of 2000ms, so it won't be executed immediately.
  • The console logs 2 on the next line.
  • The second setTimeout is also called with a delay of 0ms, but since JS executes setTimeout with the Web API, it is added to the Web API queue.
  • The console logs 4 and the function execution ends.
  • The 0ms setTimeout is now called from the Web API queue and it logs 3.
  • Lastly, the 2000ms setTimeout is executed and it logs 1.

Understanding closures in JavaScript

The output of the code snippet will be 21.

Explanation:

The outer function takes an argument `a` as input and immediately returns an anonymous inner function that is being called immediately with `()` at the end.

javascript
(function(a){
    return (function(){
       console.log(a); // logs 21
       a = 6; 
    })(); // immediately invoked
})(21);

The console logs the value of `a`, which is `21`, so the output will be 21. Even though a is being reassigned to `6` in the inner function, it does not affect the value of `a` in the outer function.

Hence, the correct option is:

Option c: 21As the code snippet was incomplete, it is not possible to determine the output of the code. Please provide the complete code to assist you better.Code:

javascript
function displaySquareRoot() {
  document.getElementById("example").innerHTML = Math.sqrt(81);
}

displaySquareRoot(); // Output: 9

The output of the code snippet will be **9**.

Explanation: The `Math.sqrt()` function takes a number as an argument and returns the square root of that number. In this case, the argument passed is 81. Therefore, the square root of 81 is calculated and displayed using the `innerHTML` property, and the value displayed is 9.

Determining the typeof a NULL value with the unary operator in JavaScript

The typeof of a NULL value with the unary operator in JavaScript will always return "object".I'm sorry, the code snippet seems to be incomplete. Could you please provide the rest of the code?

Explanation of the JavaScript "debugger" statement

The "debugger" statement in JavaScript is used to set breakpoints in the code, which will pause the execution of code at the specified point and launch the debugger window. This allows for live inspection of variables and code execution at that point, making it a useful tool for debugging errors in the code. Therefore, option 2 is the correct answer. Option 1 and 3 are incorrect because the debugger statement does not debug all errors in the program at runtime nor does it debug errors in the current statement only. Option 4 is incorrect because only option 2 is correct.Code:

javascript
//Initializing variables with Math.max() and Math.min()

const maxVal = Math.max();
const minVal = Math.min();

//Printing values of maxVal and minVal

console.log(maxVal);
console.log(minVal);

Output:


-Infinity

Infinity

The code creates two variables `maxVal` and `minVal`. The `Math.max()` method returns the largest value in a given set of numbers, and when it is used without any parameters, it returns `-Infinity` as the default value. Similarly, the `Math.min()` method returns the smallest value in a given set of numbers, and when it is used without any parameters, it returns `Infinity` as the default value.

Therefore, when we run the code, the output shows that `maxVal` is `-Infinity` and `minVal` is `Infinity`.Code:

javascript
var a = Math.max(); 
var b = Math.min();
console.log(a);
console.log(b);

Output:


-Infinity
Infinity

The output of the given code will be `-Infinity` for variable `a` and `Infinity` for variable `b`.The output of the code snippet will be 5.

This is because in JavaScript, `true` is considered as the number `1` when used in any arithmetic expression. The expression `true + true + true * 3` evaluates as `1 + 1 + 3*1`, which equals to `5`.

The `print` function is not a valid JavaScript function. Instead, you can use the `console.log()` method to output values to the console.The output of the code snippet is `false`.H3 Output of typeof(NaN)

Code:

javascript
console.log(typeof(NaN)); // logs "number"

P: The output of the code snippet will be "number". In JavaScript, NaN (Not a Number) is of type "number", despite its name.

Explanation of the 'toLocaleString()' method in JavaScript

The 'toLocaleString()' method is a built-in method in JavaScript that is used to return a localized string representation of an object. This method is often used when displaying data to end-users in a format that meets their local language and cultural norms.

For example, if you have a date object that you want to display to the user, you can use the 'toLocaleString()' method to format the date in a way that follows the user's local time and date conventions.

Overall, the 'toLocaleString()' method is a powerful tool that can be used to ensure that your JavaScript applications are accessible and usable for users around the world.

Understanding Object Serialization

Object Serialization refers to the process of translating an object or data structure into a format that can easily be transferred over a network or stored. This process allows for easy transmission of data between different systems and platforms.

Serialization is typically used in scenarios where objects or data structures need to be transferred from one platform to another. This could be because the data needs to be stored for later use or because it needs to be transmitted over a network to a different computer system.

During the serialization process, the object or data structure is encoded into a suitable format, such as JSON or XML, which can be easily transmitted over a network or stored. The receiving system can then decode the data back into its original format to use it for further processing.

Overall, object serialization is a crucial aspect of modern networked applications, allowing for seamless data transfer and platform independence.

Serializing Objects in JavaScript

In JavaScript, the function used to serialize an object into a JSON string is

JSON.stringify()

.

For example:

javascript
const obj = { name: "John", age: 30 };
const jsonStr = JSON.stringify(obj); // {"name":"John","age":30}

Understanding the 3 Basic Object Attributes in JavaScript

JavaScript objects have three main attributes, which are:

  1. Class
  2. Prototype
  3. Extensible Flag

The class refers to the type of object that's being created. Prototypes are essentially blueprints that define the properties and methods of an object. The extensible flag determines if new properties can be added to an object.

Therefore, option 2 "Class, prototype, object's extensible flag" is the correct answer.

Code:

javascript
let sum = 0;
const array = [1, 2, 3];

// iterate over array elements and pass each element to getSum function
array.forEach(getSum);

// print the sum
console.log(sum);

// function to get the sum of all the elements in the array
function getSum(number) {
  sum += number;
}

The output of the code above will be:


6

This is because the `getSum` function is called for each element in the `array`, and the `sum` variable is incremented by the value of the current element on each iteration. After all elements have been processed, the `sum` variable contains the total sum of all elements in the array, which is equal to 6. Finally, the `sum` variable is printed to the console using the `console.log` statement.

Output of Javascript Code

[3, 4]

Explanation:
The given code creates an array a of numbers from 1 to 5 and then print the slice of elements from index 2 to 4 (exclusive) of array a. Therefore, the output will be [3, 4].

Output of parseInt()

Code:


console.log(parseInt("123Hello"));
console.log(parseInt("Hello123")); 

The output of the above code will be:


123
NaN

Explanation: The parseInt() function parses a string argument and returns an integer. If the first character of the string cannot be converted into a number, then it returns NaN (Not a Number). In the first case, the string "123Hello" starts with a number, so the parseInt() method converts the numeric part "123" to a number and returns it. In the second case, the string "Hello123" does not start with a number, so the parseInt() method returns NaN.

Identifying Closures in Javascript

In Javascript, closures are created every time a function is created. The following items are closures in Javascript:

- Functions

This is because functions have a scope chain that is associated with them.

Therefore, the correct answer is: All of the above.

Note: While objects and variables can be stored as properties of closures, they are not closures themselves.

Identifying Javascript Frameworks

Node

,

Vue

, and

React

are all Javascript frameworks.

However,

Cassandra

is not a Javascript framework. It is actually a NoSQL database management system.

Therefore, the correct answer is

Cassandra

.As the code snippet is incomplete, it is not possible to determine the output. The variable 'a' is assigned the string "hello", but there is no further information provided about what should happen in the loop. Please provide the complete code for a full answer.

Declaring Asynchronous Functions in JavaScript

To declare an asynchronous function in JavaScript, we use the 'async' keyword. The code block that follows the 'async' keyword will run asynchronously. This means it will not block the execution of subsequent code.


async function asyncFunction() {
  // asynchronous code here
}

The 'await' keyword is then used when calling asynchronous functions inside of an async function to wait for the asynchronous code to finish executing before moving on to the next line of code.


async function asyncFunction() {
  const result = await asyncOperation();
  console.log(result);
}

The 'setTimeout' function is used to delay the execution of a function by a specified amount of time, and is not directly related to asynchronous functions.

Stopping an Interval Timer in Javascript

In Javascript, you can stop an interval timer by using the clearInterval() method. This method clears the timer set by the setInterval() method.

Example:


// Start the interval timer
var timer = setInterval(myFunction, 1000);

// Stop the interval timer after 5 seconds
setTimeout(function() {
  clearInterval(timer);
}, 5000);

In the above example, the `setInterval()` method runs `myFunction()` every 1 second and returns a timer pointer that is stored in the variable `timer`. The `setTimeout()` method is used to stop the interval timer after 5 seconds by passing in a function that calls `clearInterval(timer)`.

Using this method, you can effectively stop an interval timer in Javascript.The output of the code snippet will be:

11 NaN [object Object]

The first element in the set is 5, which is added to 6 in the loop, resulting in 11. The second element is a string 'Hello', which is concatenated with the number 6 resulting in 'Hello6'. Adding a string with a number in JavaScript results in a string concatenation. The third element is an object which cannot be added with a number, resulting in NaN. When this object is printed in the console, it is stringified and results in '[object Object]'.

Comparison of Objects in JavaScript

In JavaScript, when we use the strict equality operator (===) to check the equality of two objects, their references are compared. This is because objects are passed by reference in JavaScript.

If we want to compare the contents of two objects, we need to manually compare each key-value pair of the objects. We can use a loop to iterate over the keys of both objects, and then compare the values of the corresponding keys.

It is important to note that comparing objects can be computationally expensive, especially if the objects have a large number of properties. Therefore, we should always try to avoid deep object comparisons unless they are absolutely necessary.

Explanation of the Spread Operator in JavaScript

The spread operator in JavaScript (written as three dots: `...`) is used to spread or expand an iterable (such as an array, object, or string) into individual elements. This allows you to easily combine multiple arrays or objects into a new array, or pass multiple arguments to a function.

For example, you can use the spread operator to merge two arrays:

javascript
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const mergedArray = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]

Or to add a new item to an existing array:

javascript
const oldArray = ['a', 'b', 'c'];
const newArray = [...oldArray, 'd']; // ['a', 'b', 'c', 'd']

The spread operator is also useful for passing multiple arguments to a function:

javascript
function sum(a, b, c) {
  return a + b + c;
}

const nums = [1, 2, 3];
const result = sum(...nums); // 6

In this example, we use the spread operator to expand the `nums` array into individual arguments for the `sum` function.

So, to answer the question, the ... operator is used to spread iterables to individual elements in JavaScript and is also called the spread operator.The output of the code snippet will be "Undefined Undefined Undefined" since the function is expecting an object with properties a, b, and c but is instead being passed three separate arguments of type number. This will result in all three properties being initialized with the default value of undefined.The given code seems to be incomplete as the while loop is not closed and there is no further code after it. Therefore, it will throw a syntax error.

To fix the syntax error, we can add the closing curly bracket '}' for the while loop and add code after it.

Assuming that the code after it returns the output of the search, the corrected code snippet is shown below:

javascript
let a = [1, 2, 3, 4, 5, 6];
var left = 0, right = 5;
var found = false;
var target = 5;
while (left <= right) { // corrected while loop
  var mid = parseInt((left + right) / 2);
  if (a[mid] == target) {
    found = true;
    break;
  } else if (a[mid] < target) {
    left = mid + 1;
  } else {
    right = mid - 1;
  }
}
console.log(found); // assuming this line outputs the result of the search

Output:


true

The code snippet performs binary search to find the target element in the given array. The while loop condition checks if `left` is less than or equal to `right`, and searches the middle element `mid` of the array `a`. If the middle element is equal to `target`, it sets `found` to true and exits the loop. Otherwise, it adjusts the left and right indexes based on the relative position of `target` with respect to `mid`. Finally, it outputs the result of the search using the `console.log()` statement outside the loop.The given code snippet is incomplete and will result in a syntax error if executed. However, let's assume that the code is completed as follows:


let s = "00000001111111";
let l = 0, r = s.length - 1, ans = -1;

while (l <= r) {
  let mid = Math.floor((l + r) / 2);
  
  if (s.charAt(mid) == '1') {
    ans = mid;
    l = mid + 1;
  } else {
    r = mid - 1;
  }
}

if (ans == -1) {
  console.log("No 1s found in the string.");
} else {
  console.log("Last index of 1 in the string: " + ans);
}

The code above is using binary search to find the last index of the character '1' in the string `s`. The output of the code will be:


Last index of 1 in the string: 12

This is because the string `s` has 1s starting from the 7th index, and the last 1 in the string is at the 12th index.I'm sorry, but the code snippet you provided is incomplete. It ends with "while(l ", but there is no closing statement or bracket. Please provide the complete code so I can help you with it.Code:

javascript
const obj1 = {name: "Hello", age: 16};
const obj2 = {name: "Hello", age: 16};
console.log(obj1 === obj2);

Output:


false

Comparing Objects with Strict Equality Operator

The given code snippet creates two separate objects, `obj1` and `obj2`, with the same property values but two different reference addresses in memory. The `===` operator checks for strict equality of both operands and compares their references instead of their values. Therefore, the condition `obj1 === obj2` evaluates to `false`.

Understanding Javascript Function Objects

The given code defines a function named `dog` which prints out a statement. The line `dog.sound = "Bark"` assigns a property named `sound` to the function object `dog`. This is possible in JavaScript because functions are treated as objects and can have properties just like any other object.

However, running this code does not produce any output because the function `dog` is not called or executed. If we were to call the `dog` function like so: `dog()`, it would print out the statement "I am a dog." as defined in the function body.

Therefore, the correct answer is: Nothing happens.

Writing Comments in JavaScript

In JavaScript, there are two ways to write comments:

1. Using double forward slashes (//) for single-line comments.

Example:


// This is a single-line comment

2. Using forward slash and asterisk (/* */) for multi-line comments.

Example:


/* 
This is a 
multi-line comment 
*/

It's important to write comments in code to explain what the code is doing, especially if other people will be reading or working with your code.

Identification of Javascript object without a prototype

In Javascript, the base object doesn't have a prototype. Therefore, option A "Base Object" is the correct answer.


// Example code:

let myObject = {}; 

// The above line of code is equivalent to:
// let myObject = new Object();

let hasPrototype = Object.getPrototypeOf(myObject);
console.log(hasPrototype); // Output: {}
// This means that the object prototype of 'myObject' is Object.prototype which is the base object.

The output of the code snippet will be "Object" because the spread syntax (...) used in the function declaration collects all the arguments into an array named "args". In JavaScript, the typeof an array is an object, hence the output is "Object".The output of the code snippet will be:

{first: 50, second: 30}

This is because the object `obj1` has duplicate keys (`first`), and when an object is declared with duplicate keys, the value of the key will be replaced by the last value of that key used in the declaration. In this case, the value of `first` is first set to `20`, but then it is later overridden by a value of `50`. So, `first` will have a value of `50` in the final object, and `second` will keep its original value of `30`.

Identifying Non-Server-Side JavaScript Objects

Date

,

Function

, and

FileUpload

are not server-side JavaScript objects.

Therefore, the correct answer is All of the above, as all the options constitute non-server-side JavaScript Objects.

Technical Interview Guides

Here are guides for technical interviews, categorized from introductory to advanced levels.

View All

Best MCQ

As part of their written examination, numerous tech companies necessitate candidates to complete multiple-choice questions (MCQs) assessing their technical aptitude.

View MCQ's
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.