Multiple Choice Question for Grand JS Quiz



(Chap # 81 - Browser Control – Testing for Popup Blockers)

(1) Which method is commonly used to test for popup blockers in JavaScript?

A) window.open()
B) document.createElement()
C) window.alert()
D) document.getElementById()

Answer: A) window.open()

Explanation: Popup blockers usually prevent windows opened using window.open(). A test is performed by trying to open a new window and checking if it was successful.



(2) What is the expected result if a popup is blocked?

A) The window.open() function returns a window object.
B) The window.open() function returns null or undefined.
C) The window will open, but it will be invisible.
D) The browser will display an error message.

Answer: B) The window.open() function returns null or undefined.

Explanation: If a popup is blocked, window.open() returns null or undefined, indicating that the popup was blocked.



(3) How can you handle popup blocker detection in JavaScript?

A) By checking if window.open() returns null or undefined.
B) By using document.getElementById().
C) By adding a window.onresize event.
D) By checking the document.readyState property.

Answer: A) By checking if window.open() returns null or undefined.

Explanation: The result of window.open() can be used to detect whether a popup was blocked. If it returns null, the popup was blocked.



(4) Which browser feature commonly blocks popups?

A) Browser cookies
B) Browser history
C) Popup blockers
D) User authentication

Answer: C) Popup blockers

Explanation: Popup blockers are designed to block windows that are opened by scripts in response to user actions, such as clicking on links or buttons.



(5) What can cause a popup to be blocked?

A) The popup is initiated by a user action.
B) The popup is initiated by a JavaScript function on page load.
C) The popup appears in a new tab.
D) The popup contains an advertisement.

Answer: B) The popup is initiated by a JavaScript function on page load.

Explanation: Many browsers block popups that are triggered automatically (e.g., during page load) to prevent intrusive advertisements.



(6) How can you test whether a popup is blocked?

A) By checking the size of the popup window.
B) By checking the URL of the popup.
C) By checking if the window.open() function returns null.
D) By checking the page's title.

Answer: C) By checking if the window.open() function returns null.

Explanation: If window.open() returns null, it indicates that the popup has been blocked.



(7) Which of the following will prevent a popup from being blocked?

A) Initiating the popup in response to a user action like a click.
B) Using the setTimeout() function.
C) Opening the popup when the page loads.
D) Creating multiple popups simultaneously.

Answer: A) Initiating the popup in response to a user action like a click.

Explanation: Browsers typically allow popups that are triggered by direct user interaction (e.g., clicking a button or link).



(8) What should you do if a popup is blocked in your application?

A) Automatically attempt to open another popup.
B) Notify the user that their browser is blocking popups.
C) Disable all popup functionality.
D) Try to open the popup again after a delay.

Answer: B) Notify the user that their browser is blocking popups.

Explanation: It's a good practice to inform users if their browser is blocking popups and suggest that they allow popups for the site.



(9) Which of the following can help prevent popups from being blocked?

A) Opening the popup window in response to a background process.
B) Using inline JavaScript for popup functions.
C) Triggering popups with user-initiated actions like clicks or key presses.
D) Using a single popup for all interactions.

Answer: C) Triggering popups with user-initiated actions like clicks or key presses.

Explanation: Browsers allow popups that are initiated by direct user actions, reducing the likelihood of them being blocked.



(10) What happens when a popup is blocked in a browser?

A) A message appears informing the user of the block.
B) The popup window is hidden but still functional.
C) The page redirects to another URL.
D) The script continues to execute without any issues.

Answer: A) A message appears informing the user of the block.

Explanation: Most browsers display a message or icon in the address bar indicating that a popup was blocked.





(Chap # 82 - Form Validation – Text Fields)

(1) What is the primary purpose of form validation in JavaScript?

A) To improve the appearance of the form.
B) To ensure that the form is submitted successfully.
C) To check if all form fields are filled with the correct type of data.
D) To prevent users from submitting the form without filling all fields.

