-
Hello World (Console)
console.log("Hello, World!");
This code prints "Hello, World!" to the console.
-
Hello World (Browser)
This code prints "Hello, World!" in the browser.
-
Variables
let name = "Alice";
const age = 30;
console.log(name + " is " + age + " years old.");
This creates a variable `name` and a constant `age`, then logs a string to the console.
-
Functions
function add(a, b) {
return a + b;
}
let sum = add(5, 3);
console.log("The sum is: " + sum);
This defines a function `add` that takes two parameters and returns their sum.
-
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");
}
This code checks the `score` and logs the corresponding grade.
-
Loops
for (let i = 0; i < 5; i++) {
console.log("Iteration number: " + i);
}
This loop iterates five times, printing the iteration number to the console.
-
Arrays
let fruits = ["apple", "banana", "cherry"];
fruits.forEach(function(fruit) {
console.log(fruit);
});
This code initializes an array of fruits and uses `forEach` to print each fruit.
-
Objects
let person = {
name: "Bob",
age: 25,
greet: function() {
console.log("Hello, my name is " + this.name);
}
};
person.greet();
This initializes an object `person` with properties and a method, then calls the `greet` method.
-
Promises
let fetchData = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Data fetched successfully!");
} else {
reject("Error fetching data.");
}
});
fetchData
.then(response => console.log(response))
.catch(error => console.log(error));
This creates a simple promise that resolves or rejects based on a condition.
-
Asynchronous Functions
async function fetchData() {
return "Data fetched!";
}
fetchData().then(response => console.log(response));
This defines an asynchronous function that returns a string and uses `.then()` to log the result.