<!DOCTYPE html> <!-- Tells the browser this is an HTML5 document -->
<html>
<head>
<title>Student Grading System</title> <!-- Title of the webpage -->
</head>
<body>
<h2>Student Grading Form</h2> <!-- Heading displayed on the page -->
<!-- The form where user inputs student data -->
<form id="gradeForm">
<!-- Input for student name -->
<label>Student Name:</label><br>
<input type="text" id="name" required><br><br>
<!-- Input for student ID -->
<label>Student ID:</label><br>
<input type="text" id="studentId" required><br><br>
<!-- Input for score (0–100) -->
<label>Score:</label><br>
<input type="number" id="score" min="0" max="100" required><br><br>
<!-- Button the user clicks to calculate grade -->
<button type="button" onclick="calculateGrade()">Submit</button>
</form>
<!-- Area where the result will be shown -->
<h3>Result:</h3>
<div id="result"></div>
<script>
// This function runs when the "Submit" button is clicked
function calculateGrade() {
// Get the value of the "name" input field
let name = document.getElementById("name").value;
// Get the value of the "studentId" input field
let studentId = document.getElementById("studentId").value;
// Get the numeric value of the "score" input field
let score = Number(document.getElementById("score").value);
// Variable to store the grade
let grade;
// Check score and assign the correct grade
if (score >= 90) grade = "A"; // Score 90–100
else if (score >= 80) grade = "B"; // Score 80–89
else if (score >= 70) grade = "C"; // Score 70–79
else if (score >= 60) grade = "D"; // Score 60–69
else grade = "F"; // Score below 60
// Display all results inside the "result" div
document.getElementById("result").innerHTML = `
<p><strong>Name:</strong> ${name}</p>
<p><strong>ID:</strong> ${studentId}</p>
<p><strong>Score:</strong> ${score}</p>
<p><strong>Grade:</strong> ${grade}</p>
`;
}
</script>
</body>
</html>
Category: JavaScript
Simple Calculator Example in JavaScript
<head>
<title>Simple Calculator</title>
</head>
<body>
<h2>Calculator</h2>
<input id="num1" type="number" placeholder="Number 1">
<input id="num2" type="number" placeholder="Number 2">
<select id="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<button onclick="calculate()">Calculate</button>
<p id="result"></p>
<script>
function calculate() {
const num1 = parseFloat(document.getElementById("num1").value);
const num2 = parseFloat(document.getElementById("num2").value);
const op = document.getElementById("operator").value;
let result;
switch (op) {
case '+': result = num1 + num2; break;
case '-': result = num1 - num2; break;
case '*': result = num1 * num2; break;
case '/': result = num2 !== 0 ? num1 / num2 : "Error: Divide by zero"; break;
default: result = "Invalid operator";
}
document.getElementById("result").innerText = "Result: " + result;
}
</script>
</body>
</html>Cheat Sheet
JavaScript Master Cheat Sheet
A compact, styled reference that covers basics → advanced topics. Paste into a WordPress Custom HTML block.
Basics
Include scripts, comments, and simple examples.
<!-- Inline -->
<script>
// JS goes here
console.log('Hello world');
</script>
<!-- External file -->
<script src="app.js"></script>
Variables & Types
Use let/const for block scope; var is function-scoped.
// Declaration examples
var legacy = 'hello';
let counter = 0;
const PI = 3.14159;
// Common types
let name = "Jane"; // string
let isActive = true; // boolean
let scores = [10, 20, 30]; // array
let user = { id: 1, name: 'J' }; // object
Arrays
Common methods for manipulating arrays.
const fruits = ["Banana","Apple","Pear"];
fruits.push("Orange"); // add
fruits.pop(); // remove last
fruits.includes("Apple"); // true
const part = fruits.slice(1,3); // shallow copy portion
fruits.splice(2,1, "Kiwi"); // remove & replace
Operators
Arithmetic, comparison, logical.
5 + 3; // 8
10 % 3; // 1 remainder
x === y; // strict equality
x !== y; // not equal
a && b; // logical AND
a || b; // logical OR
!flag; // logical NOT
Functions
Classic, arrow, default params, IIFE.
// Classic
function greet(name){ return `Hello ${name}`; }
// Arrow
const add = (a,b) => a + b;
// Default param
function welcome(user = 'Guest'){ console.log(user); }
// IIFE (immediately-invoked)
(function(){ console.log('Init'); })();
Loops
for, while, for…of, break/continue.
// for
for(let i=0;i<5;i++){ console.log(i); }
// while
let n=3; while(n--){console.log(n);}
// for...of for arrays
for(const v of [1,2,3]) { console.log(v); }
// break & continue
for(let i=0;i<5;i++){
if(i===2) continue;
if(i===4) break;
}
If / Else
Conditional logic with ternary shortcuts.
if(age >= 18){
console.log('Adult');
} else if(age >= 13){
console.log('Teen');
} else {
console.log('Child');
}
// ternary
const status = age >= 18 ? 'Adult' : 'Minor';
Strings
Common methods & escape sequences.
const s = "JavaScript";
s.toLowerCase();
s.toUpperCase();
s.includes("Script");
s.replace("Java","ECMA");
s.slice(0,4); // "Java"
// escapes: \n, \t, \', \"
Regular Expressions
Patterns, flags, common usage.
// flags: i (ignore), g (global), m (multiline)
const rx = /\\d+/g;
"abc123".match(rx); // ["123"]
/^[A-Z]/.test("Hello"); // true if starts with capital
Numbers & Math
Parsing, Math helper methods.
Number("42"); // 42
parseInt("10px"); // 10
parseFloat("3.14"); // 3.14
Math.random(); // 0..1
Math.round(2.7); // 3
Math.max(1,5,3); // 5
Math.sqrt(16); // 4
Dates
Create and manipulate dates.
const now = new Date();
const custom = new Date(2025, 11, 25); // year, monthIndex(0-11), day
now.getFullYear();
now.getMonth(); // 0-11
now.getTime(); // ms since 1970
DOM (Document)
Select elements, update content, create nodes.
// Select
const el = document.getElementById('title');
const firstBtn = document.querySelector('.btn');
// Update
el.textContent = 'New Title';
el.innerHTML = '<strong>Bold</strong>';
// Create / append
const div = document.createElement('div');
div.textContent = 'Hi';
document.body.appendChild(div);
Browser & Window
Window methods & properties.
alert('Hi');
console.log(window.location.href);
setTimeout(()=>console.log('later'), 1000);
localStorage.setItem('k','v');
Events
Listening patterns and common event names.
// Click
button.addEventListener('click', (e) => {
console.log('clicked', e.target);
});
// Keyboard
window.addEventListener('keydown', (e) => {
if(e.key === 'Enter') console.log('enter pressed');
});
Errors & Debugging
try/catch and useful console tools.
try {
mightFail();
} catch(err) {
console.error('Error:', err.message);
} finally {
console.log('cleanup');
}
// console methods: log, warn, error, table, group
Tip: Use the copy buttons to quickly paste examples into your editor.
Java Script Exam 2
1. What keyword creates a block-scoped variable that can be reassigned?
let score = 10;
2. Which statement correctly creates a function named sum?
function sum(a, b) { return a + b; }
3. What will this log?
console.log(typeof null);
4. Which method adds a value to the end of an array?
let a = [1,2]; a.push(3);
5. What does === test for?
6. Which of these creates an object with a property name?
let obj = { name: 'Sam' };
7. What will [1,2,3].map(x => x * 2) return?
[1,2,3].map(x => x * 2);
8. Which is true about const?
9. What is hoisting in JavaScript?
10. Which method parses a JSON string into an object?
JSON.parse('{"a":1}');
11. What will this expression return: [...'abc'] ?
[...'abc']
12. How do you schedule a function to run after 2 seconds?
setTimeout(fn, 2000);
13. Which event fires when the DOM has been loaded (but before images load)?
14. What does Array.prototype.filter return?
15. Which of these accesses the element with id ‘app’?
document.getElementById('app')
16. What is a Promise?
17. How do you catch errors from a Promise?
promise.then(...).catch(err => ...)
18. What does async/await provide?
19. Which built-in method returns the characters in a string as uppercase?
'hi'.toUpperCase()
20. How do you remove the first element from an array?
let a = [1,2,3]; a.shift();
21. Which operator spreads an array into separate arguments?
Math.max(...[1,2,3])
22. What will 0 == '0' evaluate to?
23. Which method trims whitespace from both ends of a string?
' hi '.trim()
24. What will typeof [] return?
25. Which regex flag makes matching case-insensitive?
/abc/i
26. Which built-in object provides methods for rounding and generating random numbers?
27. What is the output of typeof NaN?
28. Which DOM API finds elements by class name?
document.getElementsByClassName('btn')
29. What does event.preventDefault() do?
30. Which of these creates a shallow copy of an object?
let copy = Object.assign({}, obj);
31. What does document.createElement('div') do?
32. Which method returns the index of the first match in an array?
33. Which will parse integer from string?
34. Which of the following is a truthy value?
35. What does Object.keys(obj) return?
36. Which will stop propagation of an event so it doesn’t bubble up?
37. Which creates a new object that delegates to a specified prototype?
38. Which will convert a value to a number, returning NaN on failure?
39. What will 0 === -0 evaluate to?
40. Which statement throws an exception?
41. Which returns milliseconds since 1970-01-01 UTC?
42. What does call() do on functions?
43. Which removes a property from an object?
delete obj.prop;
44. Which is true about arrow functions?
45. What is event delegation?
46. Which array method reduces values to a single value?
47. What does void 0 evaluate to?
48. Which error type indicates invalid JSON or code syntax?
49. Which returns true if at least one element passes a predicate?
arr.some(x => x > 5)
50. Which method adds an element as the last child of a node?
parent.appendChild(child)
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?
JavaScript Operators Quiz
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>
JavaScript Variables Quiz