Answer: C) To check if all form fields are filled with the correct type of data.

Explanation: Form validation checks the correctness and completeness of user input before the form is submitted to the server.



(2) Which JavaScript method is commonly used for validating text fields in a form?

A) getElementById()
B) addEventListener()
C) test()
D) checkValidity()

Answer: D) checkValidity()

Explanation: The checkValidity() method checks if the text field satisfies the specified constraints and is valid according to HTML5 validation rules.



(3) What happens if the validation of a text field fails in a form?

A) The form is submitted.
B) The browser shows a message and prevents form submission.
C) The form is automatically reset.
D) The field turns green.

Answer: B) The browser shows a message and prevents form submission.

Explanation: If validation fails, the browser typically displays a message and prevents the form from being submitted until the user corrects the error.



(4) How can you make a text field required in HTML5 form validation?

A) By using the required attribute.
B) By using JavaScript to check if the field is empty.
C) By using the validate() function.
D) By setting the type attribute to text.

Answer: A) By using the required attribute.

Explanation: The required attribute ensures that the user must fill in the text field before submitting the form.



(5) What is the default behavior if a required text field is left empty and the user tries to submit the form?

A) The form is submitted but with a warning.
B) The form submission is blocked, and the user is prompted to fill the field.
C) The form submission is blocked, and the field is highlighted.
D) The field is automatically filled with a default value.

Answer: B) The form submission is blocked, and the user is prompted to fill the field.

Explanation: If a required field is empty, the form cannot be submitted until the user fills it out. A prompt is shown to guide the user.



(6) Which event is typically used to trigger form validation?

A) onload
B) onsubmit
C) onfocus
D) onchange

Answer: B) onsubmit

Explanation: The onsubmit event is commonly used to trigger form validation when the user tries to submit the form.



(7) What JavaScript property can you use to get the current value of a text field?

A) value
B) innerText
C) textContent
D) input

Answer: A) value

Explanation: The value property retrieves the current value entered by the user in a text field.



(8) Which of the following can you validate in a text field?

A) Whether the field is empty.
B) Whether the field contains a valid email address.
C) Whether the field contains only numbers.
D) All of the above.

Answer: D) All of the above.

Explanation: You can validate various criteria like checking if the field is empty, if the value matches a pattern (e.g., email), or if it only contains numbers.



(9) How can you trigger custom validation messages in JavaScript?

A) By setting the message attribute.
B) By using the setCustomValidity() method.
C) By changing the innerHTML of the form.
D) By triggering the onvalidate event.

Answer: B) By using the setCustomValidity() method.

Explanation: The setCustomValidity() method is used to set a custom validation message if the value of a form field does not meet the criteria.



(10) Which HTML attribute can you use to specify the minimum and maximum length of a text field?

A) minlength and maxlength
B) minLength and maxLength
C) min_size and max_size
D) min_val and max_val

Answer: A) minlength and maxlength

Explanation: The minlength and maxlength attributes allow you to set the minimum and maximum length of a text field in HTML5.



(Chap # 83 - Form Validation – Drop-downs)

(1) What is a drop-down menu used for in HTML forms?

A) To allow the user to select a single option from a list.
B) To allow the user to input custom data.
C) To display multiple options at once.
D) To display only one option at a time.

Answer: A) To allow the user to select a single option from a list.

Explanation: A drop-down menu, created using the select element, allows the user to select one option from a list of options.



(2) Which attribute is used to specify the list of options in a drop-down menu in HTML?

A) option
B) select
C) options
D) optionvalue

Answer: A) option

Explanation: Each option in a drop-down menu is defined using the option element within the select element.



(3) How can you make a drop-down field required for form submission?

A) By setting the required attribute on the select element.
B) By setting the value attribute of the first option.
C) By using JavaScript validation.
D) By setting the option attribute to required.

Answer: A) By setting the required attribute on the select element.

Explanation: The required attribute ensures that the user selects an option before submitting the form.



