JavaScript MCQ (Multiple Choice Questions)

Here are 1000 MCQs on JavaScript (chapterwise).

1. What is JavaScript?
a) JavaScript is a scripting language used to make the website interactive
b) JavaScript is an assembly language used to make the website interactive
c) JavaScript is a compiled language used to make the website interactive
d) None of the mentioned
View Answer

Answer: a
Explanation: JavaScript is a scripting language used along with HTML and CSS to make the website interactive along. It is used both on the client-side and server-side.

2. Which of the following is correct about JavaScript?
a) JavaScript is an Object-Based language
b) JavaScript is Assembly-language
c) JavaScript is an Object-Oriented language
d) JavaScript is a High-level language
View Answer

Answer: a
Explanation: Although JavaScript is not an OOP (Object-Oriented Programming) language like Java or PHP, it is object based language. The standard threesome of polymorphism, encapsulation, and inheritance are the criteria for object orientation, and JavaScript fails to meet them.

3. Among the given statements, which statement defines closures in JavaScript?
a) JavaScript is a function that is enclosed with references to its inner function scope
b) JavaScript is a function that is enclosed with references to its lexical environment
c) JavaScript is a function that is enclosed with the object to its inner function scope
d) None of the mentioned
View Answer

Answer: b
Explanation: A closure is a function that is enclosed with references to its lexical environment. A closure allows an inner function to access the scope of an outside function. Closures are formed every time a function is created in JavaScript, during function creation time.

4. What will be the output of the following JavaScript code snippet?

<p id="demo"></p>
var txt1 = "Sanfoundry_";
var txt2 = "Javascriptmcq";
document.getElementById("demo").innerHTML = txt1 + txt2;

a) error
b) Sanfoundry_ Javascriptmcq
c) undefined
d) Sanfoundry_Javascriptmcq
View Answer

Answer: d
Explanation: The + operator in javascript acts as a concatenation operator when used with string. The new string does not have any space between the two added strings.
advertisement
advertisement

5. What will be the output of the following JavaScript code?

<p id="demo"></p>
<script>
var js = 10;
js *= 5;
document.getElementById("demo").innerHTML = js;
</script>

a) 10
b) 50
c) 5
d) Error
View Answer

Answer: b
Explanation: The *= operator in javascript is a shorthand expression for the multiplication of a particular number. It is a combination of two operators * and = .

6. Arrays in JavaScript are defined by which of the following statements?
a) It is an ordered list of values
b) It is an ordered list of objects
c) It is an ordered list of string
d) It is an ordered list of functions
View Answer

Answer: a
Explanation: An array in JavaScript is an ordered list of values, each value is referred to as an element, and it is identified by an index. An array can include values of many sorts and the length of an array dynamically sized.

7. What will be the output of the following JavaScript code?

// JavaScript Comparison Operators
function compare()
{
    let a=2;
    let b=2.0;
    if(a==b)
        return true;
    else
        return false;
}

a) false
b) true
c) compilation error
d) runtime error
View Answer

Answer: b
Explanation: The == in JS convert different types of operands to the same type before making the comparison whereas a strict comparison === results in true value if the operands are of the same type and the contents match.

8. What will be the output of the following JavaScript code snippet?

advertisement
// JavaScript Equalto Operators
function equalto()
{
    let num=10;
    if(num==="10")
        return true;
    else
        return false;
}

a) false
b) true
c) compilation error
d) runtime error
View Answer

Answer: a
Explanation: A === operator in JS is only true if the operands are of the same type and the contents match. Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions. In this case, we are comparing an integer and a string so it will be false.

9. Will the following JavaScript code work?

var js = (function(x) {return x*x;}(10));

a) Exception will be thrown
b) Memory leak
c) Error
d) Yes, perfectly
View Answer

Answer: d
Explanation: For functions expressed as expressions, the function name is optional in Javascript. Sometimes function expressions are defined and used right away.
advertisement

10. Which of the following is not javascript data types?
a) Null type
b) Undefined type
c) Number type
d) All of the mentioned
View Answer

