JavaScript is the language of the browser — every button that reacts, every slider, every live search box on
a website is JavaScript. Learn it once and you can also build mobile apps, desktop apps and servers with
the very same language.
Difficulty: Easy, with sharp edgesGreat for: Websites, apps, serversRun with:node app.js or the browser console (F12)9 chapters · 20+ examples
HTML gives a page its structure, CSS gives it style, and JavaScript gives it behaviour.
It was written in 10 days in 1995 by Brendan Eich and is now the most-used language in the world,
because it runs natively in every browser.
Two ways to run code today
1
Browser console — press F12, open the Console tab, type and press Enter. Fastest way to try a line.
2
Node.js — install it, save a file as app.js, then run node app.js in the terminal.
3
Inside a page, link your file with <script src="app.js"></script> just before the closing </body> tag.
JavaScriptapp.js
// two slashes start a comment
console.log("Hello, Study Hub!");
console.log(2 + 3); // 5
console.log("Hi", "there"); // Hi there
console.warn("this one is orange");
console.error("this one is red");
02
Variables & data types
let for values that change, const for values that do not
Keyword
Can be reassigned?
Use it when
const
No
Default choice — the value should stay put
let
Yes
A counter, a score, anything that changes
var
Yes
Old code only — avoid it in new work
JavaScripttypes.js
const name = "Ayush"; // string
let marks = 87; // number
const percent = 87.5; // number (no separate decimal type)
const passed = true; // boolean
let notYet; // undefined - declared, no value
console.log(typeof marks); // "number"
console.log(typeof name); // "string"
marks = marks + 5; // allowed - let
console.log(`Now ${marks}`); // Now 92
// prompt() always returns TEXT - convert before maths
const age = Number(prompt("Your age?"));
console.log(age + 1);
// numbers and text add up strangely
console.log("5" + 5); // "55" (text wins)
console.log("5" - 5); // 0 (minus forces maths)
console.log(Number("5") + 5); // 10 (convert first!)
1
const only locks the name. You can still change what is inside an object or array declared with const.
2
The + sign means "add" for numbers and "join" for text. That single fact causes more beginner bugs than anything else.
3
Use backticks and ${ } to build text: `Hello ${name}`. It is called a template literal.
03
Operators
Maths, comparisons and the strict equality trap
Operator
Meaning
Example
Result
+ - * /
The usual four
7 / 2
3.5
**
Power
2 ** 5
32
%
Remainder
7 % 2
1
===
Strict equal (value and type)
"5" === 5
false
!==
Strict not equal
"5" !== 5
true
==
Loose equal — converts types first
"5" == 5
true ⚠️
&& || !
And, or, not
a && b
true if both true
??
Fallback if null/undefined
x ?? 0
value or 0
JavaScriptoperators.js
const price = 499;
const qty = 2;
const gst = 0.18;
const subtotal = price * qty;
const total = subtotal + subtotal * gst;
console.log(`Total: ₹${total.toFixed(2)}`); // ₹1177.64
// --- always use === and !== , never == and != ---
console.log("5" == 5); // true (JS silently converts - dangerous)
console.log("5" === 5); // false (compares type too - correct)
console.log(0 == ""); // true 😬
console.log(0 === ""); // false ✅
// --- short-circuit: && returns the first falsy, || the first truthy ---
const user = { name: "" };
const shown = user.name || "Guest";
console.log(shown); // Guest
const count = 0;
console.log(count ?? 99); // 0 (only null/undefined trigger ??)
04
Conditions & loops
Decisions first, repetition second
JavaScriptdecisions.js
const marks = 78;
let grade;
if (marks >= 90) {
grade = "A+";
} else if (marks >= 75) {
grade = "A";
} else if (marks >= 33) {
grade = "B";
} else {
grade = "F";
}
console.log(grade); // A
// ternary - a compact if / else
const label = marks >= 33 ? "Pass" : "Fail";
// switch - many exact matches on one value
switch (grade) {
case "A+": console.log("Outstanding"); break;
case "A": console.log("Excellent"); break;
default: console.log("Keep going");
}
JavaScriptloops.js
// classic for
for (let i = 1; i <= 5; i++) {
console.log(i); // 1 2 3 4 5
}
// while
let count = 1;
while (count <= 3) {
console.log("Round", count);
count++; // forgetting this = infinite loop
}
// for...of - walk through a list (most readable)
const subjects = ["Maths", "Science", "English"];
for (const subject of subjects) {
console.log("I study", subject);
}
// also gives you the position
for (const [i, subject] of subjects.entries()) {
console.log(`${i + 1}. ${subject}`);
}
// there is also for...in (for object keys) and .forEach() on arrays
subjects.forEach((s) => console.log("Again:", s));
1
JavaScript blocks use curly braces{ }, not indentation — Python-style indentation is not required here.
2
Each switch case needs break, or execution falls through into the next case.
3
A while loop whose value never changes freezes the browser tab. Refresh the page to escape.
05
Functions
Named, anonymous and arrow — all three you will see
JavaScriptfunctions.js
// 1. function declaration
function greet(name) {
return `Hello, ${name}!`;
}
// 2. arrow function - the modern short form
const average = (a, b) => (a + b) / 2;
// 3. default parameters
const power = (base, exponent = 2) => base ** exponent;
console.log(greet("Ayush")); // Hello, Ayush!
console.log(average(80, 90)); // 85
console.log(power(5)); // 25
// arrow with a block body needs an explicit return
const gradeOf = (marks) => {
if (marks >= 90) return "A+";
if (marks >= 75) return "A";
return "B";
};
// functions are values - you can pass them around
function runTwice(fn) {
fn();
fn();
}
runTwice(() => console.log("called"));
Which form should you use?
1
Use arrow functions for short callbacks: list.map(n => n * 2).
2
Use function declarations for the main, named pieces of your program — they read better and can be called before they appear.
3
Arrow functions written as one line without braces return the expression automatically. Add { } and you must write return.
06
Arrays & objects
Lists and labelled records — the two shapes you will use forever
JavaScriptcollections.js
const marks = [78, 91, 66];
marks.push(88); // add to the end
console.log(marks.length); // 4
console.log(marks[0], marks.at(-1));// 78 88 (at(-1) is the last item)
console.log(marks.slice(0, 2)); // [78, 91]
// --- the four methods you will use every single day ---
const nums = [1, 2, 3, 4, 5];
const doubled = nums.map(n => n * 2); // transform each item
const evens = nums.filter(n => n % 2 === 0); // keep some items
const total = nums.reduce((sum, n) => sum + n, 0); // boil down to one
const found = nums.find(n => n > 3); // first match
console.log(doubled, evens, total, found);
// [2,4,6,8,10] [2,4] 15 4
// --- objects hold labelled values ---
const student = {
name: "Ayush",
marks: { Maths: 78, Science: 91 },
city: "Shimla",
greet() { return `Hi, I am ${this.name}`; },
};
console.log(student.name); // dot for known keys
console.log(student["marks"]["Science"]); // brackets for dynamic keys
student.phone = "99999-00000"; // add a key any time
console.log(student.greet());
// a list of objects - the shape almost every real app uses
const classMarks = [
{ name: "Ayush", marks: [78, 91, 66] },
{ name: "Riya", marks: [92, 88, 95] },
];
classMarks.forEach((s) => {
const avg = s.marks.reduce((a, b) => a + b, 0) / s.marks.length;
console.log(`${s.name}: ${avg.toFixed(1)}`);
});
// spread makes short copies instead of editing the original
const withExtra = [...marks, 100]; // new array
const renamed = { ...student, name: "Riya" }; // new object
07
The DOM — making a page react
This is what JavaScript is famous for on the web
The browser turns your HTML into a tree of objects called the DOM. JavaScript can read
that tree, change it, and listen for clicks and typing.
// 1. find elements
const title = document.querySelector("#title");
const btn = document.querySelector("#likeBtn");
const input = document.querySelector("#nameInput");
const list = document.querySelector("#list");
// 2. read and change content
console.log(title.textContent);
title.textContent = "Study Hub — Learn Code";
// 3. change style and classes
title.style.color = "#38bdf8";
title.classList.add("highlight");
// 4. listen for a click
let likes = 0;
btn.addEventListener("click", () => {
likes++;
btn.textContent = `Like (${likes})`;
});
// 5. listen for typing, and build list items from user input
input.addEventListener("input", (event) => {
list.innerHTML = "";
if (!event.target.value.trim()) return;
["Maths", "Science", "English"]
.filter((s) => s.toLowerCase().includes(event.target.value.toLowerCase()))
.forEach((s) => {
const li = document.createElement("li");
li.textContent = s;
list.appendChild(li);
});
});
1
querySelector() takes any CSS selector — #id, .class, div > p. It returns the first match; querySelectorAll() returns all of them.
2
Always put your script after the HTML it touches, or wrap the code in DOMContentLoaded. Otherwise the elements do not exist yet.
3
innerHTML runs any HTML you give it. Never pass text typed by a user straight into it — build elements with createElement instead.
08
Errors & common beginner mistakes
The console tells you the line number — use it
Consolehow to read an error
Uncaught TypeError: Cannot read properties of null (reading 'textContent')
at app.js:4:15
# meaning, line by line:
# 1. TypeError ... null -> you used something that does not exist
# 2. reading 'textContent'-> the property you tried to use
# 3. at app.js:4:15 -> file, line, column - click it in DevTools
Six errors you will hit this week
1
Cannot read properties of null — querySelector found nothing. Usually a typo in the selector, or the script ran before the element existed.
2
is not a function — you spelled a method wrong, or you are calling it on text instead of an array.
3
Assignment to constant variable — you declared with const and then reassigned. Change it to let.
4
Unexpected token — a missing bracket, quote or comma. The real problem is usually on the line above the one reported.
5
"5" + 5 giving "55" — convert with Number() before doing maths.
6
Nothing happens at all — your script is loaded but never runs. Check the Network tab; a 404 means the path to your file is wrong.
JavaScriptsafe_parse.js
// stop a crash before it happens
function toNumber(raw, fallback = 0) {
const n = Number(raw);
return Number.isFinite(n) ? n : fallback;
}
console.log(toNumber("42")); // 42
console.log(toNumber("hello")); // 0 - no crash
console.log(toNumber("", 99)); // 99
// try / catch when something can genuinely fail
try {
const data = JSON.parse('{ broken json }');
console.log(data);
} catch (error) {
console.warn("Bad data received:", error.message);
} finally {
console.log("this always runs");
}
// debug like a professional
const before = [1, 2, 3];
console.table(before);
console.log({ before, doubled: before.map((n) => n * 2) });