(4) How do you set a default value in a drop-down menu?

A) By setting the selected attribute on one of the option elements.
B) By setting the value attribute to the default option.
C) By placing the default option at the top of the list.
D) By using JavaScript to select the option.

Answer: A) By setting the selected attribute on one of the option elements.

Explanation: The selected attribute makes an option the default choice in a drop-down menu.



(5) Which method is used in JavaScript to get the selected value of a drop-down menu?

A) getValue()
B) value()
C) getSelectedValue()
D) value

Answer: D) value

Explanation: The value property of the select element retrieves the selected value from the drop-down menu.



(6) How can you prevent the user from selecting multiple options in a drop-down menu?

A) By adding the multiple attribute to the select element.
B) By removing the multiple attribute from the select element.
C) By setting the disabled attribute to all but one option.
D) By using JavaScript to check the selected option.

Answer: B) By removing the multiple attribute from the select element.

Explanation: The multiple attribute allows multiple options to be selected; removing it ensures that only one option can be chosen.



(7) What is the best way to validate that a user has selected an option from a drop-down list?

A) By checking if the selected value is empty or the default value.
B) By setting the required attribute.
C) By using the onchange event.
D) All of the above.

Answer: D) All of the above.

Explanation: You can validate a drop-down list by checking if the selected value is empty, using the required attribute, or by handling the onchange event for real-time validation.



(8) What will happen if the user tries to submit a form with an unselected required drop-down field?

A) The form will be submitted with an empty value.
B) The browser will display a validation message, preventing the form from being submitted.
C) The field will be automatically filled with a default value.
D) The form will not be submitted, but no message will be displayed.

Answer: B) The browser will display a validation message, preventing the form from being submitted.

Explanation: If a drop-down menu is required and no option is selected, the form will not be submitted, and a message will prompt the user to select a value.



(9) Which of the following is the correct way to iterate through all options in a drop-down list using JavaScript?

A) for (var i = 0; i < select.options.length; i++) {}
B) for (var option of select.options) {}
C) for (var option in select.options) {}
D) Both A and B are correct.

Answer: D) Both A and B are correct.

Explanation: Both for loop structures allow you to iterate through the options collection of a select element.



(10) How can you change the selected option in a drop-down menu using JavaScript?

A) By setting the value property of the select element.
B) By using the selectedIndex property to specify the index of the option.
C) By using the setAttribute() method on the selected option element.
D) All of the above.

Answer: D) All of the above.

Explanation: You can change the selected option by setting the value or selectedIndex properties, or using setAttribute() on the option element.



(Chap # 84 - Firm validation - radio buttons)

(1) What is the primary use of radio buttons in a form?

A) To allow the user to select multiple options from a list.
B) To allow the user to select one option from a group of options.
C) To enter a numeric value.
D) To display multiple input fields.

Answer: B) To allow the user to select one option from a group of options.

Explanation: Radio buttons allow the user to choose one option from a group of predefined options. They are used when only one selection is allowed.



(2) How do you group radio buttons together in HTML?

A) By using the same name attribute.
B) By using the group attribute.
C) By placing them inside a fieldset element.
D) Both A and C are correct.

Answer: A) By using the same name attribute.

Explanation: To group radio buttons, they must all share the same name attribute. This ensures that only one option can be selected from the group.



(3) What will happen if multiple radio buttons within a group are selected at the same time?

A) Both options will be selected.
B) The first option will be selected.
C) Only one option can be selected.
D) None of the options will be selected.

Answer: C) Only one option can be selected.

Explanation: Radio buttons are mutually exclusive; selecting one will automatically deselect any other radio buttons in the same group.



(4) How can you make a radio button required in a form submission?

A) By adding the required attribute to the input element.
B) By using JavaScript to check if the radio button is selected.
C) By setting the checked attribute on one of the options.
D) Both A and B are correct.

Answer: D) Both A and B are correct.

