JavaScript Code Examples
// ====================
// VARIABLES & DATA TYPES
// ====================
// Variable declaration
const name = "John"; // string
let age = 30; // number
var isStudent = false; // boolean
let score = null; // null
let undefinedVar; // undefined
// Object
const person = {
firstName: "Jane",
lastName: "Doe",
age: 28
};
// Array
const colors = ["red", "green", "blue"];
// ====================
// FUNCTIONS
// ====================
// Basic function
function greet(name) {
return `Hello, ${name}! `;
}
// Arrow function (ES6)
const addNumbers = (a, b) => a + b;
// Callback function
function processUserInput(callback) {
const name = prompt("Please enter your name:");
callback(name);
}
// ====================
// CONTROL FLOW
// ====================
// If-else statement
if (age >= 18) {
[Link]("You are an adult ");
} else {
[Link]("You are a minor ");
}
// Switch statement
switch (new Date().getDay()) {
case 0:
[Link]("Sunday ");
break;
case 6:
[Link]("Saturday ");
break;
default:
[Link]("Weekday ");
}
// For loop
for (let i = 0; i < 5; i++) {
[Link](`Iteration ${i} `);
}
// ====================
// DOM MANIPULATION
// ====================
// Select element
const button = [Link]("#myButton");
// Event listener
[Link]("click", () => {
[Link]("Button clicked! ");
[Link] = "lightblue";
});
// Create element
const newDiv = [Link]("div");
[Link] = "New element created! ";
[Link](newDiv);
// ====================
// PROMISES & ASYNC/AWAIT
// ====================
// Promise example
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
const success = true; // simulate success/failure
if (success) {
resolve("Data fetched successfully! ");
} else {
reject("Error fetching data! ");
}
}, 2000);
});
// Async/await example
async function getUserData() {
try {
const response = await fetch('[Link]
const data = await [Link]();
[Link](data);
} catch (error) {
[Link]("Error:", error);
}
}
// ====================
// ARRAY METHODS
// ====================
const numbers = [1, 2, 3, 4, 5];
// map()
const doubled = [Link](num => num * 2);
// filter()
const evens = [Link](num => num % 2 === 0);
// reduce()
const sum = [Link]((total, num) => total + num, 0);
// forEach()
[Link](num => [Link](num));
// ====================
// CLASSES (ES6)
// ====================
class Animal {
constructor(name) {
[Link] = name;
}
speak() {
[Link](`${[Link]} makes a noise. `);
}
}
class Dog extends Animal {
speak() {
[Link](`${[Link]} barks. `);
}
}
const myDog = new Dog("Rex");
[Link]();
Key Notes
1. Variables: Use const by default, let when reassignment is needed,
and avoid var
2. Functions: Prefer arrow functions for concise syntax and
proper this binding
3. Async Code: Use promises or async/await for cleaner asynchronous
code
4. DOM: Remember to wait for DOM content to load before
manipulating elements
5. ES6+: Modern JavaScript has many helpful features like classes,
template literals, destructuring, etc.