Answer: d
Explanation: JavaScript is a dynamic, loosely typed language. Variables in JavaScript aren’t tied to any specific value type, and each variable can be assigned and reassigned to values of all the types.

11. Where is Client-side JavaScript code is embedded within HTML documents?
a) A URL that uses the special javascript:code
b) A URL that uses the special javascript:protocol
c) A URL that uses the special javascript:encoding
d) A URL that uses the special javascript:stack
View Answer

Answer: b
Explanation: The Client-side JavaScript code is embedded within HTML documents in four ways :

  1. Inline, between a pair of “script” tags
  2. From an external file specified by the src attribute of a “script” tag
  3. In an HTML event handler attribute, such as onclick or onmouseover
  4. In a URL that uses the special javascript: protocol.

12. What will be the output of the following JavaScript code snippet?

int a=1;
if(a!=null) // JavaScript not equal to Operators
    return 1;
else
    return 0;

a) 0
b) 1
c) compiler error
d) runtime error
View Answer

Answer: b
Explanation: != is not equal to the operator in Javascript. It gives a value of 1 if the two values which are compared are not equal and give 0 if the two values are equal.

13. Which of the following object is the main entry point to all client-side JavaScript features and APIs?
a) Position
b) Window
c) Standard
d) Location
View Answer

Answer: b
Explanation: All client-side JavaScript features and APIs are accessed through the Window object. It represents a web browser window or frame, and the identifier window can be used to refer to it.

14. What will be the output of the following JavaScript program?

function sanfoundry(javascript)
{
	return (javascript ?  “yes” :  “no”);
}
	bool ans=true;
console.log(sanfoundry(ans));

a) Compilation error
b) Runtime error
c) Yes
d) No
View Answer

Answer: c
Explanation: In javascript, “?” is called the ternary operator which is used for choosing one choice from the given two choices. It is used instead of if else statement and makes the code shorter.

15. What will be the output of the following JavaScript code?

// Javascript code snippet to compare the height
function height()
{	
    var  height = 123.56;
    var type = (height>=190) ? "tall" : "short";
    return type;
}

a) short
b) 123.56
c) tall
d) 190
View Answer

Answer: a
Explanation: The ternary operator in javascript is used as a comparison operator which works on three operands. The statement in the above code initializes type variable with the value short which is returned through the function.

16. Which of the following can be used to call a JavaScript Code Snippet?
a) Function/Method
b) Preprocessor
c) Triggering Event
d) RMI
View Answer

Answer: a
Explanation: A function call to the element on which JavaScript is to be run can be used to invoke JavaScript code. Other techniques include onclick, onload, and onsubmit, among others.

17. What will be the output of the following JavaScript function?

<p id="demo"></p>
<script>
function javascript() 
{
// javacript abs() method
    document.getElementById("demo").innerHTML = Math.abs(-7.25);
}
</script>

a) -7.25
b) 7.25
c) -7
d) 7
View Answer

Answer: b
Explanation: The javacript abs() method returns the absolute value of a number. The method is found in the math library of Javascript.

18. What will be the output of the following JavaScript code?

var a=5 , b=1
var obj = { a : 10 }
// with keyword in JavaScript
with(obj)
{
      alert(b)
}

a) 1
b) 10
c) 5
d) Error
View Answer

Answer: a
Explanation: Firstly the interpreter checks obj for property b. But it doesn’t find any property b so it takes the value from outside the object within the JavaScript code snippet.

19. Which of the following explains correctly what happens when a JavaScript program is developed on a Unix Machine?
a) will work perfectly well on a Windows Machine
b) will be displayed as JavaScript text on the browser
c) will throw errors and exceptions
d) must be restricted to a Unix Machine only
View Answer

Answer: a
Explanation: Because JS can run on a variety of operating systems, an application written for UNIX will run just as well on Windows.

20. Which is a more efficient JavaScript code snippet?
Code 1 :

// for loop in javascript
for(var num=10;num>=1;num--)
{
           document.writeln(num);
}

Code 2 :

