Unit 2 - Notes

INT219 6 min read

Unit 2: JavaScript Programming Fundamentals

1. JavaScript Syntax and Data Types

JavaScript is the scripting language of the web, enabling dynamic content and interactivity. It is an interpreted, lightweight, JIT (Just-In-Time) compiled language with first-class functions.

Basic Syntax

  • Case Sensitivity: JavaScript is case-sensitive (myVariable is different from myvariable).
  • Statements: Instructions are executed sequentially. While semicolons (;) are often optional due to Automatic Semicolon Insertion (ASI), explicit use is recommended for best practice.
  • Comments:
    • Single-line: // Comment here
    • Multi-line: /* Comment here */

Data Types

JavaScript is dynamically typed, meaning variables do not hold types; values do. A variable can change types during execution.

Primitive Types (Immutable)

  1. String: Textual data surrounded by quotes (" ", ' ') or backticks (` `).
  2. Number: Represents both integers and floating-point numbers. Special values include Infinity, -Infinity, and NaN (Not a Number).
  3. BigInt: For integers larger than the Number type can safely represent. Appended with n (e.g., 9007199254740991n).
  4. Boolean: Logical entity having two values: true and false.
  5. Undefined: A variable that has been declared but not assigned a value.
  6. Null: Represents the intentional absence of any object value.
  7. Symbol: A unique and immutable primitive introduced in ES6, often used as object keys.

Reference Types (Mutable)

  • Object: Collections of key-value pairs (includes Arrays, Functions, Dates, etc.).

JAVASCRIPT
// Examples of Data Types
let username = "Alice";      // String
let age = 25;                // Number
let isLoggedIn = true;       // Boolean
let emptyValue = null;       // Null
let notAssigned;             // Undefined (automatically)
let userObj = { id: 1 };     // Object

console.log(typeof age);     // Output: "number"


2. Variables and Scope

Variable Declaration Keywords

Modern JavaScript (ES6+) provides three ways to declare variables:

Keyword Scope Reassignable? Hoisting Behavior Best Use Case
var Function Scope Yes Initialized as undefined Legacy code (avoid in new code)
let Block Scope Yes Temporal Dead Zone (Error) Values that change (loops, counters)
const Block Scope No Temporal Dead Zone (Error) Values that remain constant

Scope Levels

  1. Global Scope: Variables declared outside any function or block. Accessible everywhere.
  2. Function Scope: Variables declared inside a function. Accessible only within that function.
  3. Block Scope: Variables declared inside {} (e.g., if-statements, loops). Only applies to let and const.

Variable Naming Rules

  • Must start with a letter, underscore (_), or dollar sign ($).
  • Subsequent characters can be digits (0-9).
  • Cannot use reserved keywords (e.g., class, return, function).
  • Convention: Use camelCase (e.g., firstName, itemCount).

JAVASCRIPT
if (true) {
    var globalish = "I leak out of blocks";
    let localized = "I stay in this block";
    const pi = 3.14;
}

console.log(globalish); // Works
// console.log(localized); // ReferenceError


3. Operators and Expressions

Arithmetic Operators

  • Addition (+), Subtraction (-), Multiplication (*), Division (/).
  • Modulus (%): Returns the division remainder.
  • Exponentiation (**): Powers (e.g., 2 ** 3 = 8).
  • Increment (++) and Decrement (--).

Comparison Operators

  • Loose Equality (==): Compares values after type conversion (e.g., 5 == "5" is true). Avoid using.
  • Strict Equality (===): Compares value and type (e.g., 5 === "5" is false). Always use.
  • Inequality: != (loose) and !== (strict).
  • Relational: >, <, >=, <=.

Logical Operators

  • AND (&&): Returns true if both operands are true.
  • OR (||): Returns true if at least one operand is true.
  • NOT (!): Inverts the boolean value.
  • Short-circuit evaluation: false && expr evaluates to false immediately; true || expr evaluates to true immediately.

Ternary Operator

A shorthand for if...else.

  • Syntax: condition ? expressionIfTrue : expressionIfFalse

JAVASCRIPT
let age = 20;
let status = (age >= 18) ? "Adult" : "Minor"; 


4. Control Flow Statements

Conditional Statements

  • if / else if / else: Executes code blocks based on boolean conditions.
  • switch: Compares an expression against multiple case clauses. Useful for single variable checks against many values.

