Launch offer
Business website $150 USD Custom plugin $200 USD Ready in 5 days
Get a quote
JavaScript

JavaScript Complete Tutorial (101 Topics with DOM, Async & Final Project)

Complete JavaScript tutorial covering syntax, functions, DOM, events, async/await, Fetch, modules, security, and a final interactive web application project.

This complete JavaScript tutorial covers 101 topics — from language fundamentals and functions to DOM, events, async/await, modules, security, and a final interactive web application project.

Course roadmap

1. Introduction to JavaScript

JavaScript powers interactive websites and modern full-stack apps. This series covers syntax, functions, OOP, DOM/events, storage, async/await, modules, and a complete JS web app project.

  1. Learn syntax and core language features.
  2. Build interactive DOM features.
  3. Ship a complete JavaScript web application.

Learning path

Syntax + data + control flow
Functions + scope + OOP
DOM + events + forms
Async + Fetch + modules
Debugging + security
Final JS web app

2. What is JavaScript?

JavaScript runs in browsers and on servers (Node.js). It is multi-paradigm: procedural, object-oriented, and functional styles all appear in real code.

Where JS runs

Browsers (DOM, Fetch)
Node.js / Deno / Bun
Embedded runtimes

3. Features of JavaScript

Key traits include closures, async promises, and a massive ecosystem via npm.

Feature highlights

First-class functions
Closures
Prototypal inheritance
Event loop / async
Huge package ecosystem

4. JavaScript vs Java

Java is statically typed and class-based for VMs; JavaScript is dynamically typed and prototype-based for web/runtime scripting (with modern class syntax sugar).

Quick compare

Java → compiled bytecode, strong typing
JS → interpreted/JIT, dynamic typing
Different ecosystems & use cases
Name similarity is historical branding

5. Installing and Setting Up JavaScript

You can start with only a browser + HTML file; Node unlocks npm and modern tooling.

  1. Install a code editor.
  2. Create an HTML + JS file pair.
  3. Optionally install Node.js LTS.

Setup checklist

Modern browser
VS Code / Cursor
Optional: Node LTS + npm
Live Server or simple static server

6. Running JavaScript in the Browser

Prefer external `.js` files with `defer` for maintainability.

Script tag

<script src="app.js" defer></script>

7. JavaScript with HTML

Select elements, listen for events, and update content dynamically.

HTML + JS idea

<button id="save">Save</button>
<script src="app.js" defer></script>

8. JavaScript with CSS

Prefer classList toggles over heavy inline style manipulation.

Toggle class

document.body.classList.toggle('dark');

9. JavaScript Syntax

Use consistent style (semicolons, quotes) and a formatter/linter.

Syntax sample

const name = 'Asha';
console.log(`Hello, ${name}`);

10. Comments in JavaScript

Prefer clear code over noisy comments; explain why when needed.

Comments

// Single line
/* Multi-line
   comment */

11. Variables – var, let and const

const for non-reassigned bindings; let for reassignment; avoid var in modern code.

Declarations

const PI = 3.14;
let count = 0;
count += 1;

12. JavaScript Data Types

Arrays and functions are objects; null is a historical typeof quirk (`object`).

typeof examples

typeof 'hi';      // string
typeof 42;         // number
typeof true;       // boolean
typeof undefined;  // undefined
typeof null;       // object (quirk)
typeof {};         // object

13. Primitive and Non-Primitive Data Types

Mutating a shared object affects all references — a common source of bugs.

Reference tip

const a = { n: 1 };
const b = a;
b.n = 2;
console.log(a.n); // 2

14. Type Conversion in JavaScript

Prefer explicit conversion over relying on coercion.

Conversion

Number('42');      // 42
String(42);        // '42'
Boolean(0);        // false
parseInt('08', 10); // 8

15. Type Coercion in JavaScript

Use === and !== to avoid surprising coercion.

Coercion pitfalls

1 + '2';     // '12'
1 == '1';     // true
1 === '1';    // false
[] == false;  // true (weird)

16. Operators in JavaScript

Know precedence; use parentheses for clarity.

Operator groups

Arithmetic
Assignment
Comparison
Logical
Nullish / optional chaining

17. Arithmetic Operators in JavaScript

Watch floating-point quirks (`0.1 + 0.2`).

Arithmetic

