1. Variables
let x = 10; // Declare a variable
const PI = 3.14; // Declare a constant
var y = 20; // Declare a variable (old syntax)
2. Data Types
let x = 10; // Number
let y = "Hello"; // String
let z = true; // Boolean
let a = null; // Null
let b = undefined; // Undefined
let c = [1, 2, 3]; // Array
let d = { name: "John", age: 30 }; // Object
3. Operators
let x = 10;
let y = 20;
console.log(x + y); // Addition
console.log(x - y); // Subtraction
console.log(x * y); // Multiplication
console.log(x / y); // Division
console.log(x % y); // Modulus
console.log(x ** y); // Exponentiation
4. Conditional Statements
let x = 10;
if (x > 5) {
console.log("x is greater than 5");
} else {
console.log("x is less than or equal to 5");
}
5. Loops
for (let i = 0; i < 5; i++) {
console.log(i);
}
6. Functions
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("John");
7. Arrays
let fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // Access an element
fruits.push("orange"); // Add an element
fruits.pop(); // Remove an element
8. Objects
let person = { name: "John", age: 30 };
console.log(person.name); // Access a property
person.country = "USA"; // Add a property
delete person.age; // Remove a property
9. DOM Manipulation
let element = document.getElementById("myElement");
element.innerHTML = "Hello, World!";
element.style.color = "red";
10. Events
let button = document.getElementById("myButton");
button.addEventListener("click", function() {
console.log("Button clicked!");
});
11. JSON
let data = { name: "John", age: 30 };
let jsonData = JSON.stringify(data);
console.log(jsonData); // Output: {"name":"John","age":30}
12. AJAX
let xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
13. Promises
let promise = new Promise(function(resolve, reject) {
// Do something
resolve("Success!");
});
promise.then(function(result) {
console.log(result); // Output: Success!
});
14. Async/Await
async function myFunction() {
let result = await myPromise();
console.log(result); // Output: Success!
}
15. ES6 Classes
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
let person = new Person("John", 30);
person.greet(); // Output: Hello, my name is John and I am 30 years old.
16. ES6 Modules
// mymodule.js
export function greet(name) {
console.log(`Hello, ${name}!`);
}
// main.js
import { greet } from "./mymodule.js";
greet("John"); // Output: Hello, John!
17. ES6 Destructuring
let person = { name: "John", age : 30 };
let { name, age } = person; // Destructure properties
console.log(name); // Output: John
console.log(age); // Output: 30
18. Spread Operator
let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5]; // Spread elements into a new array
console.log(arr2); // Output: [1, 2, 3, 4, 5]
19. Rest Parameters
function sum(...numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
console.log(sum(1, 2, 3, 4)); // Output: 10
20. Template Literals
let name = "John";
let greeting = `Hello, ${name}!`; // Use backticks for string interpolation
console.log(greeting); // Output: Hello, John!
21. Arrow Functions
const add = (a, b) => a + b; // Shorter syntax for functions
console.log(add(2, 3)); // Output: 5
22. Set and Map
let mySet = new Set([1, 2, 3, 3]); // Set only stores unique values
console.log(mySet); // Output: Set(3) { 1, 2, 3 }
let myMap = new Map();
myMap.set("name", "John");
console.log(myMap.get("name")); // Output: John
23. Error Handling
try {
throw new Error("Something went wrong!");
} catch (error) {
console.log(error.message); // Output: Something went wrong!
}
24. Local Storage
localStorage.setItem("key", "value"); // Store data
let value = localStorage.getItem("key"); // Retrieve data
console.log(value); // Output: value
25. Session Storage
sessionStorage.setItem("sessionKey", "sessionValue"); // Store session data
let sessionValue = sessionStorage.getItem("sessionKey"); // Retrieve session data
console.log(sessionValue); // Output: sessionValue
26. Fetch API
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data));
27. Event Delegation
document.getElementById("parent").addEventListener("click", function(event) {
if (event.target.matches(".child")) {
console.log("Child clicked!");
}
});
28. Throttle and Debounce
// Throttle function
function throttle(func, limit) {
let lastFunc;
let lastRan;
return function() {
const context = this;
const args = arguments;
if (!lastRan) {
func.apply(context, args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(function() {
func.apply(context, args);
lastRan = Date.now();
}, limit - (Date.now() - lastRan));
}
};
}
// Debounce function
function debounce(func, delay) {
let timeout;
return function() {
const context = this;
const args = arguments;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), delay);
};
}
29. Regular Expressions
let regex = /[a-z]+/; // Regular expression to match lowercase letters
console.log(regex.test("hello")); // Output: true
30. Array Methods
let numbers = [1, 2, 3, 4, 5];
let doubled = numbers.map(num => num * 2); // Map
let filtered = numbers.filter(num => num > 2); // Filter
console.log(doubled); // Output: [2, 4, 6, 8, 10]
console.log(filtered); // Output: [3, 4, 5]
31. String Methods
let str = "Hello, World!";
console.log (str.length); // Output: 13
console.log(str.toUpperCase()); // Output: HELLO, WORLD!
console.log(str.includes("World")); // Output: true
32. Date and Time
let date = new Date();
console.log(date); // Current date and time
console.log(date.getFullYear()); // Output: Current year
33. SetTimeout and SetInterval
setTimeout(() => {
console.log("Executed after 2 seconds");
}, 2000); // Execute after 2 seconds
setInterval(() => {
console.log("Executed every 1 second");
}, 1000); // Execute every 1 second
34. Closures
function outerFunction() {
let outerVariable = "I'm from outer function";
return function innerFunction() {
console.log(outerVariable);
};
}
const innerFunc = outerFunction();
innerFunc(); // Output: I'm from outer function
35. IIFE (Immediately Invoked Function Expression)
(function() {
console.log("I am an IIFE");
})(); // Output: I am an IIFE
36. Prototypes
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
const john = new Person("John");
john.greet(); // Output: Hello, my name is John
37. Object.create()
const animal = {
speak() {
console.log("Animal speaks");
}
};
const dog = Object.create(animal);
dog.speak(); // Output: Animal speaks
38. Object.assign()
const target = { a: 1 };
const source = { b: 2, c: 3 };
const returnedTarget = Object.assign(target, source);
console.log(returnedTarget); // Output: { a: 1, b: 2, c: 3 }
39. Array Destructuring
const arr = [1, 2, 3];
const [first, second] = arr; // Destructure array
console.log(first); // Output: 1
console.log(second); // Output: 2
40. Object Destructuring
const obj = { x: 1, y: 2 };
const { x, y } = obj; // Destructure object
console.log(x); // Output: 1
console.log(y); // Output: 2
41. Spread Syntax with Objects
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // Spread properties into a new object
console.log(obj2); // Output: { a: 1, b: 2, c: 3 }
42. Array.from()
const str = "hello";
const arr = Array.from(str); // Convert string to array
console.log(arr); // Output: ['h', 'e', 'l', 'l', 'o']
43. Array.prototype.includes()
const arr = [1, 2, 3];
console.log(arr.includes(2)); // Output: true
console.log(arr.includes(4)); // Output: false
44. Array.prototype.reduce()
const arr = [1, 2, 3, 4];
const sum = arr.reduce((acc, curr) => acc + curr, 0); // Sum of array elements
console.log(sum); // Output: 10
45. Array.prototype.forEach()
const arr = [1, 2, 3];
arr.forEach(num => console.log(num)); // Output: 1 2 3
46. Array.prototype.find()
const arr = [1, 2, 3, 4];
const found = arr.find(num => num > 2); // Find first element greater than 2
console.log(found); // Output: 3
47. Array.prototype.filter()
const arr = [1 , 2, 3, 4];
const filtered = arr.filter(num => num > 2); // Filter elements greater than 2
console.log(filtered); // Output: [3, 4]
48. Array.prototype.map()
const arr = [1, 2, 3];
const doubled = arr.map(num => num * 2); // Double each element
console.log(doubled); // Output: [2, 4, 6]
49. Array.prototype.some()
const arr = [1, 2, 3, 4];
const hasEven = arr.some(num => num % 2 === 0); // Check if any element is even
console.log(hasEven); // Output: true
50. Array.prototype.every()
const arr = [1, 2, 3, 4];
const allEven = arr.every(num => num % 2 === 0); // Check if all elements are even
console.log(allEven); // Output: false
51. Array.prototype.splice()
const arr = [1, 2, 3, 4];
arr.splice(1, 2); // Remove 2 elements starting from index 1
console.log(arr); // Output: [1, 4]
52. Array.prototype.slice()
const arr = [1, 2, 3, 4];
const sliced = arr.slice(1, 3); // Get elements from index 1 to 3 (not inclusive)
console.log(sliced); // Output: [2, 3]
53. Array.prototype.concat()
const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = arr1.concat(arr2); // Combine two arrays
console.log(combined); // Output: [1, 2, 3, 4]
54. Array.prototype.join()
const arr = [1, 2, 3];
const joined = arr.join(", "); // Join elements into a string
console.log(joined); // Output: "1, 2, 3"
55. String.prototype.split()
const str = "Hello, World!";
const words = str.split(", "); // Split string into an array
console.log(words); // Output: ["Hello", "World!"]
56. String.prototype.replace()
const str = "Hello, World!";
const newStr = str.replace("World", "JavaScript"); // Replace substring
console.log(newStr); // Output: "Hello, JavaScript!"
57. String.prototype.trim()
const str = " Hello, World! ";
const trimmed = str.trim(); // Remove whitespace
console.log(trimmed); // Output: "Hello, World!"
58. String.prototype.charAt()
const str = "Hello";
const char = str.charAt(0); // Get character at index 0
console.log(char); // Output: "H"
59. String.prototype.indexOf()
const str = "Hello, World!";
const index = str.indexOf("World"); // Get index of substring
console.log(index); // Output: 7
60. String.prototype.includes()
const str = "Hello, World!";
const hasWorld = str.includes("World"); // Check if substring exists
console.log(hasWorld); // Output: true
61. Date.prototype.getDate()
const date = new Date();
console.log(date.getDate()); // Get day of the month
62. Date.prototype.getMonth()
const date = new Date();
console.log(date.getMonth()); // Get month (0-11)
63. Date.prototype.getFullYear()
const date = new Date();
console.log(date.getFullYear()); // Get full year
64. Date.prototype.getTime()
const date = new Date();
console.log(date.getTime()); // Get timestamp
65. Date.prototype.setDate()
const date = new Date();
date.setDate(15); // Set day of the month
console.log(date); // Output: Date object with day set to 15
66. Date.prototype.setMonth()
date.setMonth(5); // Set month (0-11)
console.log(date); // Output: Date object with month set to June
67. Date.prototype.setFullYear()
date.setFullYear(2025); // Set full year
console.log(date); // Output: Date object with year set to 2025
68. Date.prototype.toISOString()
console.log(date.toISOString()); // Output: ISO string representation of the date
69. Math Object
console.log(Math.PI); // Output: 3.141592653589793
console.log(Math.sqrt(16)); // Output: 4
console.log(Math.random()); // Output: Random number between 0 and 1
70. Set and Get Cookies
document.cookie = "username=John"; // Set a cookie
console.log(document.cookie); // Get all cookies
71. Fetching Data with Axios
axios.get("https://api.example.com/data")
.then(response => console.log(response.data))
.catch(error => console.error(error));
72. Using Local Storage
localStorage.setItem("key", "value"); // Store data
let value = localStorage.getItem("key"); // Retrieve data
console.log(value); // Output: value
73. Using Session Storage
sessionStorage.setItem("sessionKey", "sessionValue"); // Store session data
let sessionValue = sessionStorage.getItem("sessionKey"); // Retrieve session data
console.log(sessionValue); // Output: sessionValue
74. Using Web Workers
const worker = new Worker("worker.js"); // Create a new web worker
worker.onmessage = function(event) {
console.log(event.data); // Handle message from worker
};
worker.postMessage("Hello, Worker!"); // Send message to worker
75. Using Service Workers
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js')
.then(registration => console.log('Service Worker registered:', registration))
.catch(error => console.error('Service Worker registration failed:', error));
}
76. Using IndexedDB
let request = indexedDB.open("myDatabase", 1);
request.onsuccess = function(event) {
let db = event.target.result;
console.log("Database opened successfully");
};
77. Using Fetch API with Async/Await
async function fetchData() {
try {
let response = await fetch("https://api.example.com/data");
let data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
fetchData();
78. Using the Window Object
console.log(window.innerWidth); // Get the width of the window
console.log(window.innerHeight); // Get the height of the window
79. Using the Document Object
console.log(document.title); // Get the title of the document
document.title = "New Title"; // Set a new title
80. Using the History Object
history.pushState({}, "New Page", "/new-page"); // Add a new entry to the history
81. Using the Location Object
console.log(location.href); // Get the current URL
location.href = "https://www.example.com"; // Redirect to a new URL
82. Using the Navigator Object
console.log(navigator.userAgent); // Get the user agent string
83. Using the Screen Object
console.log(screen.width); // Get the width of the screen
console.log(screen.height); // Get the height of the screen
84. Using the Console Object
console.log("Hello, World!"); // Log a message to the console
console.error("This is an error message"); // Log an error message
console.warn("This is a warning message"); // Log a warning message
85. Using the Debugger
debugger; // Pause execution for debugging
86. Using the Fetch API for POST Requests
fetch("https://api.example.com/data", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ name: "John" })
})
.then(response => response.json())
.then(data => console.log(data));
87. Using the XMLHttpRequest for AJAX
let xhr = new XMLHttpRequest();
xhr.open("POST", "https://api.example.com/data", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send(JSON.stringify({ name: "John" }));
88. Using the Event Object
document.addEventListener("click", function(event) {
console.log(event.target); // Log the clicked element
});
89. Using the Mouse Events
document.addEventListener("mousemove", function(event) {
console.log(`Mouse position: ${event.clientX}, ${event.clientY}`);
});
90. Using the Keyboard Events
document.addEventListener("keydown", function(event) {
console.log(`Key pressed: ${event.key}`);
});
91. Using the Touch Events
document.addEventListener("touchstart", function(event) {
console.log("Touch started");
});
92. Using the Resize Event
window.addEventListener("resize", function() {
console.log("Window resized");
});
93. Using the Scroll Event
window.addEventListener("scroll", function() {
console.log("Scrolled");
});
94. Using the Focus and Blur Events
let input = document.getElementById("myInput");
input.addEventListener("focus", function() {
console.log("Input focused");
});
input.addEventListener("blur", function() {
console.log("Input blurred");
});
95. Using the Change Event
let select = document.getElementById("mySelect");
select.addEventListener("change", function() {
console.log(`Selected value: ${select.value}`);
});
96. Using the Submit Event
let form = document.getElementById("myForm");
form.addEventListener("submit", function(event) {
event.preventDefault(); // Prevent form submission
console.log("Form submitted");
});
97. Using the Load Event
window.addEventListener("load", function() {
console.log("Page fully loaded");
});
98. Using the Unload Event
window.addEventListener("unload", function() {
console.log("Page is unloading");
});
99. Using the BeforeUnload Event
window.addEventListener("beforeunload", function(event) {
event.preventDefault(); // Show confirmation dialog
event.returnValue = ''; // Required for Chrome
});
100. Using the Visibility Change Event
document.addEventListener("visibilitychange", function() {
if (document.hidden) {
console.log("Page is hidden");
} else {
console.log("Page is visible");
}
});