Chapter 1 deck Chapter 2 deck Chapter 3 deck Chapter 4 deck Chapter 5 deck Chapter 6 deck Chapter 7 deck Chapter 8 deck Chapter 9 deck Chapter 10 deck Chapter 11 deck Chapter 12 deck Chapter 13 deck Chapter 14 deck

Chapter 5: Basic JavaScript

54 slides · use ←/→ or Space to navigate, F for fullscreen.

Reading view

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
Fullscreen for presentation · Print / PDF for a handout
1 / 54
Chapter 5

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.

Lesson

JavaScript Origin & Overview

Where JavaScript came from, what it is, and how it powers both the client and the server.

JavaScript Origin & Overview

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

JavaScript Origin & Overview

Overview of JavaScript

PropertyDetail
High-level languageAbstracts away low-level machine details, making it accessible.
Runs in all browsersThe only programming language that runs natively in all major web browsers — essential for front-end development.
Embedded in HTMLCan be embedded directly into HTML documents, or referenced via external .js files.
Dynamic & interactiveResponds 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.

JavaScript Origin & Overview

Client-Side vs Server-Side

Client-sideServer-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
JavaScript Origin & Overview

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 of
document.("Hello, world!");
</script>
</body>
</html>

Lesson

What JavaScript Can Do

Core capabilities and the three patterns of DOM manipulation.

What JavaScript Can Do

Core Capabilities

CapabilityDetail
HTML designer toolGives HTML designers a full programming capability to build logic directly into web pages.
Dynamic textWrites variable content into HTML: "Hello " + name.
Event reactionsExecutes code when events happen — for example when a user clicks an element.
Client-side validationValidates form data before submission, saving unnecessary server round-trips.
DOM manipulationAccesses and modifies the Document Object Model — a tree representation of the page.
User notificationsShows information or alerts without interrupting workflow (alert, confirm, prompt).
Back-end data loadingMakes HTTP requests (AJAX / Fetch API) to retrieve or send data without reloading.
Interactive presentationsLibraries 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.

What JavaScript Can Do

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.

What JavaScript Can Do

Activity — complete the code

Complete the three DOM manipulation patterns.

// 1. Change HTML content
document.getElementById("demo"). = "Hello JavaScript!";
 
// 2. Change an HTML attribute
var image = document.getElementById("myImage");
image. = "pic_bulbon.gif";
 
// 3. Change HTML styles
document.getElementById("demo").style. = "25px";

Lesson

The &lt;script&gt; Tag & Where to Put Scripts

Embedding JavaScript in HTML, script placement, and external files.

The &lt;script&gt; Tag & Where to Put Scripts

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.
The &lt;script&gt; Tag & Where to Put Scripts

Where to Put Your Scripts

PlacementNotes
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 bothYou can split scripts between the two sections.
External .js fileLinked 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.

The &lt;script&gt; Tag & Where to Put Scripts

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.
The &lt;script&gt; Tag & Where to Put Scripts

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>

Lesson

Writing Output to the Page

The five ways to display JavaScript output.

Writing Output to the Page

Five Ways to Display Output

MethodPurpose
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.innerHTMLSets 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.

Writing Output to the Page

Activity — complete the code

Complete the five ways of writing output.

// 1. Pop-up dialog
window.("text");
 
// 2. Write into the document
document.("value");
 
// 3. Set an element content by id
document.getElementById("demo"). = "value";
 
// 4. Write to the developer console
console.("text");

Lesson

Statements, Variables & Comments

How JavaScript programs are built, how to store data, and how to document code.

Statements, Variables & Comments

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
Statements, Variables & Comments

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
Statements, Variables & Comments

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.
*/
Statements, Variables & Comments

Activity — complete the code

Complete the variable declarations and the statement terminator.

x = 10; // block-scoped, reassignable
PI = 3.14; // block-scoped, constant
name = "Toot"; // classic declaration
 
var total = 5 6; // each statement ends with this

Lesson

JavaScript Data Types

The value types a variable can hold.

JavaScript Data Types

Data Types

