Skip to content
This repository was archived by the owner on Sep 24, 2025. It is now read-only.

Latest commit

 

History

History
117 lines (85 loc) · 2.4 KB

File metadata and controls

117 lines (85 loc) · 2.4 KB

JavaScript Documentation

Introduction

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).

Core Concepts

  • Variables: Store data using let, const, or var.
  • Data Types: String, Number, Boolean, Object, Array, Null, Undefined.
  • Functions: Blocks of code that perform tasks.
  • Control Flow: if, else, switch, loops (for, while).

Example

// Variable declaration
let name = "Alice";

// Function definition
function greet(user) {
  return `Hello, ${user}!`;
}

console.log(greet(name)); // Output: Hello, Alice!

DOM Manipulation

JavaScript can interact with HTML elements:

document.getElementById("myBtn").addEventListener("click", function () {
  alert("Button clicked!");
});

ES6+ Features

  • Arrow functions: const add = (a, b) => a + b;
  • Template literals: Hello, ${name}
  • Destructuring, Spread/Rest operators

Best Practices

  • Use const and let instead of var.
  • Write modular, reusable code.
  • Handle errors with try...catch.

Advanced Topics

Asynchronous JavaScript

  • 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();

Object-Oriented Programming (OOP)

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());

Functional Programming

  • Use functions as first-class citizens.
  • Array methods: map, filter, reduce.
const nums = [1, 2, 3];
const doubled = nums.map((n) => n * 2);

Modules

Organize code into separate files:

// math.js
export function add(a, b) {
  return a + b;
}
// main.js
import { add } from "./math.js";

Debugging JavaScript

  • Use console.log, breakpoints, and browser DevTools.
  • Use linters like ESLint to catch errors early.

Useful Resources