YouTip LogoYouTip

Js Examples

# JavaScript Examples: A Comprehensive Developer's Guide Welcome to the **YouTip** JavaScript Examples reference guide. This tutorial provides a structured, comprehensive collection of JavaScript examples ranging from basic syntax to advanced DOM manipulation and real-world UI components. Whether you are a beginner looking to understand core concepts or an experienced developer seeking clean, reusable code snippets, this guide serves as your go-to reference. --- ## 1. Basic JavaScript Examples These foundational examples demonstrate how to output text, manipulate HTML elements, and link external JavaScript files. ### Outputting Text Write text directly into the HTML document output stream. ```javascript // Note: Using document.write() after an HTML document is fully loaded will delete all existing HTML. document.write("Hello, World!"); ``` ### Modifying HTML Elements (DOM Manipulation) Select an HTML element by its ID and change its inner content. ```javascript // Find the element with id="demo" and change its content document.getElementById("demo").innerHTML = "Hello JavaScript!"; ``` ### External JavaScript To link an external JavaScript file, use the `src` attribute of the ` ``` ```javascript // myScript.js function myFunction() { document.getElementById("demo").innerHTML = "Paragraph changed by external JS."; } ``` --- ## 2. Statements, Comments, and Code Blocks Learn how to structure your code, write comments, and group statements into blocks. ### JavaScript Statements Statements are executed by the browser sequentially. ```javascript let x, y, z; // Statement 1: Declare variables x = 5; // Statement 2: Assign value 5 to x y = 6; // Statement 3: Assign value 6 to y z = x + y; // Statement 4: Assign the sum of x and y to z ``` ### Code Blocks JavaScript statements can be grouped together in code blocks inside curly brackets `{...}`. ```javascript function myBlockFunction() { document.getElementById("p1").innerHTML = "Hello World!"; document.getElementById("p2").innerHTML = "How are you?"; } ``` ### Single-line and Multi-line Comments Comments are used to explain code or prevent execution when testing. ```javascript // This is a single-line comment let speed = 100; // This comment is at the end of a line /* This is a multi-line comment. It can span multiple lines of text. */ let score = 95; ``` --- ## 3. Variables and Data Types Variables are containers for storing data values. ### Declaring and Displaying a Variable ```javascript // Declare a variable using 'let' (or 'var' / 'const') let carName = "Volvo"; // Display the variable inside an HTML element document.getElementById("demo").innerHTML = carName; ``` --- ## 4. Conditional Statements (If...Else, Switch) Use conditional statements to perform different actions based on different conditions. ### If...Else Statement ```javascript const hour = new Date().getHours(); let greeting; if (hour < 18) { greeting = "Good day"; } else { greeting = "Good evening"; } console.log(greeting); ``` ### Switch Statement Use the `switch` statement to select one of many code blocks to be executed. ```javascript let day; switch (new Date().getDay()) { case 0: day = "Sunday"; break; case 1: day = "Monday"; break; case 2: day = "Tuesday"; break; case 3: day = "Wednesday"; break; case 4: day = "Thursday"; break; case 5: day = "Friday"; break; case 6: day = "Saturday"; break; } console.log("Today is " + day); ``` --- ## 5. Popup Boxes JavaScript has three kinds of popup boxes: Alert, Confirm, and Prompt. ### Alert Box An alert box is used to ensure information gets through to the user. ```javascript // Display a simple alert message alert("This is an alert message!"); // Alert with line breaks alert("Hello\nHow are you?"); ``` ### Confirm Box A confirm box is often used if you want the user to verify or accept something. ```javascript if (confirm("Press a button!")) { console.log("You pressed OK!"); } else { console.log("You pressed Cancel!"); } ``` ### Prompt Box A prompt box is used if you want the user to input a value before entering a page. ```javascript let person = prompt("Please enter your name:", "Harry Potter"); if (person != null && person != "") { console.log("Hello " + person + "! How are you today?"); } ``` --- ## 6. Functions A JavaScript function is a block of code designed to perform a particular task, executed when "something" invokes it. ### Basic Function and Parameterized Functions ```javascript // Simple function with no arguments function sayHello() { console.log("Hello!"); } // Function with parameters function calculateProduct(a, b) { return a * b; // Returns the product of a and b } // Invoking the function and storing the result let result = calculateProduct(4, 3); console.log(result); // Outputs: 12 ``` --- ## 7. Loops Loops can execute a block of code a number of times. ### For Loop ```javascript // Loop through a block of code 5 times for (let i = 0; i < 5; i++) { console.log("The number is " + i); } ``` ### While and Do...While Loops ```javascript // While loop let i = 0; while (i < 5) { console.log("While count: " + i); i++; } // Do...While loop (always executes at least once) let j = 0; do { console.log("Do-While count: " + j); j++; } while (j < 5); ``` ### Break and Continue * `break` jumps out of a loop. * `continue` jumps over one iteration in the loop. ```javascript // Example of break for (let k = 0; k < 10; k++) { if (k === 5) { break; } console.log(k); // Outputs 0 to 4 } // Example of continue for (let m = 0; m < 5; m++) { if (m === 3) { continue; } console.log(m); // Outputs 0, 1, 2, 4 } ``` ### For...In Loop (Iterating Objects and Arrays) ```javascript const person = { fname: "John", lname: "Doe", age: 25 }; for (let key in person) { console.log(key + ": " + person); } ``` --- ## 8. Event Handling HTML events are "things" that happen to HTML elements. JavaScript can react to these events. ### Click Event (`onclick`) ```html ``` ### Mouseover Event (`onmouseover`) ```html
Mouse Over Me
``` --- ## 9. Error Handling The `try...catch` statement allows you to test a block of code for errors. ```javascript try { // Code that might throw an error adddlert("Welcome guest!"); } catch(err) { // Handle the error console.error("Error message: " + err.message); } ``` --- ## 10. Advanced JavaScript Examples ### Cookies Create, read, and delete cookies to store user preferences. ```javascript // Function to set a cookie function setCookie(cname, cvalue, exdays) { const d = new Date(); d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000)); let expires = "expires=" + d.toUTCString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; } // Function to get a cookie function getCookie(cname) { let name = cname + "="; let decodedCookie = decodeURIComponent(document.cookie); let ca = decodedCookie.split(';'); for(let i = 0; i < ca.length; i++) { let c = ca.trim(); if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } ``` ### Timing Events (setTimeout and setInterval) Execute code at specified time intervals. ```javascript // setTimeout: Executes a function once after a waiting period let timeoutID = setTimeout(() => { console.log("Executed after 3 seconds"); }, 3000); // setInterval: Executes a function repeatedly at set intervals let intervalID = setInterval(() => { console.log("Triggered every 2 seconds"); }, 2000); // Stop the execution clearTimeout(timeoutID); clearInterval(intervalID); ``` ### Creating Objects and Prototypes ```javascript // 1. Creating an object instance directly const car = { type: "Fiat", model: "500", color: "white" }; // 2. Creating an object constructor (Template) function Person(first, last, age, eye) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eye; } // Instantiate new objects const myFather = new Person("John", "Doe", 50, "blue"); ``` --- ## 11. Practical UI & Application Examples These patterns are commonly used in modern web development to build interactive user interfaces. ### Search Filter (List / Table) Filter lists or tables dynamically as the user types. ```javascript function filterList() { let input = document.getElementById("searchInput"); let filter = input.value.toUpperCase(); let ul = document.getElementById("myUL"); let li = ul.getElementsByTagName("li"); for (let i = 0; i < li.length; i++) { let txtValue = li.textContent || li.innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { li.style.display = ""; } else { li.style.display = "none"; } } } ``` ### Sorting a Table Alphabetically ```javascript function sortTable() { let table = document.getElementById("myTable"); let rows, switching, i, x, y, shouldSwitch; switching = true; while (switching) { switching = false; rows = table.rows; for (i = 1; i < (rows.length - 1); i++) { shouldSwitch = false; x = rows.getElementsByTagName("TD"); y = rows[i + 1].getElementsByTagName("TD"); if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) { shouldSwitch = true; break; } } if (shouldSwitch) { rows.parentNode.insertBefore(rows[i + 1], rows); switching = true; } } } ``` ### Detecting Mobile vs. Desktop Browsers ```javascript function detectDevice() { const toMatch = [ /Android/i, /webOS/i, /iPhone/i, /iPad/i, /iPod/i, /BlackBerry/i, /Windows Phone/i ]; const isMobile = toMatch.some((toMatchItem) => { return navigator.userAgent.match(toMatchItem); }); if (isMobile) { console.log("Mobile Browser Detected"); } else { console.log("Desktop Browser Detected"); } } ``` --- ## Considerations & Best Practices 1. **Use `const` and `let`**: Avoid using `var` to declare variables. Use `const` by default, and `let` if you know the variable's value will change. This prevents scope-related bugs. 2. **Minimize Global Variables**: Global variables can lead to naming collisions and hard-to-debug code. Keep your variables scoped inside functions or modules. 3. **Event Delegation**: When adding event listeners to multiple elements (like list items), attach a single listener to the parent element instead of individual listeners to each child. This improves performance. 4. **Asynchronous Code**: For modern applications, prefer using `async/await` and `Promises` over nested callbacks to keep your code clean and readable.
← Js Ex ObjectsJs Htmldom Events β†’