Course එකට ආපසු

JavaScript Deep Dive — The Brain

45 මිනිත්තු📖Lecture

JavaScript Deep Dive — The Brain

JavaScript (JS) makes pages interactive and dynamic.

  • HTML = structure
  • CSS = appearance
  • JS = behavior

Without JS: Static pages that just display content
With JS: Dynamic apps that respond to users


Variables: Storing Data

Variables are named containers for storing information.

JavaScript
const name = "Alex"; // CONSTANT - cannot be changed
let age = 25; // VARIABLE - can be changed
var old = "legacy"; // OLD WAY - avoid using
Keyword
Changes?
const
No
let
Yes
var
Yes

Rule of Thumb

Use const by default, let only when you need to change the value.


Data Types

String (Text)

JavaScript
const greeting = "Hello, World!";
const name = 'Alex'; // Single quotes work too
const template = `Hello, ${name}`; // Template literal (backticks)

Number

JavaScript
const count = 42;
const price = 19.99;
const negative = -10;

Boolean (True/False)

JavaScript
const isLoggedIn = true;
const hasError = false;

Array (List)

JavaScript
const fruits = ["apple", "banana", "orange"];
// Access by index (starts at 0)
fruits[0]; // "apple"
fruits[1]; // "banana"
fruits.length; // 3

Object (Collection of Properties)

JavaScript
const person = {
name: "Alex",
age: 25,
isStudent: true
};
// Access properties
person.name; // "Alex"
person["age"]; // 25

Null and Undefined

JavaScript
let nothing = null; // Intentionally empty
let notDefined; // undefined (no value assigned)

Functions: Reusable Actions

Functions are blocks of code that perform tasks.

Function Declaration

JavaScript
function greet(name) {
return "Hello, " + name + "!";
}
// Using the function
greet("Alex"); // Returns: "Hello, Alex!"

Arrow Function (Modern Way)

JavaScript
const greet = (name) => {
return "Hello, " + name + "!";
};
// Short version (for simple returns)
const greet = (name) => "Hello, " + name + "!";

Function with Multiple Parameters

JavaScript
function add(a, b) {
return a + b;
}
add(5, 3); // Returns: 8

Conditionals: Making Decisions

If/Else Statement

JavaScript
const age = 18;
if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}

If/Else If/Else

JavaScript
const score = 85;
if (score >= 90) {
console.log("A grade");
} else if (score >= 80) {
console.log("B grade");
} else if (score >= 70) {
console.log("C grade");
} else {
console.log("Need improvement");
}

Comparison Operators

Operator
Meaning
===
Equal to (strict)
!==
Not equal to
>
Greater than
<
Less than
>=
Greater or equal
<=
Less or equal

Logical Operators

JavaScript
// AND - both must be true
if (age >= 18 && hasID) {
console.log("Can enter");
}
// OR - at least one must be true
if (isAdmin || isModerator) {
console.log("Has permissions");
}
// NOT - reverses boolean
if (!isLoggedIn) {
console.log("Please log in");
}

Loops: Repetition

For Loop

JavaScript
for (let i = 0; i < 5; i++) {
console.log(i);
}
// Output: 0, 1, 2, 3, 4

Breakdown:

  • let i = 0 — Start at 0
  • i < 5 — Continue while i is less than 5
  • i++ — Increase i by 1 each time

For...of Loop (Arrays)

JavaScript
const fruits = ["apple", "banana", "orange"];
for (const fruit of fruits) {
console.log(fruit);
}
// Output: apple, banana, orange

forEach Method

JavaScript
const numbers = [1, 2, 3];
numbers.forEach(num => console.log(num * 2));
// Output: 2, 4, 6

DOM Manipulation: Changing the Page

The DOM (Document Object Model) is how JavaScript sees and manipulates HTML.

Selecting Elements

JavaScript
// By ID (returns one element)
const header = document.getElementById("main-header");
// Modern way - querySelector
const firstCard = document.querySelector(".card"); // First match
const allCards = document.querySelectorAll(".card"); // All matches
const navLink = document.querySelector("nav a"); // First <a> in <nav>

Changing Content

JavaScript
const title = document.querySelector("h1");
// Change text
title.textContent = "New Title";
// Change HTML
title.innerHTML = "<span>New</span> Title";

Changing Styles

JavaScript
const box = document.querySelector(".box");
box.style.color = "blue";
box.style.backgroundColor = "white";
box.style.fontSize = "20px";

Changing Classes

JavaScript
const element = document.querySelector(".card");
element.classList.add("active"); // Add class
element.classList.remove("active"); // Remove class
element.classList.toggle("active"); // Toggle on/off
element.classList.contains("active"); // Check if has class

Event Handling: Responding to Users

Events are actions users take (clicks, typing, scrolling).

addEventListener Method

JavaScript
const button = document.querySelector("button");
button.addEventListener("click", () => {
alert("Button was clicked!");
});

Common Events

Event
Triggers When
click
Element is clicked
submit
Form is submitted
input
Input value changes
keydown
Key is pressed
mouseover
Mouse enters element
load
Page finishes loading

Example: Form Handling

JavaScript
const form = document.querySelector("form");
const input = document.querySelector("input");
form.addEventListener("submit", function(event) {
event.preventDefault(); // Stop page refresh
console.log("Input value:", input.value);
});

Putting It Together

JavaScript
// Counter App Logic
// Get elements
const countDisplay = document.getElementById("count");
const incrementBtn = document.getElementById("increment");
const decrementBtn = document.getElementById("decrement");
// Initialize counter
let count = 0;
// Update display function
function updateDisplay() {
countDisplay.textContent = count;
// Change color based on value
if (count > 0) {
countDisplay.style.color = "green";
} else if (count < 0) {
countDisplay.style.color = "red";
} else {
countDisplay.style.color = "black";
}
}
// Event listeners
incrementBtn.addEventListener("click", () => {
count++;
updateDisplay();
});
decrementBtn.addEventListener("click", () => {
count--;
updateDisplay();
});

Lesson Summary

Variables

  • const for constants, let for changeable values

Data Types

  • String, Number, Boolean, Array, Object, null, undefined

Functions

JavaScript
function name(params) { return value; }
const name = (params) => value;

Conditionals

JavaScript
if (condition) { } else if (condition) { } else { }

Loops

JavaScript
for (let i = 0; i < n; i++) { }
for (const item of array) { }
array.forEach(item => { });

DOM

  • Select: document.querySelector()
  • Modify: .textContent, .innerHTML, .style
  • Classes: .classList.add/remove/toggle()

Events

JavaScript
element.addEventListener("event", () => { });

📝 Quiz

1/4

When should you use 'const' vs 'let'?


Next Up

Lesson 2.5: Browser DevTools
Learn to use the most powerful debugging tool available!