JavaScript Exam 1

1. What keyword creates a changeable variable?




2. What is the boolean value of the string “0”?

Boolean("0")



3. What is the length of this array?

let arr = ["x", "y", "z"];



4. What does a function return if it has no return statement?




5. Can JavaScript be included in any valid HTML file?




6. What will this display?

let x = 4; let y = 6; let z = x + "" + y; alert(z);



7. Will this behave the same in all browsers?

"hello".substring(-1);



8. What does parseInt return here?

parseInt(52.9);



9. Can browser JavaScript directly read/write arbitrary local files?




10. What will this loop alert?

let total=0; for(let i=1;i<=8;i++){ if(i%3===0) continue; if(i>5) break; total+=i } alert(total);



12. Do all JavaScript engines behave identically for every feature?




13. What is the result of “super”+”man”?




14. What does s.replace(/l/g,”#”) do to “balloon”?




15. What does s.replace(“l”,”#”) do to “balloon”?




16. Which returns the integer part of a number?

Math.floor(3.9)



17. What will this alert?

let a=4, b=2; function calc(x){ b = a + x; return ++b; } alert(calc(3));



18. How to append 5 to array nums?




19. Which event fires when the mouse enters an element?




20. typeof Infinity returns?




21. Which keyword declares a constant?




22. What does Number(“123”) return?




23. What does console.log(“5” – 2) output?




24. What is the result of [] + [] ?




25. typeof [] returns?




26. Which method removes the last item of an array?




27. What value does let x; create?




28. What does “hello”.toUpperCase() return?




29. Which operator checks both value and type?




30. What does “cat”.includes(“a”) return?




31. What does typeof null return?




32. What does !true evaluate to?




33. Which literal creates an array?




34. What does push() return?




35. Which loop runs the body at least once?




36. Which event triggers on a click?




37. What is the result of NaN === NaN ?




38. Which is a primitive type?




39. typeof function(){} returns?




40. What does JSON.stringify({a:1}) do?




41. Which method adds elements to the start of an array?




42. What does “10” + 1 produce?




43. How to make a shallow copy of array a?




44. Which checks array membership?




45. typeof (function(){}) returns?




46. Which method converts a string to lowercase?




47. What does 0 == “0” evaluate to?




48. Which declares a block-scoped variable?




49. Which method splits a string into an array?




50. Which array method returns true if every element passes the test?




Posted on by admin

JavaScript Operators Quiz 

1. What is the result of 3 + '2' in JavaScript?

2. What is the result of '5' - 2?

3. Which operator checks both value and type?

4. What is the result of 0 == false?

5. What is the result of 0 === false?

6. What does typeof return for an array?

7. What is 2 ** 3?

8. What is '10' / '2'?

9. Which operator is optional chaining?

10. What is typeof undefined?

11. What does the nullish coalescing operator (??) return?

12. What is the result of true + true?

13. What is typeof NaN?

14. What is the result of '4' * '2'?

15. What does !!value convert to?

16. Which operator has the highest precedence?

17. What is [] == '' ?

18. What is the result of [] === []?

19. What does typeof return for functions?

20. Which operator assigns only if the left side is null or undefined?

21. What is +true?

22. What is +'7'?

23. What is 1 < 2 < 0?

24. What is typeof null?

25. What is [] + {}?

Posted on by admin

Client-Side Validated Contact Form Using HTML and JavaScript

This code implements a simple HTML contact form and includes JavaScript-based client-side validation with fully commented lines explaining each step. The HTML structure defines labeled input fields for name, email, subject, and message, along with hidden inline error messages that appear only when validation fails. The form intentionally disables the browser’s default validation using novalidate, allowing custom JavaScript logic to run instead. In the JavaScript section, the script retrieves references to all form fields and their corresponding error display elements, defines a lightweight email-format check, and provides helper functions to toggle error visibility. The main validation function trims and checks each field for minimum length or proper formatting, dynamically showing or hiding errors. When the form is submitted, the script prevents the default submission, validates all fields, displays a success message if everything passes, and resets the form. This combination of HTML and JavaScript demonstrates clear input handling, user feedback, and form-validation workflow for a basic client-side contact form.

<!doctype html> <!-- Tells the browser this is an HTML5 document -->
<html lang="en"> <!-- Sets the language of the page to English -->
<head> <!-- Head section: contains metadata and the title -->
  <meta charset="utf-8"> <!-- Sets character encoding to UTF-8 -->
  <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Makes the page responsive on mobile -->
  <title>Simple Contact Form</title> <!-- The page title displayed in the browser tab -->
</head>
<body> <!-- The visible body content begins -->

  <h2>Contact Us</h2> <!-- Heading for the page -->

  <!-- Form element; novalidate disables browser’s default validation -->
  <form id="contactForm" novalidate> <!-- The form container -->

    <label for="name">Name</label> <!-- Label describing the input field -->
    <input type="text" id="name" name="name" placeholder="Your full name"> <!-- Text input for the name -->
    <div id="nameError" style="color:red; display:none;"> <!-- Error message, hidden until needed -->
      Please enter your name (at least 2 characters).
    </div>
    <br><br> <!-- Line breaks for spacing -->

    <label for="email">Email</label> <!-- Label for email field -->
    <input type="email" id="email" name="email" placeholder="you@example.com"> <!-- Email input -->
    <div id="emailError" style="color:red; display:none;"> <!-- Email error message -->
      Please enter a valid email address.
    </div>
    <br><br>

    <label for="subject">Subject</label> <!-- Label for subject -->
    <input type="text" id="subject" name="subject" placeholder="Subject"> <!-- Subject input field -->
    <div id="subjectError" style="color:red; display:none;"> <!-- Subject error message -->
      Subject must be at least 4 characters.
    </div>
    <br><br>

    <label for="message">Message</label> <!-- Label for message textarea -->
    <textarea id="message" name="message" placeholder="Write your message here..."></textarea> <!-- Message box -->
    <div id="messageError" style="color:red; display:none;"> <!-- Message error element -->
      Message must be at least 10 characters.
    </div>
    <br><br>

    <button type="submit">Send Message</button> <!-- Submit button -->

    <div id="successMessage" style="color:green; display:none;"> <!-- Success text shown only on valid submission -->
      Your message was sent successfully! (Demo only)
    </div>

  </form> <!-- End of form -->

  <script> <!-- Begin JavaScript validation code -->

    const form = document.getElementById('contactForm'); // Grab the form element
    const nameInput = document.getElementById('name'); // Reference to name field
    const emailInput = document.getElementById('email'); // Reference to email field
    const subjectInput = document.getElementById('subject'); // Reference to subject field
    const messageInput = document.getElementById('message'); // Reference to message textarea

    const nameError = document.getElementById('nameError'); // Reference to name error box
    const emailError = document.getElementById('emailError'); // Reference to email error box
    const subjectError = document.getElementById('subjectError'); // Reference to subject error box
    const messageError = document.getElementById('messageError'); // Reference to message error box
    const successMessage = document.getElementById('successMessage'); // Reference for success feedback

    // Basic email validation function (checks for @ and .)
    function isValidEmail(email) { // Function definition
      return email.includes('@') && email.includes('.') && email.indexOf('@') > 0; // Returns true if email looks valid
    }

    // Show or hide an error message
    function showError(element, show) { // element = target error box, show = boolean
      element.style.display = show ? 'block' : 'none'; // Toggles display accordingly
    }

    // Main validation routine
    function validateForm() { // Runs when form is submitted
      let valid = true; // Assume valid until a rule fails

      const name = nameInput.value.trim(); // Get trimmed name value
      const email = emailInput.value.trim(); // Get trimmed email
      const subject = subjectInput.value.trim(); // Get trimmed subject
      const message = messageInput.value.trim(); // Get trimmed message

      if (name.length < 2) { // If name is too short
        showError(nameError, true); // Show name error
        valid = false; // Mark form invalid
      } else showError(nameError, false); // Hide error

      if (!isValidEmail(email)) { // If email format is bad
        showError(emailError, true); // Show email error
        valid = false; // Mark form invalid
      } else showError(emailError, false); // Hide error

      if (subject.length < 4) { // If subject too short
        showError(subjectError, true); // Show subject error
        valid = false;
      } else showError(subjectError, false);

      if (message.length < 10) { // If message too short
        showError(messageError, true); // Show error
        valid = false;
      } else showError(messageError, false);

      return valid; // Return true only if all fields pass
    }

    // Handle form submission
    form.addEventListener('submit', function(event) { // Listener for clicking submit
      event.preventDefault(); // Prevent actual form submission
      successMessage.style.display = 'none'; // Hide success message each attempt

      const valid = validateForm(); // Run validation checks

      if (valid) { // If all fields passed
        successMessage.style.display = 'block'; // Show success message
        form.reset(); // Clear all fields
      }
    });

  </script> <!-- End JavaScript block -->

</body>
</html>
Posted on by admin

JavaScript Variables Quiz

1. What keyword lets you create a changeable variable?

2. Which keyword creates a variable that cannot change?

3. Which keyword is used in old JavaScript?

4. What value does var have before setting it?

5. What happens if you use let before declaring it?

6. Which keyword stays inside a block?

7. Which keyword ignores block scope?

8. Which keyword is best for fixed values?

9. Which variable can change?

10. Which variable must have a value when created?

11. Which keyword should be avoided?

12. What happens if you redeclare let?

13. What happens if you assign without var/let/const?

14. Which variable shows undefined before setting?

15. Which variables throw ReferenceError before setting?

16. Which becomes part of window object?

17. Which is best for loop counters?

18. Which keyword allows shadowing?

19. Which keyword was added in ES6?

20. Which variable is safest for beginners?

Posted on by admin