⚡ JavaScript Basics

JavaScript is a programming language that brings interactivity to websites. While HTML provides structure and CSS provides styling, JavaScript provides behavior and logic.

📝 Note

JavaScript runs in the browser (client-side) and can also run on servers (Node.js). In this course, we focus on browser JavaScript for frontend development.

Adding JavaScript to HTML

There are three ways to include JavaScript in your web page:

1. Inline JavaScript

<!-- Directly in HTML attributes (NOT RECOMMENDED) -->
<button onclick="alert('Hello!')">Click me</button>
⚠️ Avoid Inline JavaScript

Inline JavaScript mixes structure (HTML) with behavior (JavaScript), making code hard to maintain. Use this method only for quick tests.

2. Internal JavaScript

<!-- In a <script> tag within the HTML file -->
<body>
  <button id="myButton">Click me</button>

  <script>
    // JavaScript code goes here
    const button = document.getElementById('myButton');
    button.addEventListener('click', function() {
      alert('Hello!');
    });
  </script>
</body>

3. External JavaScript (RECOMMENDED)

HTML File
<body>
  <button id="myButton">Click me</button>

  <!-- Load external JS file at end of body -->
  <script src="script.js"></script>
</body>
script.js File
// All JavaScript code in separate file
const button = document.getElementById('myButton');
button.addEventListener('click', function() {
  alert('Hello!');
});
💡 Best Practice

Place <script> tags at the end of the <body> to ensure the HTML loads before JavaScript runs. Alternatively, use the defer attribute.

Variables

Variables store data values. JavaScript has three ways to declare variables:

Keyword Scope Can Reassign? When to Use
const Block ❌ No Default choice (values that don't change)
let Block ✅ Yes Values that will change
var Function ✅ Yes Legacy code (avoid in new code)
// const: Cannot be reassigned
const name = 'Alice';
// name = 'Bob'; // ERROR: Cannot reassign const

// let: Can be reassigned
let age = 25;
age = 26; // ✅ This works

// var: Old way (avoid)
var city = 'New York';
city = 'Boston'; // Works but use let instead
💡 Best Practice

Always use const by default. Only use let when you know the value will change. Never use var in modern JavaScript.

Data Types

JavaScript has several primitive data types:

// String: Text
const message = 'Hello, World!';
const name = "Alice"; // Single or double quotes both work
const greeting = `Hello, ${name}!`; // Template literal (backticks)

// Number: Integers and decimals
const age = 25;
const price = 19.99;
const negative = -10;

// Boolean: True or false
const isActive = true;
const isLoggedIn = false;

// Null: Intentionally empty value
const emptyValue = null;

// Undefined: Variable declared but not assigned
let notAssigned;
console.log(notAssigned); // undefined

// Array: List of values
const colors = ['red', 'green', 'blue'];

// Object: Key-value pairs
const person = {
  name: 'Alice',
  age: 25,
  city: 'New York'
};

Operators

Arithmetic Operators

const a = 10;
const b = 3;

console.log(a + b); // 13 (addition)
console.log(a - b); // 7  (subtraction)
console.log(a * b); // 30 (multiplication)
console.log(a / b); // 3.333... (division)
console.log(a % b); // 1  (remainder/modulo)
console.log(a ** b); // 1000 (exponentiation: 10³)

Assignment Operators

let x = 5;

x += 3;  // Same as: x = x + 3  (x is now 8)
x -= 2;  // Same as: x = x - 2  (x is now 6)
x *= 2;  // Same as: x = x * 2  (x is now 12)
x /= 3;  // Same as: x = x / 3  (x is now 4)

// Increment and decrement
x++;     // Same as: x = x + 1  (x is now 5)
x--;     // Same as: x = x - 1  (x is now 4)

Comparison Operators

// Equality (strict - checks value AND type)
5 === 5          // true
5 === '5'        // false (different types)
5 !== 3          // true (not equal)

// Loose equality (converts types - AVOID)
5 == '5'         // true (converts string to number)

// Comparisons
5 > 3           // true (greater than)
5 < 3           // false (less than)
5 >= 5          // true (greater than or equal)
3 <= 5          // true (less than or equal)
⚠️ Always Use === and !==

Use strict equality (===) and strict inequality (!==) to avoid unexpected type conversions. The loose equality (==) can cause bugs.

Logical Operators

// AND (&&): Both conditions must be true
const age = 25;
const hasLicense = true;

if (age >= 18 && hasLicense) {
  console.log('Can drive');
}

// OR (||): At least one condition must be true
const isWeekend = false;
const isHoliday = true;

if (isWeekend || isHoliday) {
  console.log('No work today!');
}

// NOT (!): Inverts boolean value
const isLoggedIn = false;

if (!isLoggedIn) {
  console.log('Please log in');
}

Functions

Functions are reusable blocks of code. There are several ways to create functions:

Function Declaration

// Traditional function declaration
// Can be called before it's defined (hoisting)

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

const message = greet('Alice');
console.log(message); // "Hello, Alice!"

Function Expression

// Function stored in a variable
// Cannot be called before it's defined

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

const message = greet('Bob');
console.log(message); // "Hello, Bob!"

Arrow Functions (Modern)

// Modern, concise syntax

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

// Short form (implicit return, no curly braces)
const greet = name => `Hello, ${name}!`;

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

// No parameters (empty parentheses required)
const sayHello = () => 'Hello!';

Conditionals

if / else if / else

const age = 18;

if (age < 13) {
  console.log('Child');
} else if (age < 18) {
  console.log('Teenager');
} else if (age < 65) {
  console.log('Adult');
} else {
  console.log('Senior');
}

Ternary Operator

// Shorthand for simple if/else
// condition ? valueIfTrue : valueIfFalse

const age = 20;
const status = age >= 18 ? 'Adult' : 'Minor';

console.log(status); // "Adult"

Switch Statement

// For checking one value against multiple cases

const day = 'Monday';

switch (day) {
  case 'Monday':
    console.log('Start of work week');
    break; // Exit switch

  case 'Friday':
    console.log('TGIF!');
    break;

  case 'Saturday':
  case 'Sunday':
    console.log('Weekend!');
    break;

  default:
    console.log('Regular day');
}

Console Methods

The console object provides methods to debug and output information:

// Log messages
console.log('Regular message');
console.info('Information');
console.warn('Warning message');
console.error('Error message');

// Log variables
const user = { name: 'Alice', age: 25 };
console.log('User:', user);

// Table format for arrays/objects
console.table(user);

// Clear console
console.clear();
💡 Developer Tools Console

Press F12 (or Cmd+Option+I on Mac) and click the "Console" tab to see your console.log output. This is essential for debugging!

Practice Exercise

🎯 Try This

Create a function that:

  1. Takes a person's name and age as parameters
  2. Returns a greeting message
  3. If age is 18 or older, say "Welcome, [name]!"
  4. If under 18, say "Sorry, [name]. You must be 18 or older."
Solution
// Function to check age and return greeting
function checkAge(name, age) {
  if (age >= 18) {
    return `Welcome, ${name}!`;
  } else {
    return `Sorry, ${name}. You must be 18 or older.`;
  }
}

// Test the function
console.log(checkAge('Alice', 25)); // "Welcome, Alice!"
console.log(checkAge('Bob', 16));   // "Sorry, Bob. You must be 18 or older."

// Arrow function version
const checkAge = (name, age) =>
  age >= 18 ? `Welcome, ${name}!` : `Sorry, ${name}. You must be 18 or older.`;

Summary

📚 What you learned
  • How to add JavaScript to HTML (external files are best)
  • Variables: use const by default, let when values change
  • Data types: strings, numbers, booleans, null, undefined, arrays, objects
  • Operators: arithmetic, assignment, comparison, logical
  • Functions: declarations, expressions, arrow functions
  • Conditionals: if/else, ternary operator, switch
  • Console methods for debugging