James Williams
Birmingham Newman University
jwilliams@staff.newman.ac.uk
3-hour session
// Simple JavaScript example
console.log("Hello, World!");
alert("Welcome to our website!");
See Moodle for supporting materials.
<!-- Method 1: External JavaScript -->
<script src="script.js"></script>
<!-- Method 2: Internal JavaScript -->
<script>
console.log("Hello from internal script");
</script>
<!-- Method 3: Inline JavaScript -->
<button onclick="alert('Hello!')">Click me</button>
// This is a comment
let message = "Hello World";
const PI = 3.14159;
if (condition) {
// code block
}
function greet() {
return "Hello!";
}
// for single-line comments/* */ for multi-line comments{}// Variable declaration
let name = "John";
let age = 25;
let isStudent = true;
// Reassigning values
name = "Jane";
age = 30;
// Constants (cannot be changed)
const PI = 3.14159;
const COMPANY = "Tech Corp";
let: Block-scoped, can be reassignedconst: Block-scoped, cannot be reassignedvar: Function-scoped (avoid in modern JS)// String
let text = "Hello World";
let name = 'John';
// Number
let age = 25;
let price = 19.99;
// Boolean
let isActive = true;
let isLoggedIn = false;
// Undefined
let notDefined;
// Null
let emptyValue = null;
// Arithmetic operators
let sum = 5 + 3; // 8
let diff = 10 - 4; // 6
let product = 6 * 7; // 42
let quotient = 15 / 3; // 5
let remainder = 17 % 5; // 2
// Assignment operators
let x = 10;
x += 5; // Same as x = x + 5
x -= 3; // Same as x = x - 3
x *= 2; // Same as x = x * 2
Click the buttons to perform calculations using JavaScript operators!
// Comparison operators
let a = 5;
let b = "5";
a == b; // true (loose equality)
a === b; // false (strict equality)
a != b; // false
a !== b; // true
a > 3; // true
a >= 5; // true
a < 10; // true
a <= 5; // true
==: Loose equality (converts types)===: Strict equality (no type conversion)=== and !== when possible
// Logical operators
let isLoggedIn = true;
let hasPermission = false;
isLoggedIn && hasPermission; // false (AND)
isLoggedIn || hasPermission; // true (OR)
!isLoggedIn; // false (NOT)
// Short-circuit evaluation
let name = "John" || "Guest"; // "John"
let age = 0 || 25; // 25
&&: AND (both must be true)||: OR (at least one must be true)!: NOT (inverts boolean value)let firstName = "John";
let lastName = "Doe";
// String concatenation
let fullName = firstName + " " + lastName;
// Template literals (ES6)
let greeting = `Hello, ${firstName}!`;
// String methods
let message = "Hello World";
message.length; // 11
message.toUpperCase(); // "HELLO WORLD"
message.toLowerCase(); // "hello world"
message.indexOf("World"); // 6
// Creating arrays
let fruits = ["Apple", "Banana", "Orange"];
let numbers = [1, 2, 3, 4, 5];
let mixed = ["text", 42, true];
// Accessing elements
fruits[0]; // "Apple"
fruits[1]; // "Banana"
// Array methods
fruits.push("Grape"); // Add to end
fruits.pop(); // Remove from end
fruits.unshift("Lemon"); // Add to beginning
fruits.shift(); // Remove from beginning
// Function declaration
function greet(name) {
return `Hello, ${name}!`;
}
// Function expression
let multiply = function(a, b) {
return a * b;
};
// Arrow function (ES6)
let divide = (a, b) => a / b;
// Calling functions
greet("John"); // "Hello, John!"
multiply(5, 3); // 15
divide(10, 2); // 5
I'm thinking of a number between 1 and 100. Can you guess it?
Guesses: 0
This game uses functions to handle game logic, validation, and feedback!
// If statement
let age = 18;
if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}
// Switch statement
let day = "Monday";
switch(day) {
case "Monday":
console.log("Start of week");
break;
default:
console.log("Other day");
}
// For loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
// While loop
let count = 0;
while (count < 3) {
console.log(count);
count++;
}
// For...of loop (arrays)
let fruits = ["Apple", "Banana", "Orange"];
for (let fruit of fruits) {
console.log(fruit);
}
// Selecting elements
let element = document.getElementById("myId");
let elements = document.getElementsByClassName("myClass");
let element = document.querySelector(".myClass");
// Changing content
element.innerHTML = "New content";
element.textContent = "Plain text";
// Changing styles
element.style.color = "red";
element.style.fontSize = "20px";
// Adding/removing classes
element.classList.add("highlight");
element.classList.remove("old-class");
// HTML
<button id="myButton">Click me</button>
// JavaScript
let button = document.getElementById("myButton");
button.addEventListener("click", function() {
alert("Button clicked!");
});
// Arrow function version
button.addEventListener("click", () => {
console.log("Button clicked!");
});
addEventListener for event handlingjs-practice.htmlTime: 45 minutes
This task will help you understand basic JavaScript syntax and concepts
Take a break, ask questions, or catch up on the previous task.
Next: Secondary slides and Task 2
// Try-catch statement
try {
let result = 10 / 0;
console.log(result);
} catch (error) {
console.error("An error occurred:", error.message);
} finally {
console.log("This always runs");
}
// Throwing custom errors
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}
// Global scope
let globalVar = "I'm global";
function myFunction() {
// Local scope
let localVar = "I'm local";
console.log(globalVar); // Can access global
console.log(localVar); // Can access local
}
// Hoisting example
console.log(x); // undefined (not an error)
var x = 5; // var is hoisted
console.log(y); // ReferenceError
let y = 10; // let is not hoisted
// Object literal
let person = {
name: "John",
age: 30,
city: "New York",
greet: function() {
return `Hello, I'm ${this.name}`;
}
};
// Accessing properties
person.name; // "John"
person["age"]; // 30
person.greet(); // "Hello, I'm John"
// Adding properties
person.email = "john@example.com";
// JSON string
let jsonString = '{"name":"John","age":30,"city":"NYC"}';
// Parse JSON to object
let obj = JSON.parse(jsonString);
console.log(obj.name); // "John"
// Convert object to JSON
let person = {name: "Jane", age: 25};
let json = JSON.stringify(person);
console.log(json); // '{"name":"Jane","age":25}'
JSON.parse() converts JSON to objectJSON.stringify() converts object to JSONconsole.log(): Output values to consoleconsole.error(): Log errorsconsole.warn(): Log warningsconsole.table(): Display data in table formatdebugger;: Programmatic breakpoint// Debugging example
let x = 5;
let y = 10;
console.log("x =", x, "y =", y);
console.table({x, y});
debugger; // Execution stops here
let result = x + y;
interactive-page.htmlTime: 45 minutes
This task will help you understand DOM manipulation and event handling
JavaScript Events and Interactivity - Building responsive user interfaces