Unit 2 - Notes
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 (
myVariableis different frommyvariable). - 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 */
- Single-line:
Data Types
JavaScript is dynamically typed, meaning variables do not hold types; values do. A variable can change types during execution.
Primitive Types (Immutable)
- String: Textual data surrounded by quotes (
" ",' ') or backticks (` `). - Number: Represents both integers and floating-point numbers. Special values include
Infinity,-Infinity, andNaN(Not a Number). - BigInt: For integers larger than the
Numbertype can safely represent. Appended withn(e.g.,9007199254740991n). - Boolean: Logical entity having two values:
trueandfalse. - Undefined: A variable that has been declared but not assigned a value.
- Null: Represents the intentional absence of any object value.
- 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.).
// 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
- Global Scope: Variables declared outside any function or block. Accessible everywhere.
- Function Scope: Variables declared inside a function. Accessible only within that function.
- Block Scope: Variables declared inside
{}(e.g., if-statements, loops). Only applies toletandconst.
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).
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 && exprevaluates to false immediately;true || exprevaluates to true immediately.
Ternary Operator
A shorthand for if...else.
- Syntax:
condition ? expressionIfTrue : expressionIfFalse
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 multiplecaseclauses. Useful for single variable checks against many values.
let day = 3;
switch (day) {
case 1: console.log("Monday"); break;
case 2: console.log("Tuesday"); break;
default: console.log("Other day");
}
Loops
forloop: Use when the number of iterations is known.- Syntax:
for (initialization; condition; update) { ... }
- Syntax:
whileloop: loops while a condition is true.do...whileloop: 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).
function add(a, b) {
return a + b;
}
Function Expression
Assigning a function to a variable. Not hoisted.
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,
{}andreturncan be omitted. thisBinding: Arrow functions do not have their ownthis; they inherit it from the parent scope.
// 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).
- Dot notation:
- Methods: Functions stored as object properties.
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).
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
- Create:
const newDiv = document.createElement('div'); - Modify:
newDiv.textContent = "Hello World"; - Append:
document.body.appendChild(newDiv);
// Example: Change text of a paragraph
const p = document.querySelector('.my-paragraph');
p.style.color = 'blue';
p.textContent = 'Updated via JavaScript';