Chapter 5: Basic JavaScript
54 slides · use ←/→ or Space to navigate, F for fullscreen.
Jump to a lesson deck: JavaScript Origin & Overview What JavaScript Can Do The <script> Tag & Where to Put Scripts Writing Output to the Page Statements, Variables & Comments JavaScript Data Types Expressions & Operators JavaScript Functions JavaScript Event Handlers Dates & Arrays Conditionals & Loops Errors & Popup Boxes
Chapter 5: Basic JavaScript
JavaScript — the language of the web: origin, syntax, variables, data types, operators, functions, events, dates, arrays, conditionals, loops, errors and popups.
JavaScript Origin & Overview
Where JavaScript came from, what it is, and how it powers both the client and the server.
JavaScript Origin
- Created in just 10 days by Brendan Eich while working at Netscape Communications in 1995.
- First appeared in 1995 as a scripting language for web pages, initially called LiveScript before being renamed.
- ECMAScript defines the rules and guidelines. JavaScript is an implementation of ECMAScript, enabling programmatic access to computational objects.
- Other implementations: JavaScript by Netscape, JScript by Microsoft, and ActionScript by Adobe.
“Learning JavaScript used to mean you were not a serious software developer. Today, not learning JavaScript means the same thing.” — Tim O'Reilly, founder of O'Reilly Media
Overview of JavaScript
| Property | Detail |
|---|---|
| High-level language | Abstracts away low-level machine details, making it accessible. |
| Runs in all browsers | The only programming language that runs natively in all major web browsers — essential for front-end development. |
| Embedded in HTML | Can be embedded directly into HTML documents, or referenced via external .js files. |
| Dynamic & interactive | Responds to user input, dynamically updates content and creates animations — without reloading the page. |
JavaScript and Java are related only through their names and some syntax. Java is compiled and statically typed; JavaScript is interpreted and dynamically typed.
Client-Side vs Server-Side
| Client-side | Server-side (Node.js) |
|---|---|
|
Runs inside the user's browser Creates dynamic & interactive pages Responds to user input in real time Validates forms before server submission Updates content without a full page reload Frameworks: React, Angular, Vue.js |
Runs on the web server (via Node.js) Handles complex business logic Interfaces with databases Builds APIs and back-end systems Enables full-stack development Single language across the entire stack |
Activity — complete the code
Complete the script: JavaScript is an implementation of the ECMAScript standard.
<!DOCTYPE html><html><head><title>Hello JS</title></head><body><script>// JavaScript is an implementation ofdocument.("Hello, world!");</script></body></html>
What JavaScript Can Do
Core capabilities and the three patterns of DOM manipulation.
Core Capabilities
| Capability | Detail |
|---|---|
| HTML designer tool | Gives HTML designers a full programming capability to build logic directly into web pages. |
| Dynamic text | Writes variable content into HTML: "Hello " + name. |
| Event reactions | Executes code when events happen — for example when a user clicks an element. |
| Client-side validation | Validates form data before submission, saving unnecessary server round-trips. |
| DOM manipulation | Accesses and modifies the Document Object Model — a tree representation of the page. |
| User notifications | Shows information or alerts without interrupting workflow (alert, confirm, prompt). |
| Back-end data loading | Makes HTTP requests (AJAX / Fetch API) to retrieve or send data without reloading. |
| Interactive presentations | Libraries like Reveal.js and Impress.js build interactive slide decks entirely in JavaScript. |
JavaScript reacts to events triggered by the user or browser — this makes pages feel alive and responsive without a server round-trip.
Changing HTML with JavaScript
// 1. Change HTML content
document.getElementById("demo").innerHTML = "Hello JavaScript!";
// 2. Change an HTML attribute
var image = document.getElementById("myImage");
if (image.src.match("bulbon")) {
image.src = "pic_bulboff.gif";
} else {
image.src = "pic_bulbon.gif";
}
// 3. Change HTML styles (CSS)
document.getElementById("demo").style.fontSize = "25px";
document.getElementById("demo").style.color = "blue";
These three patterns — innerHTML, attribute changes and style changes — are the foundation of all DOM manipulation in JavaScript.
Activity — complete the code
Complete the three DOM manipulation patterns.
// 1. Change HTML contentdocument.getElementById("demo"). = "Hello JavaScript!";// 2. Change an HTML attributevar image = document.getElementById("myImage");image. = "pic_bulbon.gif";// 3. Change HTML stylesdocument.getElementById("demo").style. = "25px";
The <script> Tag & Where to Put Scripts
Embedding JavaScript in HTML, script placement, and external files.
The <script> Tag
The HTML <script> tag tells the browser to expect JavaScript between its opening and closing tags.
<html>
<body>
<script>
document.write("This is not Java");
</script>
</body>
</html>
- Opening
<script>tag — signals that the content between the tags is JavaScript, not HTML. document.write()— writes text or HTML directly into the page.
Where to Put Your Scripts
| Placement | Notes |
|---|---|
In the <head> | Loaded before the page body. Best for functions called from HTML elements. |
In the <body> | Runs when the browser reaches that point. Preferred for DOM manipulation. |
| In both | You can split scripts between the two sections. |
External .js file | Linked via <script src="...">. Keeps HTML clean, enables caching and reuse. |
Scripts in the <head>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
Scripts in the head run before the DOM is rendered. Avoid direct DOM access in the head unless it is inside a function that is called later.
Scripts at the end of <body>
<body>
<button onclick="myFunction()">Click</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
Best practice: place scripts at the bottom of <body> so the DOM is fully loaded before your script runs.
External JavaScript Files
<head>
<script src="myscript.js"></script>
</head>
- Separation of concerns — HTML handles structure, JavaScript handles behaviour.
- Easier maintenance — changes to logic are made in one place; many pages can share the file.
- Browser caching — the file is downloaded only once, speeding up repeat visits.
Activity — complete the code
Complete the script embedding and placement.
<!-- External JavaScript file --><head><script ="myscript.js"></script></head><!-- Inline script --><>document.write("This is not Java");</script><!-- Best practice: put scripts at the bottom of --><>...</body>
Writing Output to the Page
The five ways to display JavaScript output.
Five Ways to Display Output
| Method | Purpose |
|---|---|
window.alert("text") | Shows a pop-up alert dialog to the user. |
document.write(value) | Writes content into the HTML document. No newline added. |
document.writeln(value) | Like document.write() but adds a newline after each call. |
element.innerHTML | Sets the HTML content of a specific element by its ID. |
console.log("text") | Writes to the browser's developer console. Great for debugging. |
window.alert("Hello!"); // pop-up dialog
document.write("Hello from JS"); // writes into the page
document.writeln("Next line"); // write + newline
document.getElementById("demo").innerHTML = "Hello!"; // set element content
console.log("Debugging value"); // developer console
console.log() is your best friend for debugging — open DevTools (F12) and check the Console tab.
Activity — complete the code
Complete the five ways of writing output.
// 1. Pop-up dialogwindow.("text");// 2. Write into the documentdocument.("value");// 3. Set an element content by iddocument.getElementById("demo"). = "value";// 4. Write to the developer consoleconsole.("text");
Statements, Variables & Comments
How JavaScript programs are built, how to store data, and how to document code.
JavaScript Statements
A JavaScript statement is an instruction that tells the browser what to do. A program is simply a series of statements. A semicolon separates each statement.
Statements are made up of values (variables, numbers, strings), keywords, operators and expressions.
var x = 5; // statement 1
var y = 6; // statement 2
var z = x + y; // statement 3
JavaScript Variables
Naming rules
- Names are case-sensitive (
myVar≠MyVar). - Must begin with a letter, underscore (
_) or dollar sign ($). - Cannot use reserved JavaScript keywords.
- Use camelCase by convention:
firstName,totalAmount.
// Using var (classic)
var strName = "value";
// Without var (global scope — avoid!)
strName = "value";
// Modern alternatives (ES6+)
let x = 10; // block-scoped, reassignable
const PI = 3.14; // block-scoped, constant
var firstname;
firstname = "Toot";
document.write(firstname);
firstname = "Tweet"; // outputs: Toot
JavaScript Comments
Comments are lines that are not executed. They explain code or temporarily disable it during debugging.
// This is a single-line comment
var x = 5; // you can also comment after code
/*
This whole block is a comment
and will not execute.
*/ Activity — complete the code
Complete the variable declarations and the statement terminator.
x = 10; // block-scoped, reassignablePI = 3.14; // block-scoped, constantname = "Toot"; // classic declarationvar total = 5 6; // each statement ends with this
JavaScript Data Types
The value types a variable can hold.
Data Types
| Type | Meaning |
|---|---|
| Number | Numeric values — integers and decimals. |
| String | Text values enclosed in quotes. |
| Boolean | True or false logical values. |
| Undefined | A variable declared but not assigned. |
| Null | The intentional absence of a value. |
| Object | Key-value pairs and complex data. |
var age = 25; // Number
var price = 9.99; // Number
var isActive = true; // Boolean
var done = false; // Boolean
var name = "Hello"; // String
var msg = ' World'; // String
var x; // Undefined (declared, not assigned)
var result = null; // Null (intentional absence of value)
var p = { name: "Ana", age: 22 }; // Object Activity — complete the code
Name the data type of each value.
var age = 25; //var name = "Hello"; //var isActive = true; //var x; //var result = null; // Nullvar p = { name: "Ana" }; //
Expressions & Operators
Arithmetic, assignment, comparison, logical and string operators — and type coercion.
Expressions & Operators
An expression is any combination of values, variables and operators that computes to a value.
| Operator type | Purpose |
|---|---|
| Arithmetic | Mathematical calculations on numeric values (+ - * / %). |
| Assignment | Assign values to variables (= += -=). |
| Comparison | Compare values, returning true/false (== === != < >). |
| Logical | Combine boolean expressions (&& || !). |
| String | + (concatenation) joins strings together. |
Operator examples
// String concatenation with "+"
var txt1 = "John";
var txt2 = "Doe";
var txt3 = txt1 + " " + txt2; // "John Doe"
// Assignment operator "+="
var txt = "What a very ";
txt += "nice day"; // "What a very nice day"
// Mixing numbers and strings
var x = 5;
var y = 5;
var z = x + y; // 10 (number + number)
var s = x + "5"; // "55" (number + string)
var h = "Hello" + x; // "Hello5"
Type coercion: when you add a string and a number, JavaScript converts the number to a string and concatenates them — a common source of bugs!
Activity — complete the code
Complete the operators.
// String concatenationvar txt3 = txt1 " " + txt2; // "John Doe"// Assignment (append)txt "nice day";// Arithmeticvar z = x y; // add// Strict equality (value AND type)if (age 18) { }
JavaScript Functions
Defining and calling reusable blocks of code, plus anonymous functions.
JavaScript Functions
A function is a reusable block of code that performs a specific task. It eliminates repetition and breaks complex programs into manageable pieces.
function functionName(param1, param2) {
// code to be executed
return value; // optional
}
function multiply(a, b) {
return a * b;
}
document.getElementById("demo").innerHTML = multiply(4, 3); // 12
Define once, call many times — with different arguments each time!
Function Invocation
- Function invocation — a direct call using the function name and arguments.
- Method invocation — called as a method on an object, using dot notation.
- Constructor invocation — used with the
newkeyword to create object instances.
Example: Temperature Converter
function toCelsius(fahrenheit) {
return (5 / 9) * (fahrenheit - 32);
}
var result = toCelsius(77);
document.write("The temperature is " + result + " Celsius");
// Output: "The temperature is 25 Celsius"
- The return statement sends the computed value back to the caller; execution stops at
return. - Parameters are placeholders in the definition; arguments are the actual values you pass when calling.
Anonymous Functions
An anonymous function has no name. Instead, it is assigned to a variable or passed as an argument to another function.
// Anonymous function assigned to a variable
var multiply = function (a, b) {
return a * b;
};
multiply(4, 3); // 12
// Named function (for comparison)
function multiplyNamed(a, b) {
return a * b;
}
Anonymous functions are commonly used as callbacks — functions passed as arguments to other functions (event handlers, setTimeout, array methods like forEach, map, filter).
Activity — complete the code
Complete the function definitions.
multiply(a, b) {a * b;}document.getElementById("demo").innerHTML = multiply(4, 3); // 12// Anonymous function assigned to a variablevar divide = (a, b) {return a / b;};
JavaScript Event Handlers
Making pages respond to clicks, loads, submissions and other events.
Event Handlers
JavaScript is event-driven. An event handler is a piece of code triggered in response to a specific user or browser action.
| Event | When it fires |
|---|---|
click | User clicks an HTML element. |
load / unload | Browser finishes or starts loading a page. |
submit | User submits a form. |
mouseover / mouseout | Mouse enters or leaves an element. |
keydown / keyup | User presses or releases a keyboard key. |
change | Value of an input element changes. |
What Event Handlers Can Do
- Page load actions — initialise components, start timers, load data.
- Page close actions — cleanup when the user navigates away.
- Button click actions — submit forms, trigger animations.
- Form input validation — verify data in real time before it is sent to the server.
- DOM manipulation — show/hide elements, change text, update styles dynamically.
Event Handler Example
<html>
<body>
<button onclick="myFunction()">Click Me</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Welcome to the JavaScript class!";
}
</script>
</body>
</html>
When the user clicks the button, the browser calls myFunction(), which finds the element with id="demo" and sets its innerHTML. The page updates instantly — no reload needed!
Activity — complete the code
Complete the event handler example.
<button ="myFunction()">Click Me</button><p id="demo"></p><script>function myFunction() {document.getElementById("demo"). = "Welcome!";}</script><!-- Fires when the user presses a key --><input on="checkKey()">
Dates & Arrays
Working with date/time values and ordered collections.
JavaScript Date Object
The Date object lets you work with years, months, days, hours, minutes, seconds and milliseconds.
// Create a Date object for RIGHT NOW
var now = new Date();
console.log(now); // e.g. "Fri Mar 18 2016 10:18:00"
// Dates as a number (milliseconds since Jan 1, 1970)
console.log(Date.now()); // e.g. 1458277734226
// Useful Date methods
var d = new Date();
d.getFullYear(); // 2024
d.getMonth(); // 0-11 (0 = January!)
d.getDate(); // day of month (1-31)
d.getHours(); // hour (0-23)
d.getMinutes(); // minutes (0-59)
Remember to add 1 to getMonth() when displaying the month to users!
JavaScript Arrays
An array is an ordered collection of values referenced by a single variable name. Arrays can hold mixed types.
// Two ways to create arrays
var points = new Array(40, 100, 1, 5); // old way — avoid
var points = [40, 100, 1, 5]; // modern syntax
// Arrays can mix types
var faq = [];
faq[0] = "What are JavaScript arrays";
faq[1] = Date.now();
faq[2] = 5000;
// Accessing elements (zero-indexed!)
console.log(points[0]); // 40
console.log(points[1]); // 100
// Adding elements to an array
points.push(7); // push(): adds to the end
points[points.length] = 9; // assigns at next index
points[10] = 3; // direct index: creates empty holes Activity — complete the code
Complete the Date and Array code.
// Create a Date object for right nowvar now = new ();// Milliseconds since Jan 1, 1970console.log(Date.());// Arrays are zero-indexedvar points = [40, 100, 1, 5];console.log(points); // 40// Add to the end of an arraypoints.(7);
Conditionals & Loops
Making decisions with if/else and switch, and repeating code with loops.
Comparison & Logical Operators
| Comparison | Meaning |
|---|---|
== | Equal value (loose) |
=== | Equal value AND type (strict) |
!= / !== | Not equal / not equal value or type |
< > <= >= | Less / greater than (or equal) |
| Logical | Meaning |
|---|---|
&& | AND — both conditions must be true |
|| | OR — at least one must be true |
! | NOT — reverses the boolean value |
if (age >= 18 && country === "MY") {
// eligible
}
Use strict equality === — it compares value AND type, which is best practice.
Conditional Statements: if and if...else
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
switch (new Date().getDay()) { // selects today's day
case 6:
text = "Saturday";
break;
case 0:
text = "Sunday";
break;
default:
text = "Weekday";
}
JavaScript Loop Types
| Loop | Use |
|---|---|
for | Known number of iterations. |
while | Repeats while the condition is true. |
do...while | Always runs at least once. |
for...in | Iterates over object properties. |
for...of | Iterates over iterable values. |
// for — known number of iterations
for (var i = 0; i < 5; i++) {
console.log(i);
}
// while — repeats while condition is true
var i = 0;
while (i < 5) {
console.log(i);
i++;
}
// do...while — always runs at least once
var j = 0;
do {
console.log(j);
j++;
} while (j < 5);
// for...in — iterates over object properties
for (var key in person) {
console.log(key);
}
// for...of — iterates over iterable values
for (var fruit of fruits) {
console.log(fruit);
} Activity — complete the code
Complete the conditional and the loops.
if (hour < 18) {greeting = "Good day";} {greeting = "Good evening";}// Known number of iterationsfor (var i = 0; i < 5; ) {console.log(i);}// Iterate over iterable valuesfor (var fruit fruits) {console.log(fruit);}
Errors & Popup Boxes
The three types of errors and the three popup dialogs.
JavaScript Errors
| Type | Description |
|---|---|
| Load-time errors | Syntax errors that prevent the script from loading (missing brackets, typos). |
| Run-time errors | Errors during execution — undefined variables, calling non-functions, division by zero. |
| Logic errors | Code runs fine but produces wrong results. Hardest to detect — use console.log() to debug. |
Popup Box Types
| Method | Behaviour |
|---|---|
alert("message") | Displays a message. The user must click OK. |
confirm("Message") | The user chooses OK (true) or Cancel (false). |
prompt("Message", "Default") | The user enters a value in a text field. |
alert("message");
var ok = confirm("Message"); // true or false
var name = prompt("Your name?", "Default");
Chapter 5 Topics
Origin · Overview · Syntax · Variables · Operators · Functions · Events · Dates · Arrays · Conditionals · Loops · Errors · Popups.
Activity — complete the code
Complete the popup boxes and error types.
// Popup boxes("message"); // user clicks OK("Message"); // OK (true) or Cancel (false)("Message", "Default"); // user enters a value// Error types// Load-time: errors that stop the script loading// Run-time: errors during