const sum = 2 + 3;
const mod = 10 % 3; // 1
const pow = 2 ** 3; // 8

18. Assignment Operators in JavaScript

Destructuring assignment is covered later — powerful for objects/arrays.

Assignment

let n = 5;
n += 2; // 7
n *= 3; // 21

19. Comparison Operators in JavaScript

Prefer strict equality; know localeCompare for strings when needed.

Comparison

3 === 3;   // true
3 === '3'; // false
'b' > 'a'; // true

20. Logical Operators in JavaScript

&& and || short-circuit — useful for guards.

Logical

const ok = user && user.active;
const name = input ?? 'Guest';
const ready = !loading && !!data;

21. Ternary Operator in JavaScript

Keep ternaries readable — nest sparingly.

Ternary

const label = score >= 50 ? 'Pass' : 'Retry';

22. Conditional Statements in JavaScript

Prefer early returns to reduce deep nesting.

Early return idea

function canEdit(user) {
  if (!user) return false;
  if (!user.active) return false;
  return user.role === 'admin';
}

23. if, else if and else in JavaScript

Always use braces for clarity, even one-liners on teams that require them.

if/else

if (temp > 30) {
  console.log('Hot');
} else if (temp > 20) {
  console.log('Warm');
} else {
  console.log('Cool');
}

24. switch Statement in JavaScript

Don’t forget break (or use return) to avoid fall-through bugs.

switch

switch (status) {
  case 'paid':
    return 'Done';
  case 'pending':
    return 'Waiting';
  default:
    return 'Unknown';
}

25. Loops in JavaScript

Prefer for…of for arrays; avoid for…in on arrays.

Loop choices

for → indexed
for...of → iterable values
while → unknown count
array methods → map/filter/forEach

26. for Loop in JavaScript

Still useful when you need the index or reverse iteration.

for

for (let i = 0; i < items.length; i++) {
  console.log(items[i]);
}

27. while Loop in JavaScript

Ensure the condition eventually becomes false to avoid infinite loops.

while

let n = 3;
while (n > 0) {
  console.log(n);
  n -= 1;
}

28. do-while Loop in JavaScript

Useful for “ask until valid” style flows.

do-while

let x = 0;
do {
  x += 1;
} while (x < 3);

29. break and continue in JavaScript

Use carefully — overuse can reduce readability.

break/continue

for (const n of nums) {
  if (n < 0) continue;
  if (n === 0) break;
  console.log(n);
}

30. Strings in JavaScript

Strings are immutable; methods return new strings.

Strings

const city = 'Mumbai';
const line = `Hello from ${city}`;

31. JavaScript String Methods

Know the difference between slice and substring.

String methods

'  Hi '.trim();
'JavaScript'.includes('Script');
'a,b,c'.split(',');

32. Template Literals in JavaScript

Also enable tagged templates for advanced parsing.

Template literal

const msg = `Order #${id}
Total: ${total}`;

33. Arrays in JavaScript

Arrays are objects with length and powerful methods.

Array

const tags = ['js', 'dom', 'api'];
tags.push('async');

34. JavaScript Array Methods

Prefer immutable patterns (map/filter) over mutating when sharing state.

Array methods

const nums = [1, 2, 3, 4];
const evens = nums.filter((n) => n % 2 === 0);
const doubled = nums.map((n) => n * 2);
const sum = nums.reduce((a, n) => a + n, 0);

35. Objects in JavaScript

Prefer clear property names; nest carefully.

Object

const user = {
  id: 1,
  name: 'Asha',
  active: true,
};

36. JavaScript Object Methods

Object methods help iterate and copy safely.

Object helpers

Object.keys(user);
Object.entries(user);
Object.assign({}, user, { active: false });

37. Destructuring in JavaScript

Works in parameters too — great for readable function signatures.

Destructuring

const { name, id } = user;
const [first, second] = tags;
function greet({ name }) {
  return `Hi ${name}`;
}

38. Spread Operator in JavaScript

Shallow copy only — nested objects stay shared.

Spread

const copy = { ...user, name: 'Sam' };
const merged = [...tags, 'css'];

39. Rest Operator in JavaScript

Rest is the inverse idea of spread in many patterns.

Rest

const [head, ...tail] = [1, 2, 3];
function sum(...nums) {
  return nums.reduce((a, n) => a + n, 0);
}

