Week 07: JavaScript Fundamentals

Unit III - Programming the Web

Welcome to the language of the web!

JS

What You'll Learn

  • JavaScript basics: variables, data types
  • Operators and expressions
  • Control flow: if, else, loops
  • Functions and scope

Why JavaScript?

  • Only programming language browsers understand
  • Makes web pages interactive
  • Runs on servers (Node.js)
  • Mobile apps, desktop apps, games...
  • Most in-demand programming language!

Press → or click Next to continue

Press M for slide menu | Press ? for keyboard shortcuts

Adding JavaScript to HTML

1. Inline (Avoid!)

<button onclick="alert('Hi!')">
    Click me
</button>

2. Internal Script

<script>
    console.log('Hello, World!');
</script>

3. External File (Best!)

<!-- At end of body -->
<script src="script.js"></script>

Where to Place Scripts?

At the end of <body> or use defer:

<head>
    <script src="app.js" defer></script>
</head>

Why? HTML loads first, then JavaScript runs. Prevents blocking page render.

Console is Your Friend!

Open browser DevTools (F12) → Console tab to see JavaScript output and errors!

console.log('Debug message');
console.error('Error!');
console.warn('Warning!');

Variables

Variables are containers for storing data values.

Declaring Variables

// Modern way (ES6+)
let name = 'John';      // Can be reassigned
const PI = 3.14159;     // Cannot be reassigned

// Old way (avoid!)
var age = 25;           // Function scoped, hoisted

let vs const

  • let - value can change later
  • const - value never changes

Best Practice

Use const by default. Only use let if you need to reassign!

Naming Rules

  • Start with letter, _ or $
  • Can contain letters, numbers, _ , $
  • Case-sensitive (name ≠ Name)
  • Cannot use reserved words (let, const, if...)

Naming Conventions

// camelCase (preferred)
let firstName = 'John';
let totalPrice = 99.99;

// UPPER_CASE for constants
const MAX_SIZE = 100;
const API_KEY = 'abc123';

var has confusing hoisting behavior. Always use let or const!

Data Types

JavaScript is dynamically typed - variables can hold any type!

Primitive Types

// String - text
let name = 'John';
let message = "Hello";
let template = `Hi ${name}!`;  // Template literal

// Number - integers and decimals
let age = 25;
let price = 19.99;
let negative = -10;

// Boolean - true or false
let isActive = true;
let isLoggedIn = false;

// Undefined - declared but no value
let x;  // x is undefined

// Null - intentionally empty
let data = null;

Checking Types

typeof 'hello'    // "string"
typeof 42         // "number"
typeof true       // "boolean"
typeof undefined  // "undefined"
typeof null       // "object" (JS quirk!)
typeof {}         // "object"
typeof []         // "object"

Type Coercion

// JavaScript auto-converts types!
'5' + 3     // "53" (string)
'5' - 3     // 2 (number)
'5' == 5    // true (loose equality)
'5' === 5   // false (strict equality)

Always use === (strict equality) to avoid surprises!

Operators

Arithmetic

let a = 10, b = 3;

a + b    // 13 (addition)
a - b    // 7 (subtraction)
a * b    // 30 (multiplication)
a / b    // 3.333... (division)
a % b    // 1 (modulo/remainder)
a ** b   // 1000 (exponent)

Assignment

let x = 10;
x += 5;   // x = x + 5 → 15
x -= 3;   // x = x - 3 → 12
x *= 2;   // x = x * 2 → 24
x /= 4;   // x = x / 4 → 6

// Increment/Decrement
x++;      // x = x + 1
x--;      // x = x - 1

Comparison

5 == '5'   // true (loose)
5 === '5'  // false (strict)
5 != '5'   // false
5 !== '5'  // true
5 > 3      // true
5 < 3      // false
5 >= 5     // true
5 <= 4     // false

Logical

true && true   // true (AND)
true && false  // false
true || false  // true (OR)
false || false // false
!true          // false (NOT)
!false         // true

Short-circuit Evaluation

const name = user && user.name;
const value = input || 'default';

Working with Strings

Creating Strings