Explanation: You can make a radio button required by using the required attribute in HTML, or by validating the selection using JavaScript.



(5) Which property is used to get the value of the selected radio button?

A) value
B) selected
C) checked
D) selectedIndex

Answer: C) checked

Explanation: The checked property is used to determine if a radio button is selected. You can check it in JavaScript to know which radio button is selected.



(6) How do you select a default radio button when the page loads?

A) By using the checked attribute on one of the radio buttons.
B) By using JavaScript to set the checked property.
C) By setting the value attribute to the default option.
D) Both A and B are correct.

Answer: D) Both A and B are correct.

Explanation: To set a default radio button, you can either use the checked attribute in the HTML or set the checked property via JavaScript.



(7) Which method is used to check if a radio button is selected using JavaScript?

A) getChecked()
B) isSelected()
C) checked
D) getRadioButtonValue()

Answer: C) checked

Explanation: The checked property is used to check if a radio button is selected in JavaScript.



(8) What is the result of submitting a form with no radio buttons selected, when one of them is required?

A) The form will be submitted with an empty value.
B) The form will not be submitted, and the browser will display a validation message.
C) The default radio button will be selected automatically.
D) The form will be submitted with the value of the first radio button.

Answer: B) The form will not be submitted, and the browser will display a validation message.

Explanation: If a radio button is required and none is selected, the form will not be submitted, and the browser will prompt the user to select an option.



(9) What is the purpose of using the value attribute in radio buttons?

A) To give each radio button a label.
B) To specify the value sent to the server when the radio button is selected.
C) To make a radio button required.
D) To set the default radio button.

Answer: B) To specify the value sent to the server when the radio button is selected.

Explanation: The value attribute specifies the value that will be submitted to the server when the radio button is selected.



(10) Which HTML element is used to group radio buttons together?

A) select
B) fieldset
C) form
D) label

Answer: B) fieldset

Explanation: The fieldset element is used to group related elements, including radio buttons, within a form.



(Chap # 85 - Form validation - Zip codes)

(1) What is the purpose of validating ZIP codes in a form?

A) To ensure the user enters a valid numeric code.
B) To ensure the user enters a valid geographic location.
C) To ensure the user enters a code in the correct format.
D) To ensure the user enters a complete address.

Answer: C) To ensure the user enters a code in the correct format.

Explanation: ZIP code validation ensures the user enters a valid code that follows the correct format, such as five digits or a nine-digit format (ZIP+4).



(2) What is the most common format for a ZIP code in the United States?

A) 5 digits
B) 9 digits
C) 5 digits, a hyphen, and 4 digits (ZIP+4)
D) Any number of digits

Answer: C) 5 digits, a hyphen, and 4 digits (ZIP+4)

Explanation: In the United States, the ZIP+4 format is commonly used, which includes 5 digits followed by a hyphen and 4 additional digits.



(3) Which JavaScript method is commonly used to validate a ZIP code format?

A) test()
B) match()
C) validate()
D) isZipValid()

Answer: A) test()

Explanation: The test() method is commonly used with regular expressions to validate the format of the ZIP code.



(4) How would you check if a ZIP code input field contains exactly 5 digits using JavaScript?

A) Use input.length === 5
B) Use input.match(/^\d{5}$/)
C) Use input.isNumber()
D) Use input.test(/^\d{5}$/)

Answer: B) Use input.match(/^\d{5}$/)

Explanation: The regular expression /^\d{5}$/ ensures the input matches exactly five digits, which is the standard format for ZIP codes.



(5) What would be the result of applying the regular expression /^\d{5}-\d{4}$/ to a ZIP code?

A) It will match a 5-digit ZIP code.
B) It will match a 9-digit ZIP code with a hyphen.
C) It will only match ZIP codes with letters.
D) It will not match any ZIP code.

Answer: B) It will match a 9-digit ZIP code with a hyphen.

