The Road To Dev currently has AI-generated placeholder content. This is temporary - content is being actively developed.

content

JavaScript Fundamentals

Variables, operators, and control flow in JavaScript

JavaScript Fundamentals

JavaScript is the programming language that brings websites to life. This lesson covers the essential building blocks: variables, operators, and control flow structures that form the foundation of all JavaScript programming.

What is JavaScript?

JavaScript is a high-level, interpreted programming language that enables interactive web pages. It's an essential part of web development alongside HTML and CSS:

  • HTML: Structure and content
  • CSS: Styling and layout
  • JavaScript: Behavior and interactivity

Variables

Variables store data that can be used and modified throughout your program.

Variable Declaration

// Modern way (recommended)
let message = "Hello, World!";
const PI = 3.14159;
// Older way (avoid in new code)
var oldStyle = "This works but use let/const instead";

Variable Types

let vs const

  • let: Value can change (mutable)
  • const: Value cannot change (immutable)
let age = 25;
age = 26; // This works
const name = "Alice";
// name = "Bob"; // This would cause an error

Data Types

JavaScript has several built-in data types:

Primitive Types

// String
let firstName = "John";
let lastName = 'Doe';
let fullName = `${firstName} ${lastName}`; // Template literals
// Number
let age = 30;
let price = 99.99;
let temperature = -5;
// Boolean
let isLoggedIn = true;
let hasPermission = false;
// Undefined
let undefinedVariable;
console.log(undefinedVariable); // undefined
// Null
let emptyValue = null;

Checking Types

console.log(typeof "Hello"); // "string"
console.log(typeof 42); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"

Operators

Operators perform operations on values and variables.

Arithmetic Operators

let x = 10;
let y = 3;
console.log(x + y); // 13 (addition)
console.log(x - y); // 7 (subtraction)
console.log(x * y); // 30 (multiplication)
console.log(x / y); // 3.333... (division)
console.log(x % y); // 1 (remainder/modulo)
console.log(x ** y); // 1000 (exponentiation)

Assignment Operators

let score = 100;
score += 10; // score = score + 10; (110)
score -= 5; // score = score - 5; (105)
score *= 2; // score = score * 2; (210)
score /= 3; // score = score / 3; (70)
// Increment and decrement
score++; // score = score + 1;
score--; // score = score - 1;

Comparison Operators

let a = 5;
let b = "5";
// Equality (checks value, converts types)
console.log(a == b); // true
// Strict equality (checks value and type)
console.log(a === b); // false (number vs string)
// Inequality
console.log(a != b); // false
console.log(a !== b); // true
// Relational
console.log(a > 3); // true
console.log(a < 10); // true
console.log(a >= 5); // true
console.log(a <= 4); // false

Logical Operators

let isAdult = true;
let hasPermission = false;
// AND (&&) - both must be true
console.log(isAdult && hasPermission); // false
// OR (||) - at least one must be true
console.log(isAdult || hasPermission); // true
// NOT (!) - flips the boolean value
console.log(!isAdult); // false
console.log(!hasPermission); // true

Control Flow

Control flow determines the order in which code executes.

Conditional Statements (if/else)

let temperature = 25;
if (temperature > 30) {
console.log("It's hot!");
} else if (temperature > 20) {
console.log("It's warm!");
} else if (temperature > 10) {
console.log("It's cool!");
} else {
console.log("It's cold!");
}

Switch Statements

let dayOfWeek = "Monday";
switch (dayOfWeek) {
case "Monday":
console.log("Start of the work week");
break;
case "Tuesday":
case "Wednesday":
case "Thursday":
console.log("Midweek");
break;
case "Friday":
console.log("TGIF!");
break;
case "Saturday":
case "Sunday":
console.log("Weekend!");
break;
default:
console.log("Invalid day");
}

Loops

For Loop

// Print numbers 1 to 5
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// Loop through an array
let fruits = ["apple", "banana", "orange"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}

While Loop

let count = 0;
while (count < 3) {
console.log("Count:", count);
count++;
}

For...of Loop (for arrays)

let colors = ["red", "green", "blue"];
for (let color of colors) {
console.log(color);
}

Practical Examples

Age Category Classifier

function classifyAge(age) {
if (age < 0) {
return "Invalid age";
} else if (age < 13) {
return "Child";
} else if (age < 20) {
return "Teenager";
} else if (age < 65) {
return "Adult";
} else {
return "Senior";
}
}
console.log(classifyAge(16)); // "Teenager"

Grade Calculator

function calculateGrade(score) {
if (score >= 90) {
return "A";
} else if (score >= 80) {
return "B";
} else if (score >= 70) {
return "C";
} else if (score >= 60) {
return "D";
} else {
return "F";
}
}
let studentScore = 85;
console.log(`Grade: ${calculateGrade(studentScore)}`); // "Grade: B"

Simple Counter

let counter = 0;
const maxCount = 10;
while (counter < maxCount) {
if (counter % 2 === 0) {
console.log(`${counter} is even`);
} else {
console.log(`${counter} is odd`);
}
counter++;
}

Best Practices

  1. Use const by default: Only use let when you need to reassign the variable
  2. Use strict equality (===): Avoid type coercion bugs
  3. Use descriptive variable names: userAge instead of a
  4. Initialize variables: Don't leave variables undefined when possible
  5. Use template literals: `Hello ${name}` instead of "Hello " + name

Common Mistakes to Avoid

  1. Assignment vs Equality: = assigns, == or === compares
  2. Infinite loops: Always ensure loop conditions can become false
  3. Case sensitivity: myVariable and myvariable are different
  4. Missing semicolons: While optional, they prevent certain errors

Practice Exercises

Try these exercises to reinforce your understanding:

  1. Create variables for your name, age, and favorite color, then log them
  2. Write a program that determines if a number is even or odd
  3. Create a loop that prints the multiplication table for a given number
  4. Build a simple calculator that performs basic arithmetic operations

Next Steps

Now that you understand variables, operators, and control flow, you're ready to learn about functions - reusable blocks of code that make your programs more organized and efficient. You'll also explore how to manipulate the DOM to make your web pages interactive!

Remember: programming is like learning a new language. The more you practice writing code, the more natural it becomes. Don't worry about memorizing everything - focus on understanding the concepts and practicing regularly.

Lesson Complete!

Great job! You've finished this lesson. Ready to continue?