JAVASCRIPT
let day = 3;
switch (day) {
    case 1: console.log("Monday"); break;
    case 2: console.log("Tuesday"); break;
    default: console.log("Other day");
}

Loops

  • for loop: Use when the number of iterations is known.
    • Syntax: for (initialization; condition; update) { ... }
  • while loop: loops while a condition is true.
  • do...while loop: Executes at least once, then checks the condition.
  • for...of: Iterates over iterable objects (arrays, strings).
  • for...in: Iterates over the properties (keys) of an object.

5. Functions and Arrow Functions

Functions are reusable blocks of code.

Function Declaration

Hoisted to the top of the scope (can be called before definition).

JAVASCRIPT
function add(a, b) {
    return a + b;
}

Function Expression

Assigning a function to a variable. Not hoisted.

JAVASCRIPT
const subtract = function(a, b) {
    return a - b;
};

Arrow Functions (ES6)

A concise syntax for writing function expressions.

  • Syntax: (parameters) => { body }
  • Implicit Return: If the body is a single expression, {} and return can be omitted.
  • this Binding: Arrow functions do not have their own this; they inherit it from the parent scope.

JAVASCRIPT
// Explicit return
const multiply = (x, y) => {
    return x * y;
};

// Implicit return (one-liner)
const divide = (x, y) => x / y;


6. Arrays and Objects

Arrays

Ordered lists of values, indexed starting at 0.

  • Creation: const arr = [1, 2, 3];
  • Access: arr[0]
  • Common Methods:
    • push() / pop(): Add/remove from end.
    • unshift() / shift(): Add/remove from start.
    • slice(): Returns a portion of an array (non-destructive).
    • splice(): Adds/removes items (destructive).
  • Iteration Methods (High Order):
    • forEach(): Execute a function for every element.
    • map(): Create a new array by transforming every element.
    • filter(): Create a new array with elements that pass a test.

Objects

Unordered collections of key-value pairs.

  • Creation: const person = { name: "John", age: 30 };
  • Access:
    • Dot notation: person.name
    • Bracket notation: person["name"] (Required if key has spaces or is a variable).
  • Methods: Functions stored as object properties.

JAVASCRIPT
const car = {
    brand: "Toyota",
    start: function() {
        console.log("Engine started");
    }
};
car.start();


7. Basic Event Handling

Events are signals that something has happened in the browser (e.g., clicks, key presses, page load).

Event Listeners

The standard way to handle events is addEventListener. It allows multiple handlers for the same event and separates JavaScript from HTML.

  • Syntax: element.addEventListener(event, callbackFunction);

Common Events

  • Mouse: click, dblclick, mouseenter, mouseleave.
  • Keyboard: keydown, keyup, keypress.
  • Form: submit, change, focus, blur.
  • Window: load, resize, scroll.

The Event Object

The callback function receives an event object (usually named e or event) containing details about the event.

  • e.target: The element that triggered the event.
  • e.preventDefault(): Stops the default browser action (e.g., prevents form submission refreshing the page).

JAVASCRIPT
const btn = document.querySelector('button');

btn.addEventListener('click', (e) => {
    console.log("Button clicked!");
    console.log("Clicked element ID:", e.target.id);
});


8. Introduction to Browser Interaction (DOM)

The Document Object Model (DOM) is a tree-like representation of the HTML document. JavaScript interacts with the DOM to manipulate the web page.

Selecting Elements

  • document.getElementById('id'): Selects a single element by ID.
  • document.querySelector('css-selector'): Selects the first element matching the CSS selector (class, ID, tag).
  • document.querySelectorAll('css-selector'): Selects all matching elements (returns a NodeList).

Manipulating Content

  • Text: element.textContent = "New Text"; (Safe, ignores HTML tags).
  • HTML: element.innerHTML = "<span>Bold</span>"; (Parses HTML tags).

Manipulating Styles and Classes

  • Style Object: element.style.backgroundColor = "red"; (CamelCase CSS properties).
  • ClassList:
    • element.classList.add('active')
    • element.classList.remove('active')
    • element.classList.toggle('active')

Creating and Appending Elements

  1. Create: const newDiv = document.createElement('div');
  2. Modify: newDiv.textContent = "Hello World";
  3. Append: document.body.appendChild(newDiv);

JAVASCRIPT
// Example: Change text of a paragraph
const p = document.querySelector('.my-paragraph');
p.style.color = 'blue';
p.textContent = 'Updated via JavaScript';