var num=10;
while(num>=1)
{
       document.writeln(num);
       num++;
}

a) Code 1
b) Code 2
c) Both Code 1 and Code 2
d) Cannot Compare
View Answer

Answer: a
Explanation: Code 1 would be more efficient JS code. Infact second code will go into runtime error as the value of num will never reach less than or equal to one.

21. What will be the output of the following JavaScript code?

function printArray(a) 
{
     var len = a.length, i = 0;
     if (len == 0)
        console.log("Empty Array");
     else 
     {
// do-while loop in javascript
         do 
         {
             console.log(a[i]);
         } while (++i < len);
     }
}

a) Prints “Empty Array”
b) Prints 0 to the length of the array
c) Prints the numbers in the array in order
d) Prints the numbers in the array in the reverse order
View Answer

Answer: c
Explanation: The do/while statement creates a loop that executes a block of javascript code once, before checking if the condition is true, then it will repeat the loop as long as the condition is true. Hence the iterator traverses through the array and print them in normal order.

22. What happens in the following JavaScript code snippet?

var js = 0;
while (js < 10) 
{
     console.log(js);
     js++;
}

a) An exception is thrown
b) The values of js are logged or stored in a particular location or storage
c) The value of js from 0 to 9 is displayed in the console
d) An error is displayed
View Answer

Answer: c
Explanation: In JavaScript, Console.log is a predefined function that accepts the value as an argument. At the time of code execution, console.log prints this value in the argument to the console.

23. What will be the output of the following JavaScript code?

function range(int javascript)
{
	int a=5;
	for(int i=0;i<javascript;i++)
	{
		console.log(a);
	} 
}
range(3);

a) 2
b) 5
c) 555
d) error
View Answer

Answer: c
Explanation: for loop in Javascript first initializes the variable and later on checks for the condition expression and after that execute the line of statements. The value of iterator i increase until it reaches the value of length.

24. Which of the following scoping type does JavaScript use?
a) Sequential
b) Segmental
c) Lexical
d) Literal
View Answer

Answer: c
Explanation: JavaScript, like most current programming languages, employs lexical scoping. This means that functions are performed with the variable scope in effect when they were defined, rather than the variable scope in effect when they are invoked.

25. What is the basic difference between JavaScript and Java?
a) Functions are considered as fields
b) Functions are values, and there is no hard distinction between methods and fields
c) Variables are specific
d) There is no difference
View Answer

Answer: b
Explanation: Java is an object-oriented programming language, while JS is an object-oriented scripting language. The main difference between JavaScript and Java is that functions are values, while methods and fields are not clearly defined.

26. What will be the output of the following JavaScript code?

var quiz=[1,2,3];  
var js=[6,7,8];  
var result=quiz.concat(js);  
document.writeln(result);

a) 1, 2, 3, 6, 7, 8
b) 123
c) 1, 2, 3
d) Error
View Answer

Answer: a
Explanation: concat is a predefined function in the array library in Javascript. The concat function is used to combine the value of two arrays.
i.e.1, 2, 3, 6, 7, 8

27. Why JavaScript Engine is needed?
a) Both Compiling & Interpreting the JavaScript
b) Parsing the javascript
c) Interpreting the JavaScript
d) Compiling the JavaScript
View Answer

Answer: c
Explanation: For the most part, the JS Engine is used to interpret JavaScript. It’s used to parse javascript and run it on a web page.

28. What will be the function of the following JavaScript program?

var scope = "js scope";
function checkscope() 
{
    var scope = "javascript scope"; 
    function f() 
    { 
         return scope; 
    }
    return f;
}

a) Returns the value in scope
b) Returns value null
c) Shows an error message
d) Returns exception
View Answer

Answer: a
Explanation: The Lexical Environment is an object that is connected with every executing function, code block, and the script as a whole in JavaScript. The value in scope is returned by the code snippet above.

29. What will be the output of the following JavaScript code?

int a=0;
for(a;a<5;a++);
console.log(a);

a) 4
b) 5
c) 0
d) error
View Answer

