JAVASCRIPT (JS)
Develop dynamic and interactive web pages using JavaScript
fundamentals, DOM manipulation, and ES6+ features.
JavaScript Basics
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);
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 combines
= with arithmetic (+= etc).
let counter = 10;
counter += 2; // 12
Primitive: Number, String, Boolean, Null, Undefined, Symbol, BigInt. Complex: Object.
typeof 42; // "number"
typeof "hello"; // "string"
typeof Symbol(); // "symbol"
typeof 10n; // "bigint"
Control Structures
if (x > 0) {
// ...
} else if (x === 0) {
// ...
} else {
// ...
}
switch(day) {
case 1: msg = "Mon"; break;
default: msg = "Unknown";
}
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
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.
function greet(name = "Guest"){
console.log(`Hello ${name}`);
}
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
const user = {
firstName: "Ada",
lastName : "Lovelace",
get fullName(){ return `${this.firstName} ${this.lastName}`; }
};
console.log(user.fullName);
function Person(name){ this.name = name; }
Person.prototype.sayHi = function(){ console.log(`Hi, I'm ${this.name}`); };
new Person("Bob").sayHi();
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
"hello".toUpperCase();
"hello".includes("ell");
`Template ${var}`;
Number.parseFloat("3.14");
(9007199254740993n + 1n).toString();
Arrays
const arr = [3,1,4];
arr.push(2); // add
arr.sort(); // sort
arr.filter(x=>x>2); // iteration
const bytes = new Uint8Array([255,128,64]);
Dates & Math
const now = new Date();
now.getFullYear();
now.toLocaleDateString();
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
// api.js
export function sum(a,b){ return a+b; }
// main.js
import { sum } from './api.js';
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
document.title = "New Title";
const btn = document.querySelector('#btn');
btn.addEventListener('click', () => alert('Hi'));
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
const xhr = new XMLHttpRequest();
xhr.onload = () => console.log(xhr.responseText);
xhr.open('GET','/data');
xhr.send();
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/letovervar. - Use strict equality (
===). - Avoid global variables; use modules.
-
Debounce/throttle expensive events (
resize,scroll). -
Measure performance with
Performance APIor browser devtools.