// Three ways
let s1 = 'single quotes';
let s2 = "double quotes";
let s3 = `template literal`;

// Template literals - best!
let name = 'John';
let greeting = `Hello, ${name}!`;
let multi = `Line 1
Line 2
Line 3`;

String Properties & Methods

let str = 'Hello, World!';

str.length         // 13
str.toUpperCase()  // "HELLO, WORLD!"
str.toLowerCase()  // "hello, world!"
str.trim()         // Remove whitespace

Common String Methods

let str = 'Hello, World!';

// Finding
str.indexOf('World')    // 7
str.includes('Hello')   // true
str.startsWith('He')    // true
str.endsWith('!')       // true

// Extracting
str.slice(0, 5)         // "Hello"
str.slice(-6)           // "World!"
str.substring(7, 12)    // "World"

// Modifying (returns new string!)
str.replace('World', 'JS')  // "Hello, JS!"
str.split(', ')         // ["Hello", "World!"]

// Combining
'Hello' + ' ' + 'World'  // "Hello World"
['Hello', 'World'].join(' ')  // "Hello World"

Arrays

Arrays store multiple values in a single variable.

Creating Arrays

// Array literal (preferred)
let fruits = ['apple', 'banana', 'orange'];
let numbers = [1, 2, 3, 4, 5];
let mixed = [1, 'two', true, null];

// Accessing elements (0-indexed!)
fruits[0]    // 'apple'
fruits[1]    // 'banana'
fruits[2]    // 'orange'
fruits[3]    // undefined

// Modifying
fruits[1] = 'mango';  // Replace
fruits.length         // 3

Array Destructuring

const [first, second] = fruits;
// first = 'apple', second = 'banana'

Common Array Methods

let arr = [1, 2, 3];

// Adding/Removing
arr.push(4)      // Add to end → [1,2,3,4]
arr.pop()        // Remove from end → [1,2,3]
arr.unshift(0)   // Add to start → [0,1,2,3]
arr.shift()      // Remove from start → [1,2,3]

// Finding
arr.indexOf(2)       // 1
arr.includes(2)      // true
arr.find(x => x > 1) // 2

// Transforming
arr.map(x => x * 2)      // [2, 4, 6]
arr.filter(x => x > 1)   // [2, 3]
arr.reduce((a, b) => a + b, 0)  // 6

// Other
arr.slice(1, 2)      // [2] - extract
arr.splice(1, 1)     // Remove at index
arr.join(', ')       // "1, 2, 3"
arr.reverse()        // [3, 2, 1]
arr.sort()           // Sort alphabetically

Control Flow - Conditionals

if...else

let age = 18;

if (age >= 18) {
    console.log('Adult');
} else if (age >= 13) {
    console.log('Teenager');
} else {
    console.log('Child');
}

// Single line (simple cases)
if (age >= 18) console.log('Adult');

Ternary Operator

// condition ? ifTrue : ifFalse
let status = age >= 18 ? 'adult' : 'minor';

// Can be nested (but don't!)
let category = age >= 18
    ? 'adult'
    : age >= 13
        ? 'teen'
        : 'child';

switch

let day = 'Monday';

switch (day) {
    case 'Monday':
    case 'Tuesday':
    case 'Wednesday':
    case 'Thursday':
    case 'Friday':
        console.log('Weekday');
        break;
    case 'Saturday':
    case 'Sunday':
        console.log('Weekend');
        break;
    default:
        console.log('Invalid day');
}

Don't forget break! Without it, execution "falls through" to next case.

Control Flow - Loops

for loop

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

// Looping arrays
const fruits = ['apple', 'banana', 'orange'];

for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

for...of (Arrays)

// Preferred for arrays!
for (const fruit of fruits) {
    console.log(fruit);
}

// With index
for (const [index, fruit] of fruits.entries()) {
    console.log(index, fruit);
}

while loop

let count = 0;

while (count < 5) {
    console.log(count);
    count++;
}

// do...while (runs at least once)
do {
    console.log(count);
    count++;
} while (count < 5);

Loop Control

