let x = 10;
const y = 20;
var z = 30;
const str = "Hello";
const num = 42;
const bool = true;
const arr = [1, 2, 3];
const obj = { key: "value" };
const n = null;
const u = undefined;
if (x > 10) {
console.log("x is greater than 10");
} else if (x === 10) {
console.log("x is 10");
} else {
console.log("x is less than 10");
}
for (let i = 0; i < 5; i++) {
console.log(i);
}
let j = 0;
while (j < 5) {
console.log(j);
j++;
}
Implicit return for one-liner
const add = (a, b) => a + b;
Explicit return for multi-line
const multiply = (a, b) => {
return a * b;
};
With Default Parameters
const greet = (name = "Guest") => `Hello, ${name}!`;
map()
const nums = [1, 2, 3];
const squares = nums.map(n => n * n);
filter()
const evens = nums.filter(n => n % 2 === 0);
reduce()
const sum = nums.reduce((acc, n) => acc + n, 0);
forEach()
nums.forEach(n => console.log(n));
find() and findIndex()
const found = nums.find(n => n > 1);
const index = nums.findIndex(n => n > 1);
Object Creation
const person = { name: "John", age: 30 };
Accessing Properties
console.log(person.name);
console.log(person["age"]);
Object Destructuring
const { name, age } = person;
console.log(name, age);
Spread & Rest Operators
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
const { a, ...rest } = obj2;
Set
const set = new Set([1, 2, 2, 3]);
console.log(set.has(2));
set.add(4);
set.delete(1);
console.log([...set]);
Map
const map = new Map();
map.set("key", "value");
console.log(map.get("key"));
map.delete("key");
Promises
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
Async/Await
const fetchData = async () => {
try {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
};
fetchData();
Basic Class
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
const dog = new Animal("Dog");
dog.speak();
Inheritance
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
const dog = new Dog("Dog");
dog.speak();