TypeMeaning
NumberNumeric values — integers and decimals.
StringText values enclosed in quotes.
BooleanTrue or false logical values.
UndefinedA variable declared but not assigned.
NullThe intentional absence of a value.
ObjectKey-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
JavaScript Data Types

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; // Null
var p = { name: "Ana" }; //

Lesson

Expressions & Operators

Arithmetic, assignment, comparison, logical and string operators — and type coercion.

Expressions & Operators

Expressions & Operators

An expression is any combination of values, variables and operators that computes to a value.

Operator typePurpose
ArithmeticMathematical calculations on numeric values (+ - * / %).
AssignmentAssign values to variables (= += -=).
ComparisonCompare values, returning true/false (== === != < >).
LogicalCombine 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!

Expressions & Operators

Activity — complete the code

Complete the operators.

// String concatenation
var txt3 = txt1 " " + txt2; // "John Doe"
 
// Assignment (append)
txt "nice day";
 
// Arithmetic
var z = x y; // add
 
// Strict equality (value AND type)
if (age 18) { }

Lesson

JavaScript Functions

Defining and calling reusable blocks of code, plus anonymous functions.

JavaScript 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!

JavaScript Functions

Function Invocation

  1. Function invocation — a direct call using the function name and arguments.
  2. Method invocation — called as a method on an object, using dot notation.
  3. Constructor invocation — used with the new keyword to create object instances.
JavaScript Functions

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

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).

JavaScript Functions

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 variable
var divide = (a, b) {
return a / b;
};

Lesson

JavaScript Event Handlers

Making pages respond to clicks, loads, submissions and other events.

JavaScript Event Handlers

Event Handlers

JavaScript is event-driven. An event handler is a piece of code triggered in response to a specific user or browser action.

EventWhen it fires
clickUser clicks an HTML element.
load / unloadBrowser finishes or starts loading a page.
submitUser submits a form.
mouseover / mouseoutMouse enters or leaves an element.
keydown / keyupUser presses or releases a keyboard key.
changeValue of an input element changes.
JavaScript Event Handlers

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.
JavaScript Event Handlers

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!

JavaScript Event Handlers

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()">

Lesson

Dates & Arrays

Working with date/time values and ordered collections.

Dates & Arrays

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!

Dates & Arrays

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
Dates & Arrays

Activity — complete the code

Complete the Date and Array code.

// Create a Date object for right now
var now = new ();
 
// Milliseconds since Jan 1, 1970
console.log(Date.());
 
// Arrays are zero-indexed
var points = [40, 100, 1, 5];
console.log(points); // 40
 
// Add to the end of an array
points.(7);

Lesson

Conditionals & Loops

Making decisions with if/else and switch, and repeating code with loops.

Conditionals & Loops

Comparison & Logical Operators

ComparisonMeaning
==Equal value (loose)
===Equal value AND type (strict)
!= / !==Not equal / not equal value or type
< > <= >=Less / greater than (or equal)
LogicalMeaning
&&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.

Conditionals & Loops

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";
}
Conditionals & Loops

JavaScript Loop Types

LoopUse
forKnown number of iterations.
whileRepeats while the condition is true.
do...whileAlways runs at least once.
for...inIterates over object properties.
for...ofIterates 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);
}
Conditionals & Loops

Activity — complete the code

Complete the conditional and the loops.

if (hour < 18) {
greeting = "Good day";
} {
greeting = "Good evening";
}
 
// Known number of iterations
for (var i = 0; i < 5; ) {
console.log(i);
}
 
// Iterate over iterable values
for (var fruit fruits) {
console.log(fruit);
}

Lesson

Errors & Popup Boxes

The three types of errors and the three popup dialogs.

Errors & Popup Boxes

JavaScript Errors

TypeDescription
Load-time errorsSyntax errors that prevent the script from loading (missing brackets, typos).
Run-time errorsErrors during execution — undefined variables, calling non-functions, division by zero.
Logic errorsCode runs fine but produces wrong results. Hardest to detect — use console.log() to debug.
Errors & Popup Boxes

Popup Box Types

MethodBehaviour
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");
Errors & Popup Boxes

Chapter 5 Topics

Origin · Overview · Syntax · Variables · Operators · Functions · Events · Dates · Arrays · Conditionals · Loops · Errors · Popups.

Errors & Popup Boxes

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