40. Functions in JavaScript

Functions are values — pass and return them freely.

Function

function add(a, b) {
  return a + b;
}

41. Function Parameters and Arguments

arguments object exists in non-arrow functions — prefer rest params.

Defaults

function greet(name = 'Guest') {
  return `Hello, ${name}`;
}

42. Return Statement in JavaScript

Functions without return yield undefined.

Return

function area(w, h) {
  return w * h;
}

43. Function Expressions in JavaScript

Not hoisted like declarations — order matters.

Expression

const shout = function (msg) {
  return msg.toUpperCase();
};

44. Arrow Functions in JavaScript

Arrow functions don’t bind their own this/arguments — perfect for callbacks, careful as methods.

Arrow

const double = (n) => n * 2;
const add = (a, b) => a + b;

45. Callback Functions in JavaScript

Callback hell led to Promises/async-await — still foundational.

Callback

setTimeout(() => {
  console.log('done');
}, 200);

46. Higher-Order Functions in JavaScript

map/filter/reduce and middleware patterns are HOFs.

HOF

function withLogging(fn) {
  return (...args) => {
    console.log('call', args);
    return fn(...args);
  };
}

47. Scope in JavaScript

let/const are block-scoped; var is function-scoped.

Scope tip

Minimize globals
Prefer block scope
Closures capture scope

48. Global, Function and Block Scope

Blocks ({ }) create scope for let/const.

Block scope

if (true) {
  let x = 1;
}
// x is not visible here

49. Hoisting in JavaScript

let/const are hoisted but uninitialized until the line runs (TDZ).

Hoisting tip

function declarations hoist fully
var hoists as undefined
let/const TDZ until init
Prefer declare before use

50. Closures in JavaScript

Closures power modules, event handlers, and function factories.

Closure

function makeCounter() {
  let n = 0;
  return () => {
    n += 1;
    return n;
  };
}
const next = makeCounter();

51. Execution Context in JavaScript

Helps explain scope, this, and stack traces when debugging.

Context idea

Global context
Function contexts on call stack
Creation phase + execution phase

52. JavaScript this Keyword

Methods, constructors, explicit binding, and arrows each behave differently.

this tip

const obj = {
  name: 'Site',
  greet() {
    return this.name;
  },
};

53. call(), apply() and bind() in JavaScript

bind returns a new function; call/apply invoke immediately.

bind example

const greet = obj.greet.bind(obj);
setTimeout(greet, 0);

54. Object-Oriented JavaScript

Modern JS class syntax is sugar over prototypes.

OOP pillars in JS

Encapsulation
Inheritance
Polymorphism
Prototypes under the hood

55. Classes and Objects in JavaScript

Keep classes focused; prefer composition when inheritance gets deep.

Class

class User {
  constructor(name) {
    this.name = name;
  }
  greet() {
    return `Hi ${this.name}`;
  }
}
const u = new User('Asha');

56. Constructors in JavaScript

Validate inputs early; don’t do heavy async work in constructors.

Constructor tip

Set required fields
Validate args
Avoid async constructors
Use factories if needed

57. Inheritance in JavaScript

Prefer shallow hierarchies and clear is-a relationships.

extends

class Admin extends User {
  constructor(name, level) {
    super(name);
    this.level = level;
  }
}

58. Encapsulation in JavaScript

Public API small; private state protected.

Private field

class Counter {
  #n = 0;
  inc() {
    this.#n += 1;
    return this.#n;
  }
}

59. Polymorphism in JavaScript

Duck typing is common: if it has .render(), you can render it.

Polymorphism idea

Shared method names
Override in subclasses
Or structural typing via interfaces/shapes

60. Prototypes and Prototype Chain

When a property is missing, JS walks the prototype chain.

Prototype tip

const proto = { greet() { return 'hi'; } };
const obj = Object.create(proto);
obj.greet();

61. DOM Introduction

JS reads/updates the DOM to make pages interactive.

DOM idea

document
 → html
   → body
     → elements / text nodes

62. Selecting HTML Elements with JavaScript

Prefer querySelector APIs for modern code.

Select

const btn = document.querySelector('#save');
const items = document.querySelectorAll('.item');

63. Changing HTML Content with JavaScript

