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, avoidNames may use letters, digits, _ and $, but cannot start with a digit or be a keyword (like if). Common data types:
- Number: 5, 3.14 (one type for whole and decimal numbers)
- String: text in quotes, "Asha" or 'Hi'
- Boolean: true or false
- undefined (no value yet) and null (empty on purpose)
- Array: a list, [4, 1, 3]; Object: {name: "Asha", age: 15}
typeof x tells the type. JavaScript is dynamically typed: one variable can hold different types at different times.
Operators
- Arithmetic: + β * / % (remainder) ** (power), ++ and ββ. Example: 7 % 3 = 1.
- Assignment: = += β= *= /=. Example: x += 2 means x = x + 2.
- Comparison: > < >= <= == != === !==. Use
===(equal value and type): 5 == "5" is true, but 5 === "5" is false. - Logical: && (AND), || (OR), ! (NOT).
- String joining: "Hi " + "Asha" gives "Hi Asha". Careful: "5" + 2 = "52" (text), but "5" * 2 = 10.
- Ternary:
cond ? a : b.
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 expressionVariables 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
- let x = 5; (changeable) Β· const y = 10; (fixed)
- Types: number, string, boolean, undefined, null, array, object
- === checks value and type; == converts first
- if (cond) { β¦ } else if (cond2) { β¦ } else { β¦ }
- for (let i = start; i <= end; i++) { β¦ } Β· while (cond) { β¦ }
- function name(p1, p2) { return β¦; } Β· const f = x => x * 2;
- Index starts at 0: last index = length β 1
- Random 1 to n: Math.floor(Math.random() * n) + 1
- el.addEventListener("click", handler)
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
- Using = (assign) instead of === (compare) inside if. if (x = 5) always runs because it sets x to 5.
- Forgetting that "5" + 2 gives "52". Turn input text into a number with Number() or parseInt() first.
- Thinking the first index is 1. Arrays and strings start at index 0, so the last is length β 1.
- Writing addEventListener("click", clicked()) with brackets. That runs the function at once; pass clicked without ().