Enhance your JavaScript skills with hands-on code examples and clear explanations. Perfect for beginners, this guide covers essentials from basics to advanced topics, helping you build interactive web projects with confidence.
1. Hello World
console.log("Hello, World!");
How it works:
This code prints “Hello, World!” to the console. It helps verify that your environment is set up correctly.
2. Variables and Data Types
let name = "Alice"; // String
const age = 25; // Number
let isStudent = true; // Boolean
console.log(name, age, isStudent);
How it works:
let
declares a variable that can change.const
declares a constant that cannot change.- The variables store different types: string, number, and boolean.
- The
console.log
prints their values.
3. Functions
function greet(person) {
return `Hello, ${person}!`;
}
let message = greet("Bob");
console.log(message);
How it works:
- The
greet
function takes a name and returns a greeting. - It is called with “Bob”, and the message is stored.
- The message “Hello, Bob!” is printed to the console.
4. Conditional Statements
let score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else {
console.log("Grade: C");
}
How it works:
- The code checks the
score
value. - It prints the corresponding grade based on the score.
- For 85, it outputs “Grade: B”.
5. Loops
Example: For Loop
for (let i = 1; i <= 5; i++) {
console.log(`Number: ${i}`);
}
How it works:
- A
for
loop runs from 1 to 5. - It prints each number in the console.
Example: While Loop
let count = 1;
while (count <= 5) {
console.log(`Count: ${count}`);
count++;
}
How it works:
- A
while
loop continues whilecount
is 5 or less. - It prints the count and increases it each time.
6. Arrays and Array Methods
let fruits = ["Apple", "Banana", "Cherry"];
// Adding an element
fruits.push("Date");
// Removing the first element
fruits.shift();
// Iterating through the array
fruits.forEach(function(fruit) {
console.log(fruit);
});
How it works:
- An array
fruits
is created with three items. push
adds “Date” to the end.shift
removes “Apple” from the start.forEach
prints each remaining fruit.
7. Objects
let person = {
name: "Charlie",
age: 30,
greet: function() {
console.log(`Hi, I'm ${this.name} and I'm ${this.age} years old.`);
}
};
person.greet();
Explanation
- An object
person
has propertiesname
,age
, and a methodgreet
. - The
greet
method prints a message using the object’s properties. - Calling
person.greet()
displays the greeting.
8. DOM Manipulation
<!DOCTYPE html>
<html>
<head>
<title>DOM Manipulation</title>
</head>
<body>
<h1 id="title">Original Title</h1>
<button id="changeTitle">Change Title</button>
<script>
const title = document.getElementById("title");
const button = document.getElementById("changeTitle");
button.addEventListener("click", function() {
title.textContent = "Title Changed!";
});
</script>
</body>
</html>
How it works:
- The HTML has a heading and a button.
- JavaScript selects these elements.
- When the button is clicked, the heading text changes.
9. Event Handling
<!DOCTYPE html>
<html>
<head>
<title>Event Handling</title>
</head>
<body>
<form id="myForm">
<input type="text" id="username" placeholder="Enter your name" required />
<button type="submit">Submit</button>
</form>
<p id="greeting"></p>
<script>
const form = document.getElementById("myForm");
const usernameInput = document.getElementById("username");
const greeting = document.getElementById("greeting");
form.addEventListener("submit", function(event) {
event.preventDefault();
const name = usernameInput.value;
greeting.textContent = `Hello, ${name}!`;
usernameInput.value = "";
});
</script>
</body>
</html>
How it works:
- The form has an input and a submit button.
- JavaScript listens for the form submission.
- On submit, it shows a greeting and clears the input.
10. Asynchronous JavaScript: Promises and Fetch API
fetch("https://api.example.com/data")
.then(response => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then(data => {
console.log("Data received:", data);
})
.catch(error => {
console.error("There was a problem with the fetch operation:", error);
});
How it works:
fetch
requests data from an API.- It checks if the response is okay.
- If yes, it converts the response to JSON.
- The data is then logged. Errors are caught and displayed.