← Back to Module

JavaScript Basics

CMU422: Fundamentals of Web Design - Session 6

Birmingham Newman University

Lecturer: James Williams

Adding interactivity and dynamic behavior

3-hour session • 25 slides • 2 interactive tasks

Session Timeline:

  • 10 min: Registration & waiting
  • 20 min: Opening slides
  • 45 min: Task 1
  • 15 min: Break/Catch up
  • 20 min: Secondary slides
  • 45 min: Task 2
  • Remaining: Self-study

Learning Objectives

  • Understand what JavaScript is and its role in web development
  • Learn JavaScript syntax and basic concepts
  • Master variables, data types, and operators
  • Create functions and control structures
  • Manipulate the DOM (Document Object Model)

What is JavaScript?

JavaScript is a programming language that adds interactivity to web pages
  • Makes web pages dynamic and interactive
  • Runs in the browser (client-side)
  • Can also run on servers (Node.js)
  • Essential for modern web development
// Simple JavaScript example
console.log("Hello, World!");
alert("Welcome to our website!");

Watch: JavaScript Fundamentals Explained

Comprehensive introduction to JavaScript - the programming language of the web

Adding JavaScript to HTML

<!-- 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>
  • External: Best for multiple pages
  • Internal: Good for single page
  • Inline: Avoid for maintainability

JavaScript Syntax

// This is a comment

let message = "Hello World";
const PI = 3.14159;

if (condition) {
  // code block
}

function greet() {
  return "Hello!";
}
  • Statements end with semicolons (optional but recommended)
  • Use // for single-line comments
  • Use /* */ for multi-line comments
  • Code blocks use curly braces {}

Variables

// 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 reassigned
  • const: Block-scoped, cannot be reassigned
  • var: Function-scoped (avoid in modern JS)
  • Use descriptive variable names

JavaScript Data Types

// 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;
  • String: Text data
  • Number: Integers and decimals
  • Boolean: true or false
  • Undefined: Variable declared but not assigned
  • Null: Intentional absence of value

JavaScript Operators

// 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

Try It: Interactive Calculator

Click the buttons to perform calculations using JavaScript operators!

Comparison 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)
  • Always use === and !== when possible

Logical Operators

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

Working with Strings

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

Arrays

// 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

Functions

// 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

Try It: Number Guessing Game

I'm thinking of a number between 1 and 100. Can you guess it?


Enter a number and click Guess to start!

Guesses: 0

This game uses functions to handle game logic, validation, and feedback!

Control Structures

// 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");
}

Loops

// 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);
}

DOM Manipulation

// 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");

Event Handling

// 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!");
});
  • Common events: click, mouseover, keydown, submit
  • Use addEventListener for event handling
  • Can add multiple event listeners to same element

Task 1: Basic JavaScript Practice

Instructions:

  1. Create a new HTML file called js-practice.html
  2. Add a <script> tag in the <head> section
  3. Practice the following JavaScript concepts:
    • Declare variables with different data types
    • Create a function that takes parameters
    • Use arithmetic and comparison operators
    • Create an array and access its elements
    • Use a loop to iterate through the array
    • Add a button that triggers a JavaScript function
  4. Use console.log() to see your output

Time: 45 minutes

This task will help you understand basic JavaScript syntax and concepts

Break Time

15 Minutes

Take a break, ask questions, or catch up on the previous task.

Next: Secondary slides and Task 2

Error Handling

// 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;
}

Scope and Hoisting

// 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

Objects

// 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 (JavaScript Object Notation)

// 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 is a data format, not a programming language
  • Commonly used for API communication
  • JSON.parse() converts JSON to object
  • JSON.stringify() converts object to JSON

Debugging JavaScript

  • console.log(): Output values to console
  • console.error(): Log errors
  • console.warn(): Log warnings
  • console.table(): Display data in table format
  • Browser Developer Tools: Set breakpoints
  • debugger;: 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;

Task 2: Interactive Web Page

Instructions:

  1. Create a new HTML file called interactive-page.html
  2. Build an interactive page with:
    • Form: Input fields for name, age, and favorite color
    • Button: Submit button that collects form data
    • Display: Show collected data in a formatted way
    • Validation: Check if fields are filled
    • Styling: Change page colors based on favorite color
  3. Use DOM manipulation to update the page
  4. Add event listeners for user interactions
  5. Include error handling for invalid inputs

Time: 45 minutes

This task will help you understand DOM manipulation and event handling

Session Summary

  • JavaScript adds interactivity to web pages
  • Master variables, data types, and operators
  • Use functions to organize and reuse code
  • Control structures manage program flow
  • DOM manipulation creates dynamic content

Next Session:

JavaScript Events and Interactivity - Building responsive user interfaces