Answer: b
Explanation: The value of a will increase until it equals 5, at which point the cursor will exit the loop. Because there are no statements in the for loop, the value of a will only increase. As a result, the result will be five.

30. Which of the following methods/operation does javascript use instead of == and !=?
a) JavaScript uses equalto()
b) JavaScript uses equals() and notequals() instead
c) JavaScript uses bitwise checking
d) JavaScript uses === and !== instead
View Answer

Answer: d
Explanation: The comma operator, bitwise operators, and the ++ and — operators are not included in the subset. It also forbids the usage of == and!= due to the type conversion they do, instead requiring the use of === and!==.

31. What will be the result or type of error if p is not defined in the following JavaScript code snippet?

console.log(p)

a) Value not found Error
b) Reference Error
c) Null
d) Zero
View Answer

Answer: b
Explanation: Console.log() is a javascript predefined function for printing data or messages to the console. A reference error will occur if the console.log argument is not defined.

32. What is the prototype represents in the following JavaScript code snippet?

function javascript() {};

a) Not valid
b) Prototype of a function
c) Function javascript
d) A custom constructor
View Answer

Answer: d
Explanation: All object instances have a constructor property that points to the constructor function that created them. A custom constructor is a constructor which requires no arguments and is created automatically by the compiler at the time of object creation if not created by the user.

33. Why event handlers is needed in JS?
a) Allows JavaScript code to alter the behaviour of windows
b) Adds innerHTML page to the code
c) Change the server location
d) Performs handling of exceptions and occurrences
View Answer

Answer: a
Explanation: JS code can change the behavior of windows, documents, and the elements that make up those documents via event handlers.

34. Which of the following is not a framework?
a) JavaScript .NET
b) JavaScript
c) Cocoa JS
d) jQuery
View Answer

Answer: b
Explanation: jQuery, which is used in web development, is one of the most popular frameworks. JavaScript is a scripting language, not a framework, in this case.

35. Which of the following is the property that is triggered in response to JS errors?
a) onclick
b) onerror
c) onmessage
d) onexception
View Answer

Answer: b
Explanation: The Window object’s onerror property acts as an event handler, and it is triggered when JavaScript problems occur. However, because it is called with various arguments, it isn’t a genuine event handler.

36. What will be the output of the following JavaScript code?

function compare()
{
    let sanfoundry=1;
    let javascript="1";
    if(sanfoundry.toString()===javascript)
        return true;
    else 
        return false;
}

a) runtime error
b) logical error
c) true
d) false
View Answer

Answer: c
Explanation: The toString() function can be used to convert a non-string (integer) to a string. Only if the operands are of the same type and the contents match, then only the comparison is true. In this case, both the operands to === operator are strings and have the same value “1”. So, the result is true.

37. What will be the firstname and surname of the following JavaScript program?

var book = {
              "main title": "JavaScript", 
              'sub-title': "The Definitive Guide", 
              "for": "all audiences", 
              author: { 
                         firstname: "David", 
                         surname: "Flanagan" 
                      }
           };

a) objects
b) property names
c) properties
d) property values
View Answer

Answer: b
Explanation: An item is contained within another object in the code sample above. The property names are firstname and surname. The value of that property is an object in and of itself.

38. Which of the following is not an error in JavaScript?
a) Missing of Bracket
b) Division by zero
c) Syntax error
d) Missing of semicolons
View Answer

Answer: b
Explanation: In JavaScript, division by zero does not result in an error; it just returns infinity or negative infinity. However, because zero divided by zero has no well-defined value, the result of this operation is the unusual not-a-number value, which is written as NaN.

39. Consider the following JavaScript statement containing regular expressions and check if the pattern matches.

var text = "testing: 1, 2, 3"; 
var pattern = /d+/g;

a) text.check(pattern)
b) pattern.test(text)
c) text==pattern
d) text.equals(pattern)
View Answer

Answer: b
Explanation: The pattern specified is applied to the text included in parenthesis. The test() method checks a string for a match. If a match is found, this method returns true; otherwise, it returns false.


