Documentation & Learning Guide
A complete, student-friendly guide to JavaScript — from your very first console.log to advanced async patterns. Built to run beautifully on any smartphone.
Using the HirenJS Editor
A quick tour of every feature so you can get the most out of your coding sessions — even on a small screen.
On phones, HirenJS shows a bottom action bar for the most-used actions so you don't have to scroll to reach buttons.
| Button | Action |
|---|---|
| ▶ Run (yellow circle) | Execute your code — output appears in the Console panel below. |
| ↩ Undo | Undo the last edit. |
| 🗑 Clear | Wipe the editor clean (with confirmation). |
| ✨ Format | Auto-indent your code. |
| 🎨 Theme | Cycle through 6 editor colour themes. |
| Shortcut | Action |
|---|---|
Ctrl + Enter | Run code |
Ctrl + Shift + F | Format code |
Ctrl + K | Open snippet library |
Ctrl + L | Clear output |
Ctrl + Z / Y | Undo / Redo |
Ctrl + / | Toggle comment |
Variables & Data Types
Variables store data. Understanding the three keywords — var, let, const — and the different data types is your very first step in JavaScript.
🔒 const
Use for values that never change. Best practice — always start with const.
🔄 let
Use when the value will change later in your program. Block-scoped.
⚠️ var
Old way — avoid in modern code. Function-scoped and can cause confusing bugs.
📐 Scope
let and const are block-scoped (inside { }). var leaks out of blocks.
// ── const: value that won't change ────────────────── const name = "Hiren"; const PI = 3.14159; // ── let: value that can change ────────────────────── let score = 0; score = 100; // ✅ allowed // ── Data types ────────────────────────────────────── const num = 42; // Number const text = "Hello!"; // String const flag = true; // Boolean const empty = null; // Null (intentional empty) let undef; // Undefined (not assigned) // ── Template literals ─────────────────────────────── const greeting = `Hello, ${name}! Score: ${score}`; console.log(greeting); console.log(typeof num, typeof text, typeof flag);
const first. Switch to let only if you later need to reassign the variable. Never use var in new code.Operators
Operators let you do math, compare values, and combine logic. They're the building blocks of every expression.
// Arithmetic console.log(10 + 3); // 13 console.log(10 - 3); // 7 console.log(10 * 3); // 30 console.log(10 / 3); // 3.333… console.log(10 % 3); // 1 (remainder) console.log(2 ** 8); // 256 (power) // Comparison — always use === not == console.log(5 === 5); // true console.log(5 !== 4); // true console.log(10 > 5); // true // Logical console.log(true && false); // false (AND) console.log(true || false); // true (OR) console.log(!true); // false (NOT)
== does type coercion which causes tricky bugs. For example "5" == 5 is true with == but false with ===. Always use ===.Conditionals
Make decisions in your code with if/else and switch.
const score = 85; // if / else if / else if (score >= 90) { console.log("Grade: A"); } else if (score >= 75) { console.log("Grade: B"); } else { console.log("Grade: C"); } // Ternary — short one-liner if/else const result = score >= 50 ? "Pass" : "Fail"; console.log(result); // Switch const day = "Monday"; switch (day) { case "Monday": console.log("Start of week!"); break; case "Friday": console.log("Weekend soon!"); break; default: console.log("Midweek grind"); }
Loops
Repeat actions without repeating yourself. Loops are one of the most powerful tools in programming.
// for loop for (let i = 1; i <= 5; i++) { console.log(`Count: ${i}`); } // while loop let n = 0; while (n < 3) { console.log("n =", n); n++; } // for...of — great for arrays const fruits = ["Mango", "Apple", "Banana"]; for (const fruit of fruits) { console.log("🍎", fruit); } // forEach — array method style fruits.forEach((fruit, index) => { console.log(index, fruit); });
Functions
Functions are reusable blocks of code. They are the most important building block of any JavaScript program.
// 1. Function Declaration (hoisted — works before defined) function add(a, b) { return a + b; } console.log(add(3, 4)); // 7 // 2. Arrow Function (modern, concise) const multiply = (a, b) => a * b; console.log(multiply(5, 6)); // 30 // 3. Default parameters const greet = (name = "Student") => `Hello, ${name}!`; console.log(greet()); // Hello, Student! console.log(greet("Hiren")); // Hello, Hiren! // Closure — function that remembers outer variable function makeCounter() { let count = 0; return () => ++count; } const counter = makeCounter(); console.log(counter(), counter(), counter()); // 1 2 3
Arrays
Arrays hold ordered lists of data. Master map, filter, and reduce and you unlock 80% of real-world JavaScript.
const nums = [1,2,3,4,5,6,7,8]; // map — transform every element const doubled = nums.map(n => n * 2); console.log("Doubled:", doubled); // filter — keep only matching elements const evens = nums.filter(n => n % 2 === 0); console.log("Evens:", evens); // reduce — collapse to single value const sum = nums.reduce((acc, n) => acc + n, 0); console.log("Sum:", sum); // find, some, every console.log(nums.find(n => n > 5)); // 6 console.log(nums.some(n => n > 7)); // true console.log(nums.every(n => n > 0)); // true console.log([...nums].reverse()); // [8,7,6,5,4,3,2,1]
Objects
Objects store data as key-value pairs. They are the fundamental data structure of JavaScript.
const student = { name: "Hiren", age: 22, city: "Ahmedabad", greet: function() { return `Hi, I'm ${this.name}`; } }; // Access properties console.log(student.name); // Hiren console.log(student["city"]); // Ahmedabad console.log(student.greet()); // Hi, I'm Hiren // Destructuring const { name, age } = student; console.log(name, age); // Hiren 22 // Spread — copy / merge objects const updated = { ...student, age: 23 }; console.log(updated);
ES6+ Modern Features
ES6 (2015) and later added dozens of powerful features. These are the ones you'll use every single day.
// Optional chaining (?.) — safe property access const user = null; console.log(user?.name); // undefined (no crash!) // Nullish coalescing (??) — default values const val = null ?? "default"; console.log(val); // "default" // Spread & rest const sum = (...nums) => nums.reduce((a,b) => a+b,0); console.log(sum(1,2,3,4)); // 10 // Array / Object destructuring with rename const [first, , third] = [10,20,30]; console.log(first, third); // 10 30 // Short-circuit evaluation const isLoggedIn = true; isLoggedIn && console.log("Welcome back!");
Async & Promises
JavaScript runs on a single thread. Async lets you handle time-consuming tasks (like fetching data) without freezing the page.
// ── Promises ───────────────────────────────────────── const fetchUser = () => new Promise((resolve, reject) => { setTimeout(() => resolve({ name: "Hiren", role: "Dev" }), 500); }); // ── async/await (cleaner syntax) ───────────────────── async function loadUser() { try { console.log("Loading…"); const user = await fetchUser(); console.log("User:", user); } catch (err) { console.error("Error:", err); } } loadUser(); // ── Real fetch example ─────────────────────────────── async function getJoke() { const res = await fetch("https://v2.jokeapi.dev/joke/Programming?type=single"); const data = await res.json(); console.log("Joke:", data.joke); } getJoke();
Classes & Object-Oriented Programming
Classes let you create objects from a blueprint. Inheritance, encapsulation, and polymorphism are the pillars of OOP.
class Animal { #name; // private field constructor(name, sound) { this.#name = name; this.sound = sound; } speak() { return `${this.#name} says ${this.sound}!`; } get name() { return this.#name; } } class Dog extends Animal { constructor(name) { super(name, "Woof"); } fetch() { return `${this.name} fetches the ball! 🎾`; } } const dog = new Dog("Buddy"); console.log(dog.speak()); // Buddy says Woof! console.log(dog.fetch()); // Buddy fetches the ball! 🎾 console.log(dog instanceof Animal); // true
Error Handling
Errors happen. Good code handles them gracefully instead of crashing.
// try / catch / finally function divide(a, b) { if (b === 0) throw new Error("Division by zero!"); return a / b; } try { console.log(divide(10, 2)); // 5 console.log(divide(5, 0)); // throws! } catch (err) { console.error("Caught:", err.message); } finally { console.log("Always runs ✔"); } // Custom error types class ValidationError extends Error { constructor(msg) { super(msg); this.name = "ValidationError"; } } try { throw new ValidationError("Name cannot be empty"); } catch (e) { console.log(e.name, "-", e.message); }
DOM Manipulation
The DOM (Document Object Model) lets JavaScript talk to your HTML. Use the HTML Preview tab in HirenJS to experiment with DOM code!
<button id="btn">Click me!</button> <p id="output"></p> <script> const btn = document.getElementById("btn"); const output = document.getElementById("output"); let count = 0; btn.addEventListener("click", () => { count++; output.textContent = `Clicked ${count} time(s)!`; btn.style.background = `hsl(${count*40},80%,60%)`; }); </script>
Design Patterns
Patterns are proven solutions to common problems. Learning them makes you think like an experienced developer.
// ── Singleton ───────────────────────────────────────── const Config = (() => { let instance; return { getInstance: () => { if (!instance) instance = { theme: "dark" }; return instance; } }; })(); console.log(Config.getInstance().theme); // dark // ── Observer (pub/sub) ──────────────────────────────── class EventBus { constructor() { this.events = {}; } on(e, fn) { (this.events[e] ||= []).push(fn); } emit(e, data) { (this.events[e] || []).forEach(fn => fn(data)); } } const bus = new EventBus(); bus.on("login", u => console.log("Logged in:", u)); bus.emit("login", "Hiren");
JavaScript Cheatsheet
Quick-reference for the most important JavaScript patterns. Bookmark this page!
You've reached the end of the guide!
Ready to apply what you've learned? Open the editor and start building something amazing.
Snippet Library Guide
HirenJS ships with 12 ready-made code snippets. Here's what each one does and how to use it as a learning exercise.
| Snippet | Tag | What to try |
|---|---|---|
| Hello World | Basic | Change the message. Try console.warn() and console.error() instead of log. |
| Arrow Function | Function | Add a third parameter. Try calling the function without arguments to see undefined. |
| Array Methods | Array | Chain filter and map together. Change the filter condition. |
| Promises & Async | Async | Reduce the setTimeout delay. Try rejecting the promise and catching the error. |
| Classes & OOP | OOP | Add a Cat class that extends Animal with a different sound. |
| Destructuring | ES6 | Add a default value in the destructuring. Rename a key. |
| Spread & Rest | ES6 | Try spreading 3 arrays together. Add type checking to the sum function. |
| Fetch API | Network | Try fetching from a different API. Add loading state before the fetch. |
| Fibonacci | Algorithm | Rewrite it with a loop instead of recursion. Compare performance. |
| Debounce | Utility | Change the delay. Try using it with a simulated search input. |
| Try/Catch | Error | Add a custom error class. Try throwing a string instead of an Error object. |
Ctrl+K or tap the 📦 icon in the top right. Use the search box to find snippets by name or tag. Click any snippet to insert it instantly.Keyboard Shortcuts
All keyboard shortcuts available in the HirenJS editor.
| Action | Shortcut | Mobile |
|---|---|---|
| Run code | Ctrl + Enter | ▶ Run button |
| Format / indent code | Ctrl + Shift + F | ✨ Format button |
| Open snippet library | Ctrl + K | 📦 icon |
| Clear output console | Ctrl + L | — |
| Undo | Ctrl + Z | ↩ Undo button |
| Redo | Ctrl + Y | — |
| Comment / uncomment line | Ctrl + / | — |
| Select all | Ctrl + A | — |
| Copy selected | Ctrl + C | — |
| Find in file | Ctrl + F | — |
| Toggle keyboard shortcuts | Ctrl + ? (menu) | ⌨️ icon |