Explanation: The regular expression /^\d{5}-\d{4}$/ matches a ZIP code in the ZIP+4 format (5 digits followed by a hyphen and 4 more digits).



(6) What is a valid regular expression to check if a ZIP code contains only digits?

A) /^[0-9]{5}$/
B) /^\d{5}$/
C) /^\d{9}$/
D) Both A and B are correct.

Answer: D) Both A and B are correct.

Explanation: Both /^[0-9]{5}$/ and /^\d{5}$/ are valid regular expressions for matching a 5-digit ZIP code.



(7) What is a common error that occurs when a user enters an invalid ZIP code in a form?

A) The form will automatically correct the ZIP code.
B) The browser will submit the form with an invalid ZIP code.
C) The form will display an error message and not submit.
D) The user will be able to submit the form but without the ZIP code.

Answer: C) The form will display an error message and not submit.

Explanation: When a ZIP code is invalid, the browser will typically display an error message and prevent the form from being submitted until the error is corrected.



(8) Which HTML element can be used to visually indicate an invalid ZIP code entry in a form?

A) input
B) span
C) div
D) form

Answer: B) span

Explanation: A span element is often used to display error messages or visual indicators when a form input, like a ZIP code, is invalid.



(9) How can you enhance ZIP code validation in a form for international users?

A) By using a specific regular expression for each country.
B) By requiring the user to enter a postal code in a specific format.
C) By using a drop-down list to select a country before entering the ZIP code.
D) All of the above.

Answer: D) All of the above.

Explanation: To enhance ZIP code validation for international users, you could use country-specific regular expressions, provide a specific format, or allow users to select their country before entering the ZIP code.



(10) What JavaScript function can be used to validate a ZIP code entered in a form?

A) isZipCodeValid()
B) validateZipCode()
C) checkZipCode()
D) Any custom function that uses regular expressions.

Answer: D) Any custom function that uses regular expressions.

Explanation: You can create a custom function to validate a ZIP code using regular expressions that check the format (e.g., 5 digits or ZIP+4 format).



(Chap # 86 - Form validation - Email)

(1) What is the main purpose of email validation in a form?

A) To ensure the user enters a valid email address.
B) To ensure the user enters a valid phone number.
C) To ensure the email address is unique.
D) To verify the user's identity.

Answer: A) To ensure the user enters a valid email address.

Explanation: The purpose of email validation is to make sure the entered email follows the correct format, ensuring the email address is valid for communication.



(2) Which of the following is a valid email format?

A) user@example.com
B) user@com
C) user@.com
D) userexample.com

Answer: A) user@example.com

Explanation: The valid email format consists of a username followed by "@" and a domain name, such as user@example.com.



(3) Which JavaScript method can be used to check if an email address follows a valid format?

A) test()
B) match()
C) isEmailValid()
D) validateEmail()

Answer: A) test()

Explanation: The test() method is often used with regular expressions to validate if the email format matches the expected pattern.



(4) What regular expression pattern is commonly used to validate an email format in JavaScript?

A) /^[a-zA-Z0-9]+@[a-zA-Z]+\.[a-zA-Z]{2,6}$/
B) /^[a-zA-Z0-9]+@[a-zA-Z]+\.[a-zA-Z]{3,}$/
C) /^[a-zA-Z0-9]+@[a-zA-Z]{3,5}\.[a-zA-Z]{2,4}$/
D) /^[a-zA-Z]+@[a-zA-Z]+\.[a-zA-Z]{2,}$/

Answer: A) /^[a-zA-Z0-9]+@[a-zA-Z]+\.[a-zA-Z]{2,6}$/

Explanation: This regular expression matches an email address with an alphanumeric username, followed by "@" and a domain name with a dot, and a 2-6 character long top-level domain.



(5) What is a common problem when validating emails with regular expressions?

A) False positives (matching invalid emails)
B) False negatives (failing to match valid emails)
C) Both A and B
D) None of the above

Answer: C) Both A and B