Prefer textContent for untrusted data — innerHTML can enable XSS if misused.

Content update

title.textContent = 'Saved';
// Avoid innerHTML with untrusted input

64. Changing CSS with JavaScript

classList is usually cleaner than many style.* assignments.

classList

panel.classList.add('is-open');
panel.classList.toggle('is-open');

65. Creating and Removing DOM Elements

Use DocumentFragment for many inserts.

Create/remove

const li = document.createElement('li');
li.textContent = 'Item';
list.append(li);
li.remove();

66. DOM Traversal in JavaScript

closest() is excellent for event delegation roots.

Traversal

el.parentElement;
el.children;
el.closest('.card');

67. JavaScript Events

Events drive interactive UIs — know preventDefault and stopPropagation.

Event idea

User events: click, input, keydown
Form: submit
Window: resize, load

68. Event Listeners in JavaScript

Use { once: true } or AbortController for cleanup patterns.

Listener

btn.addEventListener('click', onSave);
// later: btn.removeEventListener('click', onSave);

69. Event Bubbling and Capturing

Most handlers use bubble phase (default).

Propagation

Capturing (top → target)
Target
Bubbling (target → top)
addEventListener(type, fn, true) for capture

70. Event Delegation in JavaScript

Scales for dynamic lists — check event.target.

Delegation

list.addEventListener('click', (e) => {
  const item = e.target.closest('li');
  if (!item || !list.contains(item)) return;
  console.log(item.textContent);
});

71. Form Handling in JavaScript

Prevent default submit to handle via Fetch.

Form submit

form.addEventListener('submit', (e) => {
  e.preventDefault();
  const data = new FormData(form);
  console.log(Object.fromEntries(data.entries()));
});

72. Form Validation in JavaScript

Show accessible errors; never trust only client-side validation.

Validation tip

if (!form.checkValidity()) {
  form.reportValidity();
  return;
}

73. Regular Expressions in JavaScript

Keep regex readable; comment complex patterns.

RegExp

const emailOk = /^[^s@]+@[^s@]+.[^s@]+$/.test(email);

74. Browser Storage in JavaScript

Don’t store secrets in web storage — XSS can read it.

Storage choices

localStorage → persistent
sessionStorage → tab session
cookies → sent to server (rules apply)

75. Local Storage in JavaScript

JSON.stringify/parse objects; handle quota errors.

localStorage

localStorage.setItem('theme', 'dark');
const theme = localStorage.getItem('theme');

76. Session Storage in JavaScript

Useful for wizard progress within a tab.

sessionStorage

sessionStorage.setItem('step', '2');

77. Cookies in JavaScript

document.cookie is stringly — use libraries or server-set security flags.

Cookie tip

Secure + SameSite for sensitive cookies
HttpOnly for session cookies (server-set)
Minimize JS-accessible auth tokens

78. JSON in JavaScript

Validate shape after parse — don’t assume API trust.

JSON

const text = JSON.stringify(user);
const data = JSON.parse(text);

79. Date and Time in JavaScript

Be careful with timezones; prefer libraries for complex calendars.

Date

const now = new Date();
now.toISOString();

80. Math Object in JavaScript

Math.random is not cryptographic — use Web Crypto for secure tokens.

Math

Math.max(1, 5, 3);
Math.round(4.5);
Math.floor(Math.random() * 10);

81. Error Handling in JavaScript

Create meaningful Error messages; don’t swallow errors silently.

Throw

function assertAge(age) {
  if (age < 0) throw new Error('Invalid age');
}

82. try, catch, finally in JavaScript

finally runs for cleanup whether errors occur or not.

try/catch

try {
  JSON.parse(text);
} catch (err) {
  console.error(err);
} finally {
  console.log('done');
}

83. Promises in JavaScript

Promise.all / allSettled / race are essential tools.

Promise

const p = fetch('/api/items').then((r) => r.json());

84. async and await in JavaScript

Always try/catch awaited failures; don’t forget loading states in UI.

async/await

async function loadItems() {
  const res = await fetch('/api/items');
  if (!res.ok) throw new Error('Request failed');
  return res.json();
}

85. Fetch API in JavaScript

Check res.ok; set headers/body for POST/JSON.

Fetch POST

const res = await fetch('/api/items', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Book' }),
});

86. AJAX in JavaScript

