Modern JavaScript Course
Modern JavaScript Course
Arrow Functions
Shorter syntax for writing functions.
// Traditional function
function add(a, b) {
return a + b;
}
// Arrow function
const add = (a, b) => a + b;
Use arrow functions when you want concise function expressions, especially for callbacks.
Template Literals
Use backticks (`) to create strings that can include variables.
const name = "Tafadzwa";
console.log(`Hello, ${name}!`); // Output: Hello, Tafadzwa!
Multiline strings are easier with template literals:
const greeting = `Welcome to
JavaScript ES6!`;
Destructuring
Extract values from arrays or objects into variables.
// Array destructuring
const [a, b] = [10, 20];
console.log(a); // 10
// Object destructuring
const person = { name: "Anna", age: 30 };
const { name, age } = person;
console.log(name); // Anna
Exploring the DOM More Deeply
Beyond getElementById, you can use other powerful DOM methods:
Selecting Elements
document.querySelector(".my-class")
document.querySelectorAll("p")
document.getElementsByClassName("my-class")
document.getElementsByTagName("div")
Changing Attributes
document.querySelector("img").setAttribute("src", "new-image.jpg");
Event Listeners
Used to attach behavior to DOM elements.
const button = document.querySelector("button");
button.addEventListener("click", () => {
alert("Button clicked!");
});
Timers
Use setTimeout and setInterval for delayed and repeated actions.
setTimeout(() => {
console.log("Runs once after 2 seconds");
}, 2000);
setInterval(() => {
console.log("Runs every 1 second");
}, 1000);
Form Validation
<form id="myForm">
<input type="email" id="email" required>
<button type="submit">Submit</button>
</form>
<p id="error"></p>
document.getElementById("myForm").addEventListener("submit", function(e) {
const email = document.getElementById("email").value;
if (!email.includes("@")) {
e.preventDefault();
document.getElementById("error").textContent = "Please enter a valid email.";
}
});