Explanation: Regular expressions for email validation can sometimes produce false positives (matching invalid emails) or false negatives (failing to match valid emails) due to the complexity of email formats.



(6) Which of the following will trigger an error in email validation?

A) user@domain.com
B) user@domain..com
C) user@domain
D) user@domain..co.uk

Answer: B) user@domain..com

Explanation: The email user@domain..com contains consecutive dots, which is not allowed in email addresses according to the standard format.



(7) Which HTML5 attribute can be used to validate an email input field in a form?

A) type="email"
B) type="text"
C) pattern="email"
D) required="true"

Answer: A) type="email"

Explanation: The type="email" attribute in HTML5 automatically validates if the input follows a proper email format.



(8) How can you check if an email address already exists in the database?

A) Use JavaScript validation.
B) Check the email with an API call to the server.
C) Use HTML5 validation.
D) Use local storage.

Answer: B) Check the email with an API call to the server.

Explanation: To check if an email address already exists, you need to make an API call to the server to query the database for the given email.



(9) Which of the following is NOT a valid email address?

A) user@domain.com
B) user@domain.co.uk
C) user@domain@com
D) user@domain.info

Answer: C) user@domain@com

Explanation: The email user@domain@com is invalid because it contains multiple "@" symbols, which is not allowed in an email address.



(10) What can be done if an email validation fails in a form?

A) The form is submitted with an empty email field.
B) An error message is displayed, and the form is not submitted.
C) The email is replaced with a default value.
D) The form is automatically corrected.

Answer: B) An error message is displayed, and the form is not submitted.

Explanation: When email validation fails, the form will typically display an error message and prevent submission until the user corrects the email format.



(Chap # 87 - Exceptions – Try and Catch )

(1) What is the purpose of the try block in JavaScript?

A) To handle errors
B) To perform normal operations
C) To define the type of error
D) To throw exceptions

Answer: A) To handle errors

Explanation: The try block is used to wrap code that may throw an error so that it can be caught and handled in the corresponding catch block.



(2) What happens when an error occurs inside a try block?

A) The program stops execution
B) The code after the error in the try block is ignored
C) The error is automatically corrected
D) The finally block is always executed

Answer: B) The code after the error in the try block is ignored

Explanation: If an error occurs inside the try block, the program skips the rest of the code inside the block and moves to the catch block.



(3) Which of the following is the correct syntax for using try and catch blocks in JavaScript?

A) try { code } catch { code }
B) try { code } catch(error) { code }
C) try { code } catch error { code }
D) try { code } catch(error) { code }

Answer: B) try { code } catch(error) { code }

Explanation: The correct syntax includes the catch(error) part, where error represents the error object that contains details about the error.



(4) What type of errors can be handled using the try...catch statement?

A) Syntax errors
B) Runtime errors
C) Logical errors
D) All of the above

Answer: B) Runtime errors

Explanation: The try...catch statement is used to handle runtime errors that occur during the execution of the code.



(5) What will happen if no catch block is provided for a try block?

A) The error is automatically handled
B) The program will crash
C) The error will be ignored
D) The error will propagate, and the program will stop execution

Answer: D) The error will propagate, and the program will stop execution

Explanation: If no catch block is provided, the error will propagate to the global scope, and the program will stop execution.



(6) Which block is always executed, regardless of whether an error occurs in the try block?

A) catch
B) finally
C) error
D) else

Answer: B) finally

Explanation: The finally block is executed after the try block, whether an error occurs or not. It is typically used for cleanup actions.



(7) What will happen if there is an error inside the catch block?

A) The program will crash immediately
B) The error will be logged to the console
C) The error will be handled by a nested try...catch
D) The finally block will be executed

Answer: C) The error will be handled by a nested try...catch

Explanation: If an error occurs in the catch block, you can use a nested try...catch block to handle the error properly.



(8) Which of the following is the correct way to throw an error manually in JavaScript?

A) throw "Error message";
B) raise "Error message";
C) catch "Error message";
D) error "Error message";