// break - exit loop entirely
for (let i = 0; i < 10; i++) {
    if (i === 5) break;
    console.log(i);  // 0, 1, 2, 3, 4
}

// continue - skip to next iteration
for (let i = 0; i < 5; i++) {
    if (i === 2) continue;
    console.log(i);  // 0, 1, 3, 4
}

Functions

Functions are reusable blocks of code.

Function Declaration

function greet(name) {
    return `Hello, ${name}!`;
}

greet('John');  // "Hello, John!"

// Multiple parameters
function add(a, b) {
    return a + b;
}

add(5, 3);  // 8

Default Parameters

function greet(name = 'Guest') {
    return `Hello, ${name}!`;
}

greet();        // "Hello, Guest!"
greet('John');  // "Hello, John!"

Arrow Functions (ES6)

// Arrow function syntax
const greet = (name) => {
    return `Hello, ${name}!`;
};

// Shorter: implicit return
const greet = (name) => `Hello, ${name}!`;

// Even shorter: single param
const greet = name => `Hello, ${name}!`;

// No params
const sayHi = () => 'Hi!';

// Multiple params need ()
const add = (a, b) => a + b;

When to Use Which?

  • Arrow functions: Short callbacks, array methods
  • Regular functions: Object methods, constructors

Scope

Scope determines where variables are accessible.

Global Scope

// Accessible everywhere
const globalVar = 'I am global';

function test() {
    console.log(globalVar);  // Works!
}

Function Scope

function test() {
    const localVar = 'I am local';
    console.log(localVar);  // Works!
}

console.log(localVar);  // Error!

Block Scope (let, const)

if (true) {
    let blockVar = 'I am block scoped';
    const alsoBlock = 'Me too';
}

console.log(blockVar);  // Error!

var vs let

// var is function scoped (confusing!)
if (true) {
    var x = 5;
}
console.log(x);  // 5 (still accessible!)

// let is block scoped (predictable)
if (true) {
    let y = 5;
}
console.log(y);  // Error!

Closure

Functions remember their scope:

function outer() {
    let count = 0;
    return function inner() {
        count++;
        return count;
    };
}

const counter = outer();
counter();  // 1
counter();  // 2
counter();  // 3

CampusKart Milestone: Smart Forms

Deliverable: Form validation + price calculator + search/filter logic

What to Build

  • Product form validation (title required, price > 0, description min 20 chars)
  • Registration validation (email format, password strength, confirm match)
  • Price calculator (show price after 10% platform fee)
  • Product search function (filter by keyword)
  • Category filter function

Progress Check

Your forms look great (CSS). They collect data (HTML). Now they can think (JavaScript).

Push to GitHub when done.

Video Resources

JavaScript in 100 Seconds - Fireship

Frontend Masters

Getting Started with JS

Kyle Simpson's beginner course

JavaScript.info

javascript.info

The Modern JavaScript Tutorial

MDN

JavaScript Guide

Official documentation

Practice Exercises

Exercise 1: Variables

  • Create variables of each type
  • Use template literals
  • Check types with typeof

Exercise 2: Calculator

  • Write functions: add, subtract, multiply, divide
  • Handle division by zero
  • Use arrow functions

Exercise 3: Array Operations

  • Filter even numbers
  • Double all values with map
  • Find sum with reduce

Exercise 4: FizzBuzz

  • Print 1-100
  • Fizz for multiples of 3
  • Buzz for multiples of 5
  • FizzBuzz for both

Examples to Study

View Week 07 Examples →

Week 07 Summary

Key Concepts

  • Variables: let (reassignable), const (constant)
  • Types: string, number, boolean, null, undefined
  • Operators: arithmetic, comparison, logical
  • Strings: template literals, string methods
  • Arrays: push, pop, map, filter, reduce
  • Control: if/else, switch, for, while
  • Functions: declaration, arrow functions
  • Scope: global, function, block

Best Practices

  • Use const by default, let when needed
  • Never use var
  • Always use === for comparison
  • Use template literals for strings
  • Use for...of for array iteration
  • Keep functions small and focused
  • Use descriptive variable names

Coming Next Week

Week 08: JavaScript DOM & Events - Making pages interactive!