Here are the top 10 examples of JavaScript code snippets that demonstrate different fundamental concepts and functionalities of the language:

1. Variable Declaration
let name = "Alice";
const age = 25;
var isStudent = true;
console.log(name, age, isStudent);
2. Functions
function greet(person) {
return `Hello, ${person}!`;
}
console.log(greet("Bob"));
3. Arrow Functions
const sum = (a, b) => a + b;
console.log(sum(5, 3));
4. Array Methods
let numbers = [1, 2, 3, 4, 5];
let squares = numbers.map(num => num * num);
console.log(squares); // [1, 4, 9, 16, 25]
5. Object Literals
let person = {
name: "Charlie",
age: 30,
greet() {
console.log(`Hi, my name is ${this.name}`);
}
};
person.greet(); // Hi, my name is Charlie
6. Promises
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data fetched successfully!");
}, 2000);
});
promise.then(message => {
console.log(message);
});
7. Async/Await
async function fetchData() {
let data = await fetch('https://jsonplaceholder.typicode.com/todos/1');
let json = await data.json();
console.log(json);
}
fetchData();
8. Event Handling
document.getElementById("myButton").addEventListener("click", () => {
alert("Button was clicked!");
});
9. DOM Manipulation
let newElement = document.createElement("div");
newElement.textContent = "Hello, World!";
document.body.appendChild(newElement);
10. Class
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound`);
}
}
let dog = new Animal("Dog");
dog.speak(); // Dog makes a sound
Top 10 Topic cover in example
These examples cover variable declarations, functions, arrow functions, array methods, object literals, promises, async/await, event handling, DOM manipulation, and classes.