JavaScript MCQs
MCQ 1
Question: Which JavaScript method can be used to convert a string into an array of characters?
A. split()
B. join()
C. charAt()
D. substr()
Answer: A. split()
MCQ 2
Question: What is the output of the following code snippet?
let x = 5;
let y = 10;
let z = x++ + y--;
console.log(z);
Answer: B. 15
Explanation:
x++ increments x after the expression is evaluated, so it becomes 6.
y-- decrements y after the expression is evaluated, so it becomes 9. Therefore,
z = 6 + 9 = 15.
Hence , the output is 15.
JavaScript MCQs with getElementById
MCQ 1:
Question: What is the correct way to get an element with the ID "myDiv" using the getElementById() method?
A. document.getElementById("myDiv")
B. getElementById("myDiv")
C. document.get("myDiv")
D. document.find("myDiv")
Answer: A. document.getElementById("myDiv")
MCQ 2 :
Question: How can you change the inner HTML of an element with the ID "myParagraph" to "Hello, world!" using the getElementById() method?
A. document.getElementById("myParagraph").innerHTML = "Hello, world!";
B. document.innerHTML("myParagraph", "Hello, world!");
C. myParagraph.innerHTML = "Hello, world!";
D. document.write("Hello, world!");
Answer:
A. document.getElementById("myParagraph").innerHML = "Hello, world!";
MCQ 3 :
Given an array fruits = ["apple", "banana", "orange"], how can you create a new array containing only the fruits that start with the letter "a"?
A. fruits.filter(fruit => fruit.startsWith("a"))
B. fruits.map(fruit => fruit.startsWith("a"))
C. fruits.reduce((acc, fruit) => fruit.startsWith("a") ? [...acc, fruit] : acc, [])
D. fruits.forEach(fruit => fruit.startsWith("a") ? console.log(fruit) : null)
Answer: A. fruits.filter(fruit => fruit.startsWith("a"))
The filter() method is used to create a new array containing only the elements that pass a test (in this case, starting with the letter "a").
MCQ 4 :
What is the output of the following code?
const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map(num => num * num);
console.log(squaredNumbers);
A. [1, 4, 9, 16, 25]
B. [2, 4, 6, 8, 10]
C. [1, 2, 3, 4, 5]
D. An error will be thrown.
Answer: A. [1, 4, 9, 16, 25]
The map() method creates a new array by applying a function to each element of the original array. In this case, the function squares each number.
Comments
Post a Comment