Chapterwise Multiple Choice Questions on JavaScript

JavaScript MCQ - Multiple Choice Questions and Answers

Our 1000+ MCQs focus on all topics of the JavaScript subject, covering 100+ topics. This will help you to prepare for exams, contests, online tests, quizzes, viva-voce, interviews, and certifications. You can practice these MCQs chapter by chapter starting from the 1st chapter or you can jump to any chapter of your choice.
  1. JavaScript Lexical Structures
  2. JavaScript Classes and Modules
  3. Server Side and Client Side JavaScript
  4. Javascript Document Object Model and Event Handling
  5. Graphics and Rendering in JavaScript
  6. Performance Measures in Javascript
  7. Sockets in JavaScript
  8. JavaScript Parsing, Benchmarking and Logging
  9. JavaScript Invocation and Performance Navigation
  10. JavaScript Caching, JavaScript Debugging and Animation

1. JavaScript MCQ on Lexical Structures

The section contains JavaScript multiple choice questions and answers on variable types, lexical structures, loops and statements in java, arrays, JavaScript methods and JavaScript functions and the concept of serialization.

  • JavaScript Lexical Structure
  • JavaScript Types, Values and Variables
  • JavaScript Expressions and Operators
  • JavaScript Statements
  • JavaScript Loops
  • JavaScript Object Attributes and Serialization
  • JavaScript Array and Related Methods
  • Defining and Invoking JavaScript Functions
  • JavaScript Functions and Functional Programming
  • JavaScript Closures
  • 2. JavaScript MCQ on Classes and Modules

    The section contains questions and answers on javascript classes and modules, javascripts subsets and extentions and multiple catch clauses.

  • JavaScript Classes
  • Augmentation of JavaScript Classes
  • JavaScript Modules
  • JavaScript Pattern Matching and Regular Expressions
  • JavaScript Subsets
  • JavaScript Extentions
  • JavaScript Shorthand Functions and Multiple Catch Clauses
  • 3. Multiple Choice Questions on Server-Side and Client-Side JavaScript

    The section contains MCQ on javascript in web browsers, server and client sides javascript, embedding javascript in HTML and frameworks.

  • Server-Side JavaScript
  • Scripting Java with Rhino
  • Asynchronous I/O with Rhino
  • Client-Side JavaScript
  • Embedding JavaScript in HTML
  • JavaScript in Web Browsers – I
  • JavaScript in Web Browsers – II
  • JavaScript Client-Side Frameworks
  • 5. MCQ on Graphics and Rendering in JavaScript

    The section contains JavaScript questions with answers on browser parsing and rendering, graphics and scripted media.

  • Scripted Media
  • JavaScript Graphics
  • Browser Parsing and Rendering in JavaScript – 1
  • Browser Parsing and Rendering in JavaScript – 2
  • 6. Multiple Choice Questions on Performance Measures in JavaScript

    The section contains MCQ Questions on combination of javascript with firebug, yslow, webpagetest and minification.

  • JavaScript Performance Measures – 1
  • JavaScript Performance Measures – 2
  • JavaScript with FireBug
  • JavaScript with YSlow
  • JavaScript with WebPagetest
  • JavaScript Minification – 1
  • JavaScript Minification – 2
  • 7. Multiple Choice Questions on JavaScript Sockets

    The section contains JavaScript multiple choice questions and answers on web sockets and accessing webpagetest API.

  • Web Sockets in JavaScript
  • JavaScript History Management
  • Getting Started with R – 1
  • Getting Started with R – 2
  • Getting Started with R – 3
  • Enhanced JavaScript with R
  • Accessing the WebPagetest API
  • If you would like to learn "Javascript" thoroughly, you should attempt to work on the complete set of 1000+ MCQs - multiple choice questions and answers mentioned above. It will immensely help anyone trying to crack an exam or an interview.

    Wish you the best in your endeavor to learn and master Javascript!

    JavaScript Framework:

    JavaScript Online Test:

    Quick Links:

    advertisement
    Manish Bhojasia - Founder & CTO at Sanfoundry
    Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

    Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.