Overview of JavaScript & Fundamentals Features & Scripting Need for Client-Side Scripting: Enhances user experience by providing dynamic and interactive content directly in the browser, reducing server load and response times. Handles UI manipulation, form validation, and asynchronous communication. Benefits/Features of JavaScript: Interactivity: Makes web pages dynamic (e.g., animations, form validation). Client-side execution: Runs in the user's browser, faster response. Versatility: Used for front-end, back-end (Node.js), and mobile development. Rich Ecosystem: Large community, libraries, and frameworks (React, Angular, Vue). Asynchronous Processing: Handles operations without blocking the main thread (AJAX). Implementation Internal JavaScript: Script embedded directly within an HTML file using <script> tags. <!DOCTYPE html> <html> <head> <title>Internal JS</title> </head> <body> <script> alert('Hello from internal JavaScript!'); </script> </body> </html> External JavaScript: Script placed in a separate .js file and linked to HTML using the src attribute. // script.js alert('Hello from external JavaScript!'); <!DOCTYPE html> <html> <head> <title>External JS</title> <script src="script.js"</script> </head> <body> </body> </html> Loops 8 Times Table: for (let i = 1; i <= 10; i++) { console.log(`8 x ${i} = ${8 * i}`); } for loop in JSON (Conceptual explanation): A for loop iterates over a block of code a number of times. While JSON is a data format and doesn't directly execute code, you would use a JavaScript for loop to process data *contained within* a JSON object or array. const data = { products: [ { id: 1, name: 'Laptop' }, { id: 2, name: 'Keyboard' } ] }; for (let i = 0; i < data.products.length; i++) { console.log(`Product ID: ${data.products[i].id}, Name: ${data.products[i].name}`); } Conditional & Control Statements switch Statement: Executes different actions based on different conditions. let day = 'Monday'; let message; switch (day) { case 'Monday': message = 'Start of the week!'; break; case 'Friday': message = 'Weekend is near!'; break; default: message = 'Just another day.'; } console.log(message); // Output: Start of the week! break Statement: Terminates the current loop or switch statement and transfers control to the statement immediately following the terminated statement. for (let i = 0; i < 10; i++) { if (i === 5) { break; // Loop terminates when i is 5 } console.log(i); // Output: 0, 1, 2, 3, 4 } continue Statement: Skips the current iteration of a loop and continues with the next iteration. for (let i = 0; i < 5; i++) { if (i === 2) { continue; // Skips printing 2 } console.log(i); // Output: 0, 1, 3, 4 } Pop-up Boxes Types of Pop-up Boxes: alert() : Displays an alert message with an "OK" button. Used for notifications. alert('This is an alert message!'); confirm() : Displays a message with "OK" and "Cancel" buttons. Returns true if OK is clicked, false otherwise. Used for user confirmation. let result = confirm('Do you want to proceed?'); if (result) { console.log('User clicked OK.'); } else { console.log('User clicked Cancel.'); } prompt() : Displays a dialog box that prompts the user for input. Returns the input string or null if Cancel is clicked. let name = prompt('Please enter your name:', 'Guest'); if (name !== null && name !== '') { console.log(`Hello, ${name}!`); } else { console.log('Name not entered.'); } confirm() Box Syntax and Usage: The confirm() method displays a dialog box with a specified message and two buttons: "OK" and "Cancel". It returns a boolean value: true if the user clicks "OK", and false if the user clicks "Cancel". Syntax: confirm("messageText") Example: function deleteItem() { if (confirm("Are you sure you want to delete this item?")) { alert("Item deleted successfully!"); // Logic to delete the item } else { alert("Deletion cancelled."); } } // Call this function, e.g., on a button click: // <button onclick="deleteItem()">Delete</button> JavaScript Functions & Events Functions Calculate Percentage and Grade: function calculateGrade(score) { let percentage = (score / 100) * 100; // Assuming max score is 100 let grade; if (percentage >= 90) { grade = 'A'; } else if (percentage >= 80) { grade = 'B'; } else if (percentage >= 70) { grade = 'C'; } else if (percentage >= 60) { grade = 'D'; } else { grade = 'F'; } console.log(`Score: ${score}, Percentage: ${percentage.toFixed(2)}%, Grade: ${grade}`); return grade; } calculateGrade(85); // Output: Score: 85, Percentage: 85.00%, Grade: B calculateGrade(55); // Output: Score: 55, Percentage: 55.00%, Grade: F Check if a Number is Positive, Negative, or Zero: function checkNumber(num) { if (num > 0) { console.log(`${num} is positive.`); } else if (num < 0) { console.log(`${num} is negative.`); } else { console.log(`${num} is zero.`); } } checkNumber(10); // Output: 10 is positive. checkNumber(-5); // Output: -5 is negative. checkNumber(0); // Output: 0 is zero. Events onload and onmouseover Events: <!DOCTYPE html> <html> <head> <title>Events Example</title> <style> #myDiv { width: 100px; height: 100px; background-color: lightblue; text-align: center; line-height: 100px; cursor: pointer; } </style> <script> function pageLoaded() { console.log("Page has finished loading!"); document.getElementById('status').innerText = 'Page Loaded'; } function mouseOverDiv() { document.getElementById('myDiv').style.backgroundColor = 'lightcoral'; document.getElementById('myDiv').innerText = 'Hovering!'; } function mouseOutDiv() { document.getElementById('myDiv').style.backgroundColor = 'lightblue'; document.getElementById('myDiv').innerText = 'Hover Me'; } </script> </head> <body onload="pageLoaded()"> <p>Page Status: <span id="status">Loading...</span></p> <div id="myDiv" onmouseover="mouseOverDiv()" onmouseout="mouseOutDiv()"> Hover Me </div> </body> </html> onreset and onsubmit Event Handlers: <!DOCTYPE html> <html> <head> <title>Form Events</title> <script> function handleReset() { alert("Form is being reset!"); return true; // Allow reset } function handleSubmit(event) { event.preventDefault(); // Prevent default form submission const name = document.getElementById('name').value; alert(`Form submitted by: ${name}`); // You can add AJAX submission here return false; // Prevent default submission } </script> </head> <body> <form onreset="return handleReset()" onsubmit="return handleSubmit(event)"> <label for="name">Name:</label> <input type="text" id="name" name="name" required><br><br> <input type="submit" value="Submit"> <input type="reset" value="Reset"> </form> </body> </html> onload , onmousedown , onmouseup for text color change: <!DOCTYPE html> <html> <head> <title>Color Change Event</title> <style> #myText { font-size: 24px; cursor: pointer; color: black; /* Default color */ } </style> <script> function initPage() { document.getElementById('myText').innerText = 'Click and hold me!'; } function changeToRed() { document.getElementById('myText').style.color = 'red'; } function changeToGreen() { document.getElementById('myText').style.color = 'green'; } </script> </head> <body onload="initPage()"> <p id="myText" onmousedown="changeToRed()" onmouseup="changeToGreen()"> Initial Text </p> </body> </html> JavaScript Objects String Object replace() : Replaces a specified value with another value in a string. let text = "Hello World"; let newText = text.replace("World", "JavaScript"); // "Hello JavaScript" charAt() : Returns the character at a specified index (position) in a string. let char = text.charAt(1); // "e" search() : Searches a string for a specified value, returning the position of the match. let pos = text.search("World"); // 6 substr() : Extracts a part of a string, starting at a specified position and returning a specified number of characters. (Deprecated, prefer substring() or slice() ). let part = text.substr(6, 5); // "World" indexOf() : Returns the position of the first occurrence of a specified value in a string. let index = text.indexOf("o"); // 4 Array Object Accept 5 numbers, store, sort: function processNumbers() { const numbers = []; for (let i = 0; i < 5; i++) { let input = prompt(`Enter number ${i + 1}:`); numbers.push(parseFloat(input)); } console.log("Original numbers:", numbers); // Ascending sort const ascending = [...numbers].sort((a, b) => a - b); console.log("Ascending order:", ascending); // Descending sort const descending = [...numbers].sort((a, b) => b - a); console.log("Descending order:", descending); } // processNumbers(); Array Properties and Methods: Properties: length : Returns the number of elements in an array. Methods: push() : Adds one or more elements to the end of an array. pop() : Removes the last element from an array. shift() : Removes the first element from an array. unshift() : Adds one or more elements to the beginning of an array. splice() : Changes the contents of an array by removing or replacing existing elements and/or adding new elements. slice() : Returns a shallow copy of a portion of an array into a new array object. concat() : Joins two or more arrays. forEach() : Executes a provided function once for each array element. map() : Creates a new array populated with the results of calling a provided function on every element in the calling array. filter() : Creates a new array with all elements that pass the test implemented by the provided function. reduce() : Executes a reducer function on each element of the array, resulting in a single output value. sort() : Sorts the elements of an array in place and returns the array. indexOf() : Returns the first index at which a given element can be found in the array, or -1 if it is not present. Math Object Math.abs(x) : Returns the absolute value of $x$. (e.g., Math.abs(-5) is 5) Math.ceil(x) : Returns $x$ rounded up to the nearest integer. (e.g., Math.ceil(4.3) is 5) Math.floor(x) : Returns $x$ rounded down to the nearest integer. (e.g., Math.floor(4.9) is 4) Math.round(x) : Returns $x$ rounded to the nearest integer. (e.g., Math.round(4.4) is 4, Math.round(4.6) is 5) Math.random() : Returns a pseudo-random number between 0 (inclusive) and 1 (exclusive). Math.max(x, y, ...) : Returns the number with the highest value. Math.min(x, y, ...) : Returns the number with the lowest value. Math.pow(x, y) : Returns the value of $x$ to the power of $y$. Math.sqrt(x) : Returns the square root of $x$. Other Built-in Objects Number Object: A wrapper object allowing you to work with numerical values. Properties: Number.MAX_VALUE , Number.MIN_VALUE . Methods: toFixed() , toPrecision() . let num = 123.456; console.log(num.toFixed(2)); // "123.46" (string) Date Object: Used to work with dates and times. Methods: getDate() , getMonth() , getFullYear() , getHours() , getMinutes() , getSeconds() , getTime() . const d = new Date(); console.log(d.getFullYear()); // Current year Boolean Object: A wrapper object for boolean values. RegExp Object: Used for regular expressions. Global Objects: isNaN() : Checks if a value is "Not-a-Number". parseInt() : Parses a string argument and returns an integer. parseFloat() : Parses a string argument and returns a floating point number. eval() : Evaluates JavaScript code represented as a string. (Use with caution due to security risks) Validation & Errors Form Validation Concept of Validating Forms: Form validation ensures that user input meets specific criteria before being submitted to a server. This improves data quality, enhances user experience by providing immediate feedback, and reduces server-side processing errors. Validation can be client-side (JavaScript) or server-side. Validate Username and Password: function validateForm() { const username = document.getElementById('username').value; const password = document.getElementById('password').value; let isValid = true; // Username validation if (username === '') { alert('Username cannot be empty.'); isValid = false; } else if (username.length < 3) { alert('Username must be at least 3 characters long.'); isValid = false; } else if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(username)) { alert('Username must start with an alphabet or underscore, and contain only alphanumeric characters or underscores.'); isValid = false; } // Password validation if (password === '') { alert('Password cannot be empty.'); isValid = false; } else if (password.length < 8) { alert('Password must be at least 8 characters long.'); isValid = false; } else if (!password.includes('@')) { alert('Password must contain an "@" symbol.'); isValid = false; } return isValid; // Prevent form submission if not valid } // HTML example: <form onsubmit="return validateForm()">...</form> Validate Email, Username, Password, and Confirm Password: function validateComplexForm() { const email = document.getElementById('email').value; const username = document.getElementById('username2').value; const password = document.getElementById('password2').value; const confirmPassword = document.getElementById('confirmPassword').value; let isValid = true; // Email validation const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (!emailRegex.test(email)) { alert('Please enter a valid email address.'); isValid = false; } // Username validation (same as above) if (username === '') { alert('Username cannot be empty.'); isValid = false; } else if (username.length < 3) { alert('Username must be at least 3 characters long.'); isValid = false; } else if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(username)) { alert('Username must start with an alphabet or underscore, and contain only alphanumeric characters or underscores.'); isValid = false; } // Password validation (same as above) if (password === '') { alert('Password cannot be empty.'); isValid = false; } else if (password.length < 8) { alert('Password must be at least 8 characters long.'); isValid = false; } else if (!password.includes('@')) { alert('Password must contain an "@" symbol.'); isValid = false; } // Confirm Password validation if (password !== confirmPassword) { alert('Password and Confirm Password do not match.'); isValid = false; } return isValid; } // HTML example: <form onsubmit="return validateComplexForm()">...</form> Error & Exception Handling try...catch...finally...throw : JavaScript provides structured error handling using the try...catch...finally block. This allows you to test for errors in a block of code, handle them gracefully, and execute code regardless of whether an error occurred. try : Defines a block of code to be tested for errors while it is being executed. catch : Defines a block of code to be executed if an error occurs in the try block. finally : Defines a block of code to be executed regardless of whether an error occurred or not. throw : Allows you to create custom errors. function divide(a, b) { try { if (b === 0) { throw new Error("Division by zero is not allowed."); } const result = a / b; console.log(`Result: ${result}`); return result; } catch (error) { console.error("An error occurred:", error.message); // You could display this error to the user or log it return null; } finally { console.log("Division attempt finished."); } } divide(10, 2); // Output: Result: 5, Division attempt finished. divide(10, 0); // Output: An error occurred: Division by zero is not allowed., Division attempt finished.