Modern AJAX is typically Fetch/XHR behind the scenes.

AJAX idea

Async request
Update DOM with response
Handle loading/error states
Today: prefer Fetch

87. REST API Integration with JavaScript

Centralize base URL, auth headers, and JSON parsing.

API client sketch

async function api(path, options = {}) {
  const res = await fetch(`/api${path}`, {
    headers: { 'Content-Type': 'application/json', ...(options.headers || {}) },
    ...options,
  });
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

88. HTTP Requests in JavaScript

Understand CORS constraints and preflights at a high level.

HTTP methods

GET read
POST create
PUT/PATCH update
DELETE remove
Handle 4xx/5xx explicitly

89. ES6 Introduction

let/const, arrows, classes, modules, promises — the modern baseline.

ES6 highlights

let/const
Arrow functions
Classes
Modules
Promises
Template literals
Destructuring

90. ES6+ Features in JavaScript

Check target environments before using the newest syntax untranspiled.

Modern syntax

const city = user?.address?.city ?? 'Unknown';
const nums = [1, 2, 3].with?.(0, 99); // newer APIs vary by support

91. JavaScript Modules

Modules are deferred/strict by default in browsers.

Module script

<script type="module" src="main.js"></script>

92. import and export in JavaScript

Prefer named exports for better refactoring in many codebases.

import/export

// math.js
export const add = (a, b) => a + b;

// main.js
import { add } from './math.js';

93. CommonJS vs ES Modules

Browsers use ESM; Node supports both with caveats.

Compare

CJS: require / module.exports
ESM: import / export
Node: "type": "module" or .mjs
Don't mix casually

94. npm and Package Management

Pin versions thoughtfully; audit dependencies.

npm basics

npm init -y
npm install lodash
npm uninstall lodash

95. JavaScript Debugging

Reproduce first, then bisect — don’t randomly rewrite.

Debug tip

Reproduce reliably
Read stack traces
Breakpoints over console spam
Fix root cause

96. Browser Developer Tools for JavaScript

Network tab is essential for Fetch/API debugging.

DevTools map

Elements → DOM/CSS
Console → logs/errors
Sources → breakpoints
Network → HTTP
Application → storage

97. JavaScript Performance Optimization

Measure with Performance panel before optimizing blindly.

Perf tips

Debounce resize/input
DocumentFragment for many DOM inserts
Avoid long main-thread tasks
Code-split large bundles
Lazy-load non-critical scripts

98. JavaScript Security Best Practices

Never trust client-side checks alone; sanitize/escape untrusted HTML.

Security checklist

textContent over unsafe innerHTML
CSP where possible
Don't store secrets in JS/localStorage
Validate server-side
Depend on vetted libs

99. JavaScript Interview Questions

Be ready for closures, this, event loop, promises, and prototypal inheritance.

Sample Q&A

Q: var vs let/const?
A: var is function-scoped; let/const are block-scoped; const can't reassign binding.

Q: Closure?
A: Function retaining access to outer scope variables.

Q: == vs ===?
A: == coerces; === is strict.

100. Real-World JavaScript Projects

Each project should include HTML/CSS structure, state, and Fetch or storage.

Project ideas

Todo list + localStorage
Quiz app
Weather/search UI via API
Multi-step form wizard
Kanban board (drag/drop optional)

101. Final Project – Complete JavaScript Web Application

Ship a polished app (e.g., task manager or recipe finder): semantic HTML, responsive CSS, modular ES modules, state management, form validation, Fetch or localStorage persistence, error/loading states, and a short README.

  1. Define the app and data model.
  2. Build UI + state modules.
  3. Add persistence and validation.
  4. Polish UX states and document the project.

Final project scope

1. App idea + user flows
2. Semantic HTML + responsive CSS
3. ES modules structure
4. UI rendering + events
5. Form validation
6. Persistence (API and/or localStorage)
7. Loading/empty/error states
8. Basic accessibility (labels, focus)
9. README + screenshots

Suggested structure

index.html
styles.css
js/
  main.js
  state.js
  ui.js
  api.js

Conclusion

You now have a full JavaScript path: language core, DOM interactivity, asynchronous programming, and modular app structure. Finish the final web application project to turn the lessons into a portfolio-ready build.

Leave a reply

Your email address will not be published. Required fields are marked *