StudyHub
⭐ JavaScript
← Coding Notes
Language notes · Beginner to confident

JavaScript notes for beginners

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 edges Great for: Websites, apps, servers Run with: node app.js or the browser console (F12) 9 chapters · 20+ examples
01

What JavaScript is & how to run it

The only language a web browser truly speaks

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.
JavaScript app.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

KeywordCan be reassigned?Use it when
constNoDefault choice — the value should stay put
letYesA counter, a score, anything that changes
varYesOld code only — avoid it in new work
JavaScript types.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

OperatorMeaningExampleResult
+ - * /The usual four7 / 23.5
**Power2 ** 532
%Remainder7 % 21
===Strict equal (value and type)"5" === 5false
!==Strict not equal"5" !== 5true
==Loose equal — converts types first"5" == 5true ⚠️
&& || !And, or, nota && btrue if both true
??Fallback if null/undefinedx ?? 0value or 0
JavaScript operators.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

JavaScript decisions.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");
}
JavaScript loops.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

JavaScript functions.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

JavaScript collections.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.

HTML index.html
<h1 id="title">Study Hub</h1>
<button id="likeBtn">Like (0)</button>
<input id="nameInput" placeholder="Your name">
<ul id="list"></ul>
JavaScript app.js
// 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

Console how 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 nullquerySelector 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.
JavaScript safe_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) });
09

JavaScript cheat sheet

Keep this open while you practise

Do thisWrite thisYou get
Show a valueconsole.log(x)printed in console
Declare a constantconst x = 5cannot reassign
Changeable valuelet n = 0can reassign
Join text`Hi ${name}`one string
Text → numberNumber("15")15
Number → textString(15)"15"
Round to 2 dpn.toFixed(2)text "1.50"
Decideif (x > 5) { }runs the block
Either / orcond ? a : bone value
Count loopfor (let i=0; i<5; i++)0 … 4
Walk an arrayfor (const x of arr)each item
Functionconst f = (x) => x * 2arrow function
Add to arrayarr.push(4)array grows
Transformarr.map(fn)new array
Filterarr.filter(fn)smaller array
Total uparr.reduce((a,b)=>a+b,0)one number
Read objectobj.keythe value
Object keysObject.keys(obj)array of keys
Find elementdocument.querySelector("#id")element or null
React to clickel.addEventListener("click", fn)handler attached
Handle failuretry { } catch (e) { }no crash
Save datalocalStorage.setItem("k", v)stored in browser

Practice project: marks report card

JavaScript report.js
const students = [
  { name: "Ayush", marks: [78, 91, 66] },
  { name: "Riya",  marks: [92, 88, 95] },
  { name: "Karan", marks: [45, 52, 60] },
];

const average = (nums) =>
  nums.length ? nums.reduce((a, b) => a + b, 0) / nums.length : 0;

const gradeOf = (avg) => {
  if (avg >= 85) return "A";
  if (avg >= 70) return "B";
  if (avg >= 50) return "C";
  return "D";
};

console.table(
  students.map((s) => {
    const avg = average(s.marks);
    return { name: s.name, average: avg.toFixed(1), grade: gradeOf(avg) };
  })
);

const classAvg = average(students.map((s) => average(s.marks)));
console.log(`Class average: ${classAvg.toFixed(1)}`);

Test yourself

Four quick questions on JavaScript basics

Q1 What does "5" + 5 give?

Q2 Which declares a value you can reassign later?

Q3 Which array method keeps only the items that pass a test?

Q4 Why should you use === instead of ==?

Answered 0 of 4 · correct 0

Continue with another language

Same structure, same depth — pick the one you need next.