πŸ“˜ CodingMarble Learn

JavaScript Basics: Make a Web Page Think and React

JavaScript is the programming language of web pages. HTML builds the page, CSS styles it and JavaScript makes it do things. Variables (let, const) are named boxes that hold values: numbers, strings, booleans, arrays and objects. Operators calculate and compare. if…else lets the program choose; for and while loops repeat code. A function is a named block of code you can call many times, with parameters and a return value. Built-in methods work on strings (length, toUpperCase, slice), arrays (push, pop, sort, join) and Math (round, max, random). Events such as click and input run functions when the user acts.

🎬 Step-by-step story

  1. A variable is a labelled box that stores a value. let score = 5 puts 5 in a box named score.
  2. Operators work on values: + βˆ’ * / and % (remainder) calculate; > and === compare and give true or false.
  3. if…else lets the program choose. If marks >= 33 the green gate opens, else the red one.
  4. A loop repeats code. for (let i = 1; i <= n; i++) runs its body n times.
  5. Built-in methods do jobs for you on arrays, strings and Math: push, pop, sort, length, toUpperCase, Math.max.
  6. Free play: a function is a named recipe, and an event (a click) calls it. Press the button to call toggleLight().

Tip: drag the 3D scene to turn it. Use two fingers to zoom.

πŸ€” Common doubts, cleared

When should I use let and when const?

Use const by default; use let only if the value must change (like a counter). Step 1 shows the score box changing.

Why does 5 == "5" give true?

== converts types before comparing; === does not. Pick === in step 2 to see the strict result.

What if two if conditions are both true?

In an if…else if chain only the first true block runs. Slide the marks in step 3.

How many times does a for loop run?

for (let i = 1; i <= n; i++) runs n times; count the columns in step 4.

Why does sort() put 10 before 9?

Default sort compares as text. Use sort((a, b) => a - b), shown in step 5.

What is the difference between a function and an event?

A function is the code; an event is the moment that triggers it. In step 6 the click (event) calls toggleLight() (function).

What is JavaScript and how to add it to a page

JavaScript (JS) is a programming language that runs inside the web browser (and also on servers with Node.js). It makes pages interactive: check forms, change text, show pop-ups, run games.

Add it with a <script> tag, inside the page or as a separate file:

<script>
  console.log("Hello");
</script>
<script src="app.js"></script>

Output: console.log() (developer console), alert() (pop-up), document.write() (old style) or changing an element's text with document.getElementById("id").textContent = …. Input: prompt() or a form field's .value. Comments: // one line or /* many lines */. JavaScript is case-sensitive: Score and score are different.

Variables and data types

A variable is a named box for a value.

let score = 5;        // can change later
const PI = 3.14;      // cannot be reassigned
var old = 1;          // older style, avoid

Names may use letters, digits, _ and $, but cannot start with a digit or be a keyword (like if). Common data types:

typeof x tells the type. JavaScript is dynamically typed: one variable can hold different types at different times.

Operators

Conditions: if, else if, else and switch

let marks = 72;
if (marks >= 90) {
  grade = "A";
} else if (marks >= 33) {
  grade = "Pass";
} else {
  grade = "Try again";
}

The first true condition runs, and the rest are skipped. switch compares one value with many cases:

switch (day) {
  case 0: name = "Sunday"; break;
  case 6: name = "Saturday"; break;
  default: name = "Weekday";
}

Forgetting break makes the code fall through to the next case.

Loops and simple programs

// for: when you know how many times
let sum = 0;
for (let i = 1; i <= 5; i++) { sum += i; }   // sum = 15

// while: repeat while a condition is true
let n = 1;
while (n < 100) { n = n * 2; }               // n = 128

// do…while runs at least once
do { x--; } while (x > 0);

break leaves a loop; continue skips to the next round. Simple programs to practise: sum of 1 to n, multiplication table, even or odd (n % 2 === 0), largest of three numbers, factorial, reversing a number, counting vowels in a word.

Functions

A function is a named block of code. Define it once, call it many times.

function area(l, b) {      // l, b are parameters
  return l * b;           // send a value back
}
let a = area(4, 3);        // 4, 3 are arguments β†’ a = 12

const square = x => x * x; // arrow function
const greet = function(n) { return "Hi " + n; }; // function expression

Variables made with let/const inside a function are local (only seen inside); those outside are global. A function with no return gives undefined. Default parameters: function hi(n = "friend").

String, array and Math methods

String

