JAVASCRIPT (JS)

Develop dynamic and interactive web pages using JavaScript
fundamentals, DOM manipulation, and ES6+ features.

JavaScript Basics

JS Syntax

JavaScript statements are composed of values, operators, expressions, keywords and comments. They are executed from top to bottom and left to right.

// one‑line comment
/* multi‑line
   comment */
let x = 5 + 6; // statement ends with semicolon (optional)
console.log(x);
JS Variables, let, const

Variables hold data values. Use let for block‑scoped mutable variables, const for constants, and var (legacy) for function‑scoped variables.

let name = "Alice";
const PI = 3.1416;
var legacy = true; // avoid in ES6+ code

Operators & Data Types

Arithmetic & Assignment

Arithmetic: + - * / % **; Assignment combines = with arithmetic (+= etc).

let counter = 10;
counter += 2; // 12
Data Types

Primitive: Number, String, Boolean, Null, Undefined, Symbol, BigInt. Complex: Object.

typeof 42;           // "number"
typeof "hello";     // "string"
typeof Symbol();     // "symbol"
typeof 10n;          // "bigint"

Control Structures

Conditionals
if (x > 0) {
  // ...
} else if (x === 0) {
  // ...
} else {
  // ...
}

switch(day) {
  case 1: msg = "Mon"; break;
  default: msg = "Unknown";
}
Loops
for (let i = 0; i < arr.length; i++) {}
for (const key in obj) {}
for (const value of arr) {}
let i = 0;
while (i < 5) { i++; }

break exits the loop; continue skips to next iteration.

Functions & Scope

Declarations & Expressions
function add(a,b){ return a+b; }
const multiply = function(a,b){ return a*b; };
const divide = (a,b) => a/b; // arrow

Arrow functions capture this from outer scope.

Parameters & Defaults
function greet(name = "Guest"){
  console.log(`Hello ${name}`);
}
Closures

A closure remembers variables from its creation context.

function makeCounter(){
  let count = 0;
  return () => ++count; // arrow closes over count
}
const c1 = makeCounter();
c1(); // ➜ 1

Objects

Object Literals & Properties
const user = {
  firstName: "Ada",
  lastName : "Lovelace",
  get fullName(){ return `${this.firstName} ${this.lastName}`; }
};
console.log(user.fullName);
Constructors & Prototypes
function Person(name){ this.name = name; }
Person.prototype.sayHi = function(){ console.log(`Hi, I'm ${this.name}`); };
new Person("Bob").sayHi();
ES6 Classes
class Animal {
  constructor(kind){ this.kind = kind; }
  speak(){ console.log(`${this.kind} sound`); }
}
class Dog extends Animal {
  speak(){ console.log("Woof!"); }
}
new Dog("Dog").speak();

Strings & Numbers

String Methods
"hello".toUpperCase();
"hello".includes("ell");
`Template ${var}`;
Number & BigInt
Number.parseFloat("3.14");
(9007199254740993n + 1n).toString();

Arrays

Core Methods
const arr = [3,1,4];
arr.push(2);            // add
arr.sort();             // sort
arr.filter(x=>x>2);     // iteration
Typed Arrays
const bytes = new Uint8Array([255,128,64]);

Dates & Math

Date Object
const now = new Date();
now.getFullYear();
now.toLocaleDateString();
Math & Random
Math.max(5,10);
Math.random(); // 0 ≤ x < 1

Booleans & Comparisons

== performs type‑coercive comparison; === is strict.

Bitwise operators manipulate 32‑bit integers: & | ^ ~ << >>.

Errors & Debugging

try {
  JSON.parse('{ bad json }');
} catch (e) {
  console.error(e.message);
} finally {
  console.log("always runs");
}

Scope & Advanced Language Features

Scope is where variables are accessible. Hoisting moves declarations to top of scope. Strict Mode adds stricter parsing ('use strict';).

this refers to the calling context; arrow functions do not bind their own this.

Modules & Asynchronous JS

ES Modules
// api.js
export function sum(a,b){ return a+b; }
// main.js
import { sum } from './api.js';
Promises & async/await
function fetchJson(url){
  return fetch(url).then(r => r.json());
}
async function getData(){
  const posts = await fetchJson('https://jsonplaceholder.typicode.com/posts');
  console.log(posts[0]);
}

HTML DOM

DOM Document & Elements
document.title = "New Title";
const btn = document.querySelector('#btn');
btn.addEventListener('click', () => alert('Hi'));
DOM Navigation & Collections

parentNode, children, nextElementSibling, querySelectorAll return NodeLists.

Browser BOM

Interacting with browser objects: window, location, history, screen, navigator.

console.log(window.innerWidth);
alert('Popup!');

AJAX / Fetch

XMLHttpRequest (legacy)
const xhr = new XMLHttpRequest();
xhr.onload = () => console.log(xhr.responseText);
xhr.open('GET','/data');
xhr.send();
Fetch API (modern)
fetch('/data')
  .then(r => r.json())
  .then(data => console.log(data));

JSON

JavaScript Object Notation is a lightweight data‑exchange format.

const obj = {x:10, y:20};
const txt = JSON.stringify(obj); // "{"x":10,"y":20}"
console.log(JSON.parse(txt).y);  // 20

Sets, Maps, Iterables

// Set
const s = new Set([1,2,2]); // {1,2}
// Map
const m = new Map([['a',1]]);
for (const [k,v] of m) { console.log(k,v); }

Regular Expressions

const re = /\b\w{4}\b/g;
"Java Script".match(re); // ["Java","Script"]

Graphics & Visualization

Canvas 2D API, SVG, and libraries like Chart.js and D3.js enable drawing and data visualisation.

// Canvas example
const canvas = document.getElementById('cv');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'skyblue';
ctx.fillRect(10,10,100,50);

Best Practices & Performance

  • Prefer const/let over var.
  • Use strict equality (===).
  • Avoid global variables; use modules.
  • Debounce/throttle expensive events (resize, scroll).
  • Measure performance with Performance API or browser devtools.

Reference Links

MDN JavaScript Documentation

JavaScript.info