JavaScript is a versatile, high-level programming language used to create interactive and dynamic web pages. It runs in the browser and on servers (Node.js).
- Variables: Store data using
let,const, orvar. - Data Types: String, Number, Boolean, Object, Array, Null, Undefined.
- Functions: Blocks of code that perform tasks.
- Control Flow:
if,else,switch, loops (for,while).
// Variable declaration
let name = "Alice";
// Function definition
function greet(user) {
return `Hello, ${user}!`;
}
console.log(greet(name)); // Output: Hello, Alice!JavaScript can interact with HTML elements:
document.getElementById("myBtn").addEventListener("click", function () {
alert("Button clicked!");
});- Arrow functions:
const add = (a, b) => a + b; - Template literals:
Hello, ${name} - Destructuring, Spread/Rest operators
- Use
constandletinstead ofvar. - Write modular, reusable code.
- Handle errors with
try...catch.
- Callbacks: Functions passed as arguments.
- Promises: Handle async operations more cleanly.
- Async/Await: Write async code that looks synchronous.
function fetchData() {
return new Promise((resolve) => setTimeout(() => resolve("Done!"), 1000));
}
async function main() {
const result = await fetchData();
console.log(result);
}
main();Use classes and objects to structure code:
class Person {
constructor(name) {
this.name = name;
}
greet() {
return `Hello, I'm ${this.name}`;
}
}
const bob = new Person("Bob");
console.log(bob.greet());- Use functions as first-class citizens.
- Array methods:
map,filter,reduce.
const nums = [1, 2, 3];
const doubled = nums.map((n) => n * 2);Organize code into separate files:
// math.js
export function add(a, b) {
return a + b;
}
// main.js
import { add } from "./math.js";- Use
console.log, breakpoints, and browser DevTools. - Use linters like ESLint to catch errors early.