Variables
// Using var
var name = "John";
// Using let
let age = 30;
// Using const
const isStudent = true;
Data Types
// String
let firstName = "John";
// Number
let age = 25;
// Boolean
let isAvailable = true;
// Null
let emptyValue = null;
// Undefined
let unknownValue;
// Object
let person = {
name: "John",
age: 30,
};
// Array
let colors = ["red", "green", "blue"];
Operators
// Arithmetic
let sum = 10 + 5;
let difference = 10 - 5;
let product = 10 * 5;
let quotient = 10 / 5;
let remainder = 10 % 3;
// Assignment
let x = 10;
x += 5; // x = x + 5
x -= 5; // x = x - 5
x *= 5; // x = x * 5
x /= 5; // x = x / 5
// Comparison
let isEqual = 10 == "10"; // true
let isStrictEqual = 10 === "10"; // false
let isNotEqual = 10 != "10"; // false
let isStrictNotEqual = 10 !== "10"; // true
let isGreaterThan = 10 > 5; // true
let isLessThan = 10 < 5; // false
let isGreaterThanOrEqual = 10 >= 5; // true
let isLessThanOrEqual = 10 <= 5; // false
// Logical
let and = true && false; // false
let or = true || false; // true
let not = !true; // false
Conditionals
// if statement
if (age > 18) {
console.log("Adult");
} else if (age > 12) {
console.log("Teenager");
} else {
console.log("Child");
}
// switch statement
let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Unknown day");
}
Loops
// for loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
// while loop
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
// do...while loop
let j = 0;
do {
console.log(j);
j++;
} while (j < 5);
// for...of loop (for arrays)
let colors = ["red", "green", "blue"];
for (let color of colors) {
console.log(color);
}
// for...in loop (for objects)
let person = {
name: "John",
age: 30,
};
for (let key in person) {
console.log(key + ": " + person[key]);
}
Functions
// Function declaration
function greet(name) {
return "Hello, " + name;
}
console.log(greet("John"));
// Function expression
const add = function (x, y) {
return x + y;
};
console.log(add(5, 3));
// Arrow function
const multiply = (x, y) => {
return x * y;
};
console.log(multiply(4, 3));
// Shorter arrow function
const divide = (x, y) => x / y;
console.log(divide(10, 2));
Objects
// Object literal
let person = {
firstName: "John",
lastName: "Doe",
age: 30,
fullName: function () {
return this.firstName + " " + this.lastName;
},
};
console.log(person.fullName());
// Adding a property
person.country = "USA";
// Removing a property
delete person.age;
Arrays
// Array literal
let fruits = ["Apple", "Banana", "Mango"];
// Accessing elements
console.log(fruits[0]); // Apple
// Adding an element
fruits.push("Orange");
// Removing an element
fruits.pop();
// Iterating over an array
fruits.forEach(function (fruit) {
console.log(fruit);
});
Array Methods
let numbers = [1, 2, 3, 4, 5];
// map
let doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
// filter
let even = numbers.filter(num => num % 2 === 0);
console.log(even); // [2, 4]
// reduce
let sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // 15
// find
let firstEven = numbers.find(num => num % 2 === 0);
console.log(firstEven); // 2
// findIndex
let firstEvenIndex = numbers.findIndex(num => num % 2 === 0);
console.log(firstEvenIndex); // 1
// includes
let hasThree = numbers.includes(3);
console.log(hasThree); // true
// slice
let subset = numbers.slice(1, 3);
console.log(subset); // [2, 3]
// splice
numbers.splice(1, 2, 10, 20);
console.log(numbers); // [1, 10, 20, 4, 5]
Promises
// Creating a promise
let promise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Promise resolved!");
} else {
reject("Promise rejected!");
}
});
// Using a promise
promise
.then(message => {
console.log(message);
})
.catch(error => {
console.error(error);
});
Async/Await
// Async function
async function fetchData() {
let response = await fetch("https://api.example.com/data");
let data = await response.json();
console.log(data);
}
// Calling async function
fetchData();
Classes
// Class declaration
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
}
}
// Creating an instance
let john = new Person("John", 30);
console.log(john.greet());
Inheritance
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
let dog = new Dog("Rex");
dog.speak(); // Rex barks.
Modules
// Exporting a module (math.js)
export function add(x, y) {
return x + y;
}
// Importing a module (main.js)
import { add } from "./math.js";
console.log(add(2, 3)); // 5
Destructuring
// Array destructuring
let [first, second] = ["red", "green", "blue"];
console.log(first); // red
console.log(second); // green
// Object destructuring
let person = { name: "John", age: 30 };
let { name, age } = person;
console.log(name); // John
console.log(age); // 30
Spread and Rest
// Spread operator
let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5, 6];
console.log(arr2); // [1, 2, 3, 4, 5, 6]
let obj1 = { a: 1, b: 2 };
let obj2 = { ...obj1, c: 3 };
console.log(obj2); // { a: 1, b: 2, c: 3 }
// Rest parameter
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
Template Literals
let name = "John";
let age = 30;
let message = `My name is ${name} and I am ${age} years old.`;
console.log(message);
Error Handling
try {
// Code that may throw an error
throw new Error("Something went wrong!");
} catch (error) {
console.error(error.message);
} finally {
console.log("This will always run.");
}
Fetch API
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));