Answer: A) throw "Error message";

Explanation: The throw keyword is used to manually throw an error, followed by an error message or an object.



(9) What is the output of the following code?
try { throw "Error"; } catch (e) { console.log(e); }


A) Undefined
B) Error
C) Error message
D) Nothing

Answer: C) Error message

Explanation: The code throws an error with the message "Error," which is caught by the catch block and logged to the console.



(10) How can you create a custom error in JavaScript?

A) By using new Error("message")
B) By using throw Error("message")
C) By using catch new Error("message")
D) By using new Exception("message")

Answer: A) By using new Error("message")

Explanation: A custom error can be created using the new Error("message") syntax, which creates an error object with a specific message.



(Chap # 88 - Exceptions : Throw)

(1) What does the throw statement do in JavaScript?

A) It throws a value back into the function.
B) It stops the program execution.
C) It manually throws an error.
D) It rethrows an error that was caught.

Answer: C) It manually throws an error.

Explanation: The throw statement allows you to manually throw an exception, which can be caught by a try...catch block.



(2) Which type of values can be thrown using the throw statement?

A) Only string values
B) Only number values
C) Any type of value (objects, strings, numbers, etc.)
D) Only boolean values

Answer: C) Any type of value (objects, strings, numbers, etc.)

Explanation: The throw statement can throw any type of value, including strings, numbers, objects, or custom error objects.



(3) What will happen if you try to throw an error without using the throw keyword?

A) The error will be automatically handled.
B) It will result in a syntax error.
C) The error will be ignored.
D) The program will terminate immediately.

Answer: B) It will result in a syntax error.

Explanation: If you attempt to throw an error without the throw keyword, it will result in a syntax error because throw is required to manually throw exceptions.



(4) Which of the following is the correct syntax for throwing a custom error in JavaScript?

A) throw new Error("Custom Error");
B) throw "Custom Error";
C) throw Error("Custom Error");
D) throw "error";

Answer: A) throw new Error("Custom Error");

Explanation: To throw a custom error, use the throw keyword followed by the new Error() constructor with a message string.



(5) What is the purpose of throwing an error in JavaScript?

A) To stop the function execution
B) To manually trigger an exception that can be caught and handled
C) To create a log message
D) To break the loop execution

Answer: B) To manually trigger an exception that can be caught and handled

Explanation: Throwing an error manually allows you to create exceptions in your code, which can then be caught by a try...catch block for error handling.



(6) How can you throw an exception in JavaScript with a custom message?

A) throw("This is an error");
B) throw new Error("This is an error");
C) throw "This is an error";
D) throw new Exception("This is an error");

Answer: B) throw new Error("This is an error");

Explanation: You can throw a custom error message by using the new Error() constructor inside the throw statement.



(7) What will happen if a throw statement is encountered in a try block?

A) The program will continue executing normally
B) The catch block will be executed if the error is thrown
C) The finally block will not be executed
D) The program will throw a syntax error

Answer: B) The catch block will be executed if the error is thrown

Explanation: When an error is thrown inside the try block, it is caught by the catch block for error handling.



(8) Can the throw statement throw an error object?

A) No, only strings can be thrown.
B) Yes, the throw statement can throw error objects.
C) No, it throws a message only.
D) Yes, but only boolean values can be thrown as objects.

Answer: B) Yes, the throw statement can throw error objects.

Explanation: The throw statement can throw not just error messages, but also complete error objects, such as new Error() or custom error objects.



(9) What is the purpose of throwing custom errors in JavaScript?

A) To log data to the console
B) To make debugging easier
C) To prevent the application from crashing
D) To trigger built-in JavaScript errors

Answer: B) To make debugging easier

Explanation: Throwing custom errors helps developers identify specific issues in the code by providing meaningful error messages, improving debugging.



(10) Can the throw statement be used to handle multiple errors in a try...catch block?

