CoachingUgosay

Web Development - JavaScript Documentation

The programming language of the web that powers modern interactive websites

JavaScript Concepts

Variables & Data Types

Store and manipulate data in your JavaScript applications

var

var name = "John";
  • Function-scoped
  • Can be redeclared
  • Avoid in modern JS

let

let age = 30;
  • Block-scoped
  • Can be reassigned
  • Preferred for variables

const

const PI = 3.14;
  • Block-scoped
  • Cannot be reassigned
  • Default choice

Data Types

Primitive Types

  • SString
  • NNumber
  • BBoolean
  • NNull
  • UUndefined
  • SSymbol
  • BBigInt

Structural Types

  • OObject
  • AArray
  • FFunction

Use typeof operator to check types

Operators

Perform operations on variables and values

Arithmetic

+
5 + 3 โ†’ 8
Addition
-
10 - 2 โ†’ 8
Subtraction
*
4 * 2 โ†’ 8
Multiplication
/
8 / 2 โ†’ 4
Division
%
5 % 2 โ†’ 1
Remainder
**
2 ** 3 โ†’ 8
Exponentiation

Comparison

==
'5' == 5 โ†’ true
Loose equality
===
'5' === 5 โ†’ false
Strict equality
!=
'5' != 5 โ†’ false
Loose inequality
!==
'5' !== 5 โ†’ true
Strict inequality
>
5 > 3 โ†’ true
Greater than
<
5 < 3 โ†’ false
Less than

Logical

&&
true && false โ†’ false
Logical AND
||
true || false โ†’ true
Logical OR
!
!true โ†’ false
Logical NOT

Ternary Operator

const result = condition ? 'Yes' : 'No';

Functions

Reusable blocks of code that perform specific tasks

Function Types

Function Declaration

function greet(name) {
  return `Hello, ${name}!`;
}
  • Hoisted (can be called before declaration)
  • Has its own this context

Arrow Function (ES6+)

const greet = name => `Hello, ${name}!`;
  • Lexical this (inherits from parent scope)
  • Concise syntax for simple functions

Advanced Features

Default Parameters

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

Parameters can have default values when not provided

Rest Parameters

function sum(...numbers) {
  return numbers.reduce((a, b) => a + b, 0);
}

Collects all remaining arguments into an array

Closures

function outer() {
  const message = 'Hello';
  
  function inner() {
    console.log(message);
  }
  
  return inner;
}

Functions remember their lexical scope even when executed outside it

DOM Manipulation

Interact with and modify web page content

Selecting Elements

Single Element

const el = document.querySelector('.class');

Multiple Elements

const els = document.querySelectorAll('p');

Traditional Methods

document.getElementById('id');
document.getElementsByClassName('class');
document.getElementsByTagName('div');

Modifying Elements

Content

el.textContent = 'New text';
el.innerHTML = '<strong>Bold</strong> text';

Attributes

el.setAttribute('id', 'newId');
el.className = 'active';

Styles

el.style.color = 'blue';
el.style.fontSize = '20px';

Event Handling

// Add event listener
button.addEventListener('click', function() {
  console.log('Button clicked!');
});

// Common events
element.addEventListener('mouseover', handleHover);
input.addEventListener('focus', handleFocus);
form.addEventListener('submit', handleSubmit);

Remember to remove event listeners with removeEventListener() when no longer needed to prevent memory leaks

Making Decisions in Code

Control what happens in your program based on conditions

The Basic If Statement

Make simple yes/no decisions

// Check if user is old enough
const age = 18;

if (age >= 18) {
  console.log("Access granted!");
}

How it works:

  1. JavaScript checks the condition in parentheses
  2. If true, runs the code inside the curly braces
  3. If false, skips the code block entirely

Real-world use: Validating inputs, checking permissions

If...Else Statement

Choose between two options

// Determine if a number is even or odd
const number = 7;

if (number % 2 === 0) {
  console.log("Even number");
} else {
  console.log("Odd number");
}

Key points:

  • The else block runs when the condition is false
  • Only one block will ever execute
  • Great for binary (either/or) decisions

Try it: Change the number value and see what happens

Else If Ladder

Handle multiple possible conditions

// Grade calculator
const score = 85;

if (score >= 90) {
  console.log("Grade: A");
} else if (score >= 80) {
  console.log("Grade: B");
} else if (score >= 70) {
  console.log("Grade: C");
} else {
  console.log("Grade: D or below");
}

Important:

  • Conditions are checked in order
  • Only the first true condition runs
  • The else at the end catches all remaining cases

Real-world use: Grading systems, tiered pricing

Switch Statement

Clean alternative to long else-if chains

// Handle different user roles
const role = 'editor';

switch (role) {
  case 'admin':
    console.log("Full access");
    break;
  case 'editor':
    console.log("Can edit content");
    break;
  case 'viewer':
    console.log("Can view only");
    break;
  default:
    console.log("Unknown role");
}

Remember:

  • Uses strict equality (===) for comparisons
  • break prevents "falling through" to next case
  • default runs if no cases match

Tip: Use switch when comparing one variable against many exact values

Comparison Operators

Tools for creating conditions

===

Strict equal (value and type)

5 === 5 โ†’ true

!==

Strict not equal

5 !== "5" โ†’ true

>

Greater than

10 > 5 โ†’ true

<

Less than

10 < 5 โ†’ false

>=

Greater than or equal

10 >= 10 โ†’ true

<=

Less than or equal

10 <= 5 โ†’ false

Common Mistake:

Using = (assignment) instead of === (comparison)

Loops - Repeating Actions

Learn how to repeat code blocks efficiently

for Loop

Best when you know how many times to repeat

// Count from 0 to 4
for (let i = 0; i < 5; i++) {
  console.log("Count:", i);
}

How it works:

  1. Start with i = 0
  2. Check if i < 5
  3. Run the code block
  4. Increase i by 1
  5. Repeat until condition is false

Real-world use: Processing each item in a list

while Loop

Best when you're not sure how many times to repeat

// Keep asking until we get a valid age
let age;
while (!age || age < 0) {
  age = prompt("Enter your age:");
}

Key points:

  • Checks condition before running
  • Might never run if condition is false initially
  • Don't forget to update your condition!

Real-world use: Validating user input

do...while Loop

When you need to run at least once

// Show menu until user quits
let choice;
do {
  choice = showMenu();
  processChoice(choice);
} while (choice !== 'quit');

Key differences:

  • Runs code first, then checks condition
  • Guaranteed to run at least once
  • Useful for menus and user interactions

Real-world use: Game loops, menu systems

Working with Arrays

Modern ways to loop through arrays

1forEach - Do something with each item

['dog', 'cat', 'bird'].forEach(pet => {
  console.log('I have a', pet);
});

Simple way to process each array element

2map - Create a new array from an existing one

const lengths = ['dog', 'cat', 'bird']
  .map(pet => pet.length);
// [3, 3, 4]

Transform each element without changing the original

Tip: Start with forEach for simple loops, then learn map, filter, and reduce as you progress.

Arrays - Lists of Data

Store and manage collections of information

Array Fundamentals

The building blocks of working with lists

// Create an array
let fruits = ['apple', 'banana', 'orange'];

// Access elements (starts at 0)
let first = fruits[0]; // 'apple'
let last = fruits[fruits.length - 1]; // 'orange'

// Update an element
fruits[1] = 'pear';

Important Notes:

  • Arrays are zero-indexed (first item is 0)
  • Use length to get item count
  • Arrays can mix different data types

Try it yourself:

Create an array of your favorite colors and try accessing different positions.

Essential Array Methods

Most useful operations for beginners

Adding/Removing Items

fruits.push('grape'); // end

Add to end

fruits.pop(); // remove end

Remove from end

Finding Items

fruits.includes('apple');

Check if exists

fruits.indexOf('banana');

Find position

Copying/Modifying

let some = fruits.slice(1,3);

Copy portion

fruits.splice(1, 1);

Remove items

Remember: push/pop are for the end, slice makes copies, splice modifies the original.

Objects - Structured Data

Group related information together

Object Basics

Key-value pairs for describing things

// Describe a person
let person = {
  name: 'Alex',
  age: 28,
  hobbies: ['reading', 'hiking'],
  address: {
    city: 'Boston',
    state: 'MA'
  }
};

Accessing Properties:

person.name // 'Alex'

Dot notation

person['age'] // 28

Bracket notation

Think of objects like: A dictionary (word + definition) or a form (field name + value)

Modifying Objects

Changing and using your data

Adding/Updating Properties

// Add new property
person.job = 'Developer';

// Update existing
person.age = 29;

// Nested objects
person.address.zip = '02108';

Adding Functions (Methods)

person.greet = function() {
  console.log('Hello! My name is ' + this.name);
};

// Call the method
person.greet();

Practice: Create an object for a book with title, author, and a method to display its info.

Helpful Object Utilities

Tools for working with objects

Object.keys()

const keys = Object.keys(person);
// ['name', 'age', 'hobbies', 'address']

Get an array of all property names

Object.values()

const values = Object.values(person);
// ['Alex', 28, ['reading', 'hiking'], {...}]

Get an array of all property values

Note: These methods return arrays, so you can use array methods like forEach on the results.

Hands-On Activities

Practice what you have learned with these interactive challenges

Variable Challenge

Task:

Create three variables:

  • A const for PI (3.14)
  • A let for a counter
  • A var for your name
// Your solution here


// Test your solution:
console.log(PI);
console.log(counter);
console.log(name);

Function Challenge

Task:

Create a function that takes a name and returns a greeting message.

function greet(name) {
  // Your code here
}

// Test your solution:
console.log(greet("Alice")); // Should output "Hello, Alice!"

DOM Challenge

Task:

Select the button below and change its text when clicked.

const button = document.querySelector('#activity-btn');

button.addEventListener('click', () => {
  // Your code here
});

Array Challenge

Task:

Given this array, create a new array with only numbers greater than 5.

const numbers = [3, 8, 1, 5, 12, 4, 7];

// Your solution here

// Should output [8, 12, 7]

Hint: Use the filter() method