Index starts at 0. "hello".length β†’ 5; toUpperCase(), toLowerCase(); charAt(1) β†’ "e"; indexOf("l") β†’ 2; slice(1, 4) / substring(1, 4) β†’ "ell"; replace("h", "j"); trim(); split(","); includes("ell") β†’ true.

Array

let a = [4, 1, 3]; a[0] β†’ 4; a.length β†’ 3; push(x) adds at end, pop() removes last, unshift/shift work at the start; indexOf, includes, join("-"), reverse(), slice, splice, concat. sort() sorts as text, so for numbers use sort((x, y) => x - y). Loop helpers: forEach, map, filter.

Math

Math.round(4.5) β†’ 5, Math.floor(4.9) β†’ 4, Math.ceil(4.1) β†’ 5, Math.max(2, 8) β†’ 8, Math.min, Math.sqrt(16) β†’ 4, Math.pow(2, 3) β†’ 8, Math.abs(-3) β†’ 3, Math.PI. Random whole number 1–6: Math.floor(Math.random() * 6) + 1.

Event handling

An event is something that happens on the page: a click, a key press, typing in a box, the page loading, the mouse moving over an element. An event handler is the function that runs when it happens.

<button id="btn">Click me</button>
<p id="out"></p>
<script>
  let count = 0;
  function clicked() {
    count++;
    document.getElementById("out").textContent = "Clicked " + count;
  }
  document.getElementById("btn").addEventListener("click", clicked);
</script>

Common events: click, dblclick, mouseover, mouseout, keydown, input, change, submit, load, focus, blur. Older inline style: <button onclick="clicked()">. In a form, event.preventDefault() stops the page reloading so JavaScript can check the inputs first.

Key formulas and definitions

Worked examples

1. What is printed? let a = 7, b = 3; console.log(a % b, a / b > 2, "a" + b);

7 % 3 = 1; 7/3 β‰ˆ 2.33 > 2 is true; "a" + 3 = "a3". Output: 1 true a3.

2. Write code that prints "Even" or "Odd" for n = 14.

let n = 14; if (n % 2 === 0) { console.log("Even"); } else { console.log("Odd"); } β†’ Even, because 14 % 2 is 0.

3. Use a loop to find the sum of 1 to 10.

let s = 0; for (let i = 1; i <= 10; i++) { s += i; } β†’ s = 55. Check: 10 Γ— 11 Γ· 2 = 55.

4. Write a function that returns the largest of three numbers.

function big(a, b, c) { let m = a; if (b > m) m = b; if (c > m) m = c; return m; } big(4, 9, 2) β†’ 9. (Or return Math.max(a, b, c).)

5. let w = "Learn"; What are w.length, w.toUpperCase(), w.charAt(0), w.slice(1, 3)?

5, "LEARN", "L", "ea" (characters at index 1 and 2; index 3 is not included).

6. let a = [10, 2, 33]; a.push(4); a.sort(); What is a? How do you sort numbers correctly?

After push: [10, 2, 33, 4]. sort() compares as text ("10" < "2" < "33" < "4" because it looks at the first character), so a stays [10, 2, 33, 4]. Correct: a.sort((x, y) => x - y) β†’ [2, 4, 10, 33].

7. Count vowels in "education" with a loop and a string method.

let s = "education", c = 0; for (let ch of s) { if ("aeiou".includes(ch)) c++; } β†’ c = 5 (e, u, a, i, o).

8. Make a button that shows a random dice number in a paragraph when clicked.

<button id="d">Roll</button><p id="r"></p> and document.getElementById("d").addEventListener("click", () => { document.getElementById("r").textContent = Math.floor(Math.random() * 6) + 1; });

Common mistakes

Practice quiz

1. Which keyword makes a variable that cannot be reassigned?
2. What is 10 % 4?
3. What is "3" + 4 in JavaScript?
4. Which method adds an item to the end of an array?
5. Which event fires when a button is pressed?

Practice: answer these yourself

Type or choose your answer, then press Check. Use a hint if you are stuck; the full solution appears after you answer.

Frequently asked questions

Is JavaScript the same as Java?

No. They are different languages with similar names. JavaScript runs in web browsers; Java is used for apps and large systems.

What are the basic concepts of JavaScript?

Variables and data types, operators, conditions (if/else, switch), loops (for, while), functions, built-in methods (string, array, Math) and events.

What is event handling in JavaScript?

Running a function when something happens on the page, such as a click or key press, usually with element.addEventListener("click", handler).

Where this is taught

CBSE (India)Class 11JavaScript Part 1
CBSE (India)Class 12JavaScript Part 2

Learn first

Learn next

Related lessons

All Computer Science lessons