A) Yes, it can handle multiple errors.
B) No, only one error can be handled at a time.
C) It only handles non-runtime errors.
D) The catch block cannot catch thrown errors.

Answer: A) Yes, it can handle multiple errors.

Explanation: Multiple errors can be thrown using the throw statement, and each error can be caught and handled in the catch block.



(Chap # 89 - Handling Events within JavaScript)

(1) What is the purpose of handling events in JavaScript?

A) To improve code performance
B) To respond to user actions like clicks, key presses, or mouse movements
C) To format the appearance of the page
D) To modify the layout of the page

Answer: B) To respond to user actions like clicks, key presses, or mouse movements

Explanation: Event handling in JavaScript allows developers to listen for specific events (e.g., click, hover, keypress) and execute corresponding functions when those events occur.



(2) Which of the following is the correct way to attach an event listener to an element?

A) element.addEventListener("click", functionName);
B) element.addListener("click", functionName);
C) element.on("click", functionName);
D) element.addEvent("click", functionName);

Answer: A) element.addEventListener("click", functionName);

Explanation: The correct method to attach an event listener is addEventListener(), which listens for specific events (e.g., click) and calls the provided function when the event occurs.



(3) Which event is triggered when a user clicks on an HTML element?

A) submit
B) click
C) keydown
D) hover

Answer: B) click

Explanation: The click event is triggered when a user clicks on an HTML element, such as a button or a link.



(4) How do you prevent the default action of an event in JavaScript?

A) event.preventDefault();
B) event.stopPropagation();
C) event.prevent();
D) event.stopDefault();

Answer: A) event.preventDefault();

Explanation: To prevent the default action of an event, you use event.preventDefault();. For example, preventing a form submission when the submit button is clicked.



(5) Which event is fired when the user moves the mouse over an element?

A) mousemove
B) mouseenter
C) mouseover
D) click

Answer: C) mouseover

Explanation: The mouseover event is fired when the mouse pointer moves over an element.



(6) How can you attach an event listener for multiple events on the same element?

A) Use multiple addEventListener calls
B) Use the on attribute for each event
C) Chain multiple events in a single addEventListener
D) JavaScript doesn't support multiple events on one element

Answer: A) Use multiple addEventListener calls

Explanation: You can use multiple addEventListener calls to attach different event listeners to the same element. Each event will trigger its corresponding callback function.



(7) What does the event.target property refer to?

A) The element that is listening for the event
B) The element that triggered the event
C) The element's parent
D) The event itself

Answer: B) The element that triggered the event

Explanation: The event.target property refers to the element that triggered the event. For example, in a click event, it is the element that was clicked.



(8) How can you stop an event from propagating to other elements?

A) event.stopPropagation();
B) event.stopDefault();
C) event.cancelPropagation();
D) event.preventDefault();

Answer: A) event.stopPropagation();

Explanation: To stop an event from propagating (bubbling) to other elements, you can use event.stopPropagation();.



(9) What is the purpose of using the return false statement inside an event handler?

A) To cancel the event's default behavior and stop propagation
B) To trigger a new event
C) To continue the event flow without any changes
D) To log the event data

Answer: A) To cancel the event's default behavior and stop propagation

Explanation: Returning false from an event handler is a shortcut to prevent the default behavior of the event and stop its propagation.



(10) Which of the following is a correct way to handle a click event on a button with an ID of "submitBtn"?

A) document.getElementById("submitBtn").onclick = function() { alert('Button clicked!'); }
B) document.submitBtn.addEventListener("click", function() { alert('Button clicked!'); });
C) document.getElementById("submitBtn").addEvent("click", function() { alert('Button clicked!'); });
D) document.getElementById("submitBtn").addEventListener("click", alert('Button clicked!'));

Answer: A) document.getElementById("submitBtn").onclick = function() { alert('Button clicked!'); }

Explanation: The correct way to handle a click event on a button is by using onclick or addEventListener, with the proper syntax as shown in option A.




Prepared by "Ismail Shah"