Chapter 6: JavaScript Fundamentals

JavaScript is the programming language of the web. Learn variables, functions, conditionals, loops, arrays, objects, and string manipulation.

What you'll learn:
  • Variables and data types (strings, numbers, booleans)
  • Functions with parameters and return values
  • Operators, conditionals, and loops
  • Arrays, objects, and string manipulation

6.1 Introduction to JavaScript

JavaScript is the programming language of the web. It allows you to add interactivity, logic, and dynamic behavior to your websites. While HTML provides structure and CSS provides styling, JavaScript brings your pages to life.

Why Learn JavaScript?

  • It's the only programming language that runs natively in all web browsers
  • Powers both frontend (user interface) and backend (Node.js) development
  • Essential for creating interactive web applications
  • Huge ecosystem of libraries and frameworks (React, Vue, Angular)

Your First JavaScript Code

The simplest way to output something in JavaScript is using console.log():

// This is a comment - it's ignored by JavaScript
console.log("Hello, World!");

// You can log numbers too
console.log(42);

// And do math
console.log(5 + 3);  // Outputs: 8
Comments in JavaScript

Comments are notes for humans that JavaScript ignores:

  • // Single line comment
  • /* Multi-line comment */

6.2 Variables & Data Types

Variables are containers that store data values. Think of them as labeled boxes where you can put information and retrieve it later.

Declaring Variables

JavaScript has three ways to declare variables:

// let - for values that will change
let age = 25;
age = 26;  // Can be reassigned

// const - for values that won't change
const name = "Alice";
// name = "Bob";  // Error! Cannot reassign const

// var - older way (avoid in modern code)
var score = 100;
Best Practice

Use const by default. Only use let when you know the value will change. Avoid var.

Data Types

JavaScript has several primitive data types:

Type Description Example
string Text (in quotes) "Hello", 'World'
number Numbers (integer or decimal) 42, 3.14
boolean True or false true, false
undefined No value assigned let x;
null Intentionally empty let y = null;

Template Literals (Backticks)

Template literals let you embed variables inside strings using ${}:

const name = "Joe";
const age = 30;

// Old way (string concatenation)
const greeting1 = "Hello " + name + ", you are " + age + " years old.";

// New way (template literals - use backticks!)
const greeting2 = `Hello ${name}, you are ${age} years old.`;

console.log(greeting2);  // "Hello Joe, you are 30 years old."
This helps with Exercise 2!

Exercise 2 asks you to create a greeting message like "Hello Joe, how are you?". Use template literals: `Hello ${name}, how are you?`

6.3 Functions

Functions are reusable blocks of code that perform a specific task. They help organize code and avoid repetition.

Function Declaration

// Defining a function
function greet() {
  console.log("Hello!");
}

// Calling (running) the function
greet();  // Outputs: Hello!

Parameters and Arguments

Functions can accept input values called parameters:

// 'name' is a parameter (placeholder)
function sayHello(name) {
  console.log(`Hello ${name}!`);
}

// "Alice" is an argument (actual value)
sayHello("Alice");  // Outputs: Hello Alice!
sayHello("Bob");    // Outputs: Hello Bob!

The return Statement

Functions can send back a value using return:

function addNumbers(a, b) {
  return a + b;  // Sends the result back
}

const sum = addNumbers(5, 3);
console.log(sum);  // Outputs: 8

// You can also use the return value directly
console.log(addNumbers(10, 20));  // Outputs: 30
Important: return vs console.log

return sends a value back to where the function was called. console.log just prints to the console. For the exercises, you need return!

Export Default (For Exercises)

The exercises use export default to make functions available for testing:

// This is the pattern used in the exercises
export default function helloWorld() {
  return "Hello world!";
}

// With parameters
export default function sayHello(name) {
  return `Hello ${name}, how are you?`;
}

6.4 Operators & Expressions

Operators allow you to perform operations on values.

Arithmetic Operators

console.log(10 + 5);   // Addition: 15
console.log(10 - 5);   // Subtraction: 5
console.log(10 * 5);   // Multiplication: 50
console.log(10 / 5);   // Division: 2
console.log(10 % 3);   // Modulo (remainder): 1
console.log(2 ** 3);   // Exponent: 8
Modulo (%) is Key!

The modulo operator returns the remainder after division. It's perfect for checking if a number is even or odd:

  • 10 % 2 === 0 → 10 is even
  • 7 % 2 === 1 → 7 is odd

Comparison Operators

These compare values and return true or false:

console.log(5 === 5);   // Equal: true
console.log(5 !== 3);   // Not equal: true
console.log(5 > 3);     // Greater than: true
console.log(5 < 3);     // Less than: false
console.log(5 >= 5);    // Greater or equal: true
console.log(5 <= 4);    // Less or equal: false
Always Use === (Triple Equals)

=== checks both value AND type. == only checks value and can cause bugs:

  • "5" == 5 → true (unexpected!)
  • "5" === 5 → false (correct)

Logical Operators

Combine multiple conditions:

const age = 25;

// AND (&&) - both must be true
console.log(age >= 20 && age <= 80);  // true (age is between 20-80)

// OR (||) - at least one must be true
console.log(age < 18 || age > 65);  // false (neither is true)

// NOT (!) - reverses the boolean
console.log(!true);   // false
console.log(!false);  // true
This helps with Exercise 5!

To check if a value is between 20 and 80 (inclusive):

age >= 20 && age <= 80

6.5 Conditional Statements

Conditionals let your code make decisions based on conditions.

if Statement

const num = 5;

if (num > 0) {
  console.log("Positive!");
}

if...else Statement

function isPositive(num) {
  if (num > 0) {
    return true;
  } else {
    return false;
  }
}

else if Chains (Exercise 7)

For multiple conditions, use else if:

function calculateGrade(score) {
  if (score >= 90 && score <= 100) {
    return "A";
  } else if (score >= 80) {
    return "B";
  } else if (score >= 70) {
    return "C";
  } else if (score >= 60) {
    return "D";
  } else {
    return "F";
  }
}

switch Statement (Exercise 8)

For checking a value against multiple specific cases:

function getDayType(day) {
  switch (day) {
    case "Saturday":
    case "Sunday":
      return "Weekend";
    case "Monday":
    case "Tuesday":
    case "Wednesday":
    case "Thursday":
    case "Friday":
      return "Weekday";
    default:
      return "Invalid day";
  }
}

6.6 Loops

Loops repeat code multiple times. JavaScript has several loop types.

for Loop (Exercise 11)

Best when you know how many times to repeat:

// for (initialization; condition; update)
for (let i = 1; i <= 5; i++) {
  console.log(i);  // 1, 2, 3, 4, 5
}

// Create array with values 2-10
function integers() {
  const result = [];
  for (let i = 2; i <= 10; i++) {
    result.push(i);
  }
  return result;
}

while Loop (Exercise 12)

Best when you don't know exactly how many iterations:

// Countdown from n to 1
function countDown(n) {
  const result = [];
  while (n >= 1) {
    result.push(n);
    n--;  // Decrease n by 1
  }
  return result;
}

break and continue

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

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

A prime number is only divisible by 1 and itself. Use nested loops to check:

if (num % divisor === 0) means num is divisible by divisor.

6.7 Arrays

Arrays store multiple values in a single variable.

Creating and Accessing Arrays

const fruits = ["apple", "banana", "orange"];

console.log(fruits[0]);     // "apple" (index starts at 0)
console.log(fruits[1]);     // "banana"
console.log(fruits.length); // 3

Array Methods

const nums = [1, 2, 3];

nums.push(4);      // Add to end: [1, 2, 3, 4]
nums.pop();        // Remove from end: [1, 2, 3]
nums.includes(2);  // Check if exists: true

Iterating Arrays (Exercises 14-16)

// Sum all numbers in an array
function sumArray(nums) {
  let sum = 0;
  for (let i = 0; i < nums.length; i++) {
    sum += nums[i];
  }
  return sum;
}

// Count even numbers
function countEven(nums) {
  let count = 0;
  for (let i = 0; i < nums.length; i++) {
    if (nums[i] % 2 === 0) count++;
  }
  return count;
}

// Average of numbers
function average(nums) {
  return sumArray(nums) / nums.length;
}

Creating New Arrays (Exercises 17-20)

// Reverse an array
function reverseArray(arr) {
  const reversed = [];
  for (let i = arr.length - 1; i >= 0; i--) {
    reversed.push(arr[i]);
  }
  return reversed;
}

// Remove duplicates
function removeDuplicates(arr) {
  const unique = [];
  for (let i = 0; i < arr.length; i++) {
    if (!unique.includes(arr[i])) {
      unique.push(arr[i]);
    }
  }
  return unique;
}

6.8 Objects

Objects are one of the most important concepts in JavaScript. They let you group related data together.

Why Use Objects?

Imagine you need to store information about a person: their name, age, and email. Without objects, you'd need 3 separate variables:

let personName = "Alice"; let personAge = 25; let personEmail = "alice@email.com";

With an object, you group all related data together under one name!

What is an Object?

An object is a collection of key-value pairs (called properties). Think of it like a labeled container:

// Think of this like a filing cabinet with labeled drawers
const person = {
  name: "Alice",      // key: "name", value: "Alice"
  age: 25,            // key: "age", value: 25
  isStudent: true     // key: "isStudent", value: true
};

// You can store ANY type of value in an object:
// - Strings, numbers, booleans
// - Arrays, other objects
// - Even functions!

Accessing Properties: Two Ways

There are two ways to get values from an object:

const person = { name: "Alice", age: 25 };

// 1. Dot notation (most common, cleaner)
console.log(person.name);      // "Alice"
console.log(person.age);       // 25

// 2. Bracket notation (needed for dynamic keys)
console.log(person["name"]);   // "Alice"

// Bracket notation shines when the key is in a variable:
const keyName = "age";
console.log(person[keyName]);  // 25 - this works!
console.log(person.keyName);   // undefined - this looks for literal "keyName"
When to Use Bracket Notation

Use brackets obj[key] when:

  • The key is stored in a variable
  • The key has spaces or special characters: obj["full name"]

Modifying Objects

const person = { name: "Alice", age: 25 };

// Change existing property
person.age = 26;

// Add new property
person.email = "alice@email.com";

// Delete a property
delete person.isStudent;

console.log(person);
// { name: "Alice", age: 26, email: "alice@email.com" }
Objects are Mutable

Even though we used const, we can still change the object's properties. const only prevents reassigning the variable, not modifying the object's contents.

Useful Object Methods (Exercises 21-25)

const person = { name: "Alice", age: 25, city: "Athens" };

// Get all keys as an array
Object.keys(person);    // ["name", "age", "city"]

// Get all values as an array
Object.values(person);  // ["Alice", 25, "Athens"]

// Count properties
Object.keys(person).length;  // 3

// Check if property exists
person.hasOwnProperty("name");  // true
person.hasOwnProperty("email"); // false

Looping Through Objects: for...in

const scores = { math: 90, english: 85, science: 92 };

// for...in loops through all KEYS
for (let subject in scores) {
  console.log(subject + ": " + scores[subject]);
}
// Output:
// math: 90
// english: 85
// science: 92
Mindset: Objects vs Arrays

Use Arrays when you have a list of similar items (e.g., list of names)
Use Objects when you have labeled data with different types (e.g., a person's info)

Merging Objects (Spread Operator)

const defaults = { theme: "dark", language: "en" };
const userPrefs = { language: "el" };

// Spread operator (...) copies properties
const merged = { ...defaults, ...userPrefs };

console.log(merged);
// { theme: "dark", language: "el" }
// Note: userPrefs.language overrides defaults.language!

6.9 String Manipulation

Strings can be manipulated like arrays - each character has an index.

String Basics

const text = "Hello";

console.log(text.length);    // 5
console.log(text[0]);        // "H"
console.log(text.toLowerCase()); // "hello"
console.log(text.toUpperCase()); // "HELLO"

String Exercises (26-30)

// Reverse a string
function reverseString(str) {
  let result = "";
  for (let i = str.length - 1; i >= 0; i--) {
    result += str[i];
  }
  return result;
}

// Count vowels
function countVowels(str) {
  const vowels = "aeiouAEIOU";
  let count = 0;
  for (let char of str) {
    if (vowels.includes(char)) count++;
  }
  return count;
}

// Truncate string
function truncate(str, maxLength) {
  if (str.length <= maxLength) return str;
  return str.slice(0, maxLength) + "...";
}

// Count words
function countWords(str) {
  return str.trim().split(" ").filter(w => w).length;
}

6.10 Exercise Mapping Guide

Here's which lesson helps with each exercise:

Exercise Concept Key Lesson
1-3 Functions, return, template literals 6.2, 6.3
4-6 if/else, boolean returns 6.5
7-8 else if chains, switch 6.5
9-10 Complex boolean logic (&&, ||) 6.4, 6.5
11-13 for/while loops 6.6
14-20 Array iteration & manipulation 6.7
21-25 Objects & properties 6.8
26-30 String manipulation 6.9

Exercises

Practice what you've learned by writing code.

Exercise: Functions Practice

Write a function that takes two numbers and returns their sum:

Exercise: Conditionals Practice

Write a function that returns true if a number is positive, false otherwise:

Exercise: Arrays Practice

Write a function that sums all numbers in an array:

Exercise: Strings Practice

Reverse a string:

Final Exercise: Combine Your Skills

Count how many vowels are in a string:

Quizzes

Test your knowledge of JavaScript fundamentals.

Quick Quiz: Introduction

What does console.log() do?

A Creates a new HTML element
B Saves data to a file
C Outputs a message to the console
D Displays an alert box

Quick Quiz: Variables

Which keyword should you use for a value that will never change?

A let
B const
C var
D static

Quick Quiz: Functions

What keyword sends a value back from a function?

A return
B output
C send
D print

Quick Quiz: Operators

What does 10 % 3 return?

A 3.33
B 1
C 3
D 30

Quick Quiz: Conditionals

What does switch use to handle no matches?

A else
B otherwise
C default
D fallback

Quick Quiz: Loops

Which keyword skips to the next loop iteration?

A break
B skip
C next
D continue

Quick Quiz: Arrays

What is the index of the first element in an array?

A 0
B 1
C -1
D first

Quick Quiz: Objects

What does Object.keys(obj) return?

A All values of the object
B Array of property names
C The number of properties
D A copy of the object

Quick Quiz: Strings

What does "hello".toUpperCase() return?

A "Hello"
B "hELLO"
C "HELLO"
D "hello"

Final Check

To check if a number is even, which expression should you use?

A num / 2 === 0
B num == "even"
C num.isEven()
D num % 2 === 0