Introduction

JavaScript is the programming language of the web. It powers interactive websites, mobile apps, and even server-side applications. In this lesson, you'll learn the fundamental concepts and modern syntax that form the foundation of JavaScript development.

Learning Objectives

By the end of this lesson, you will be able to:

  • Understand the difference between let, const, and var
  • Work with all JavaScript primitive data types
  • Use template literals for string interpolation
  • Apply destructuring to extract values from arrays and objects
  • Utilize spread and rest operators effectively
  • Write clean, modern JavaScript code following ES6+ standards

Prerequisites

  • Basic understanding of HTML and CSS
  • A code editor (VS Code, Sublime Text, or similar)
  • A modern web browser with developer tools
  • Enthusiasm to learn programming!

Estimated Time

3 hours (including practice exercises)

What is JavaScript?

JavaScript is a high-level, interpreted programming language that enables you to create dynamically updating content, control multimedia, animate images, and much more. Originally designed for web browsers, JavaScript has evolved into a versatile language used across various platforms.

Key Characteristics

  • Interpreted language - runs directly in browsers without compilation
  • Dynamically typed - variable types are determined at runtime
  • Multi-paradigm - supports object-oriented, functional, and imperative programming
  • Event-driven - responds to user interactions and system events

Variables and Data Types

Variables are containers for storing data values. Modern JavaScript provides three ways to declare variables:

JavaScript
// let - for variables that can be reassigned
let userName = "Alice";
userName = "Bob"; // This works

// const - for variables that cannot be reassigned
const API_KEY = "abc123";
// API_KEY = "xyz789"; // This would cause an error

// var - old way (avoid in modern code)
var oldStyle = "deprecated";
Best Practice: Use const by default. Only use let when you know the variable will be reassigned. Avoid var in modern JavaScript.

Primitive Data Types

JavaScript
// String - text data
const greeting = "Hello, World!";
const name = 'JavaScript';

// Number - integers and decimals
const age = 25;
const price = 19.99;

// Boolean - true or false
const isActive = true;
const hasPermission = false;

// Undefined - variable declared but not assigned
let notAssigned;
console.log(notAssigned); // undefined

// Null - intentional absence of value
const emptyValue = null;

// Symbol - unique identifier (ES6)
const uniqueId = Symbol('id');

Template Literals

Template literals provide an elegant way to create strings with embedded expressions:

JavaScript
const firstName = "John";
const lastName = "Doe";
const age = 30;

// Old way (string concatenation)
const oldGreeting = "Hello, " + firstName + " " + lastName + "!";

// Modern way (template literals)
const modernGreeting = `Hello, ${firstName} ${lastName}!`;
const info = `${firstName} is ${age} years old.`;

// Multi-line strings
const multiLine = `
  This is a
  multi-line
  string
`;

console.log(modernGreeting); // "Hello, John Doe!"

Operators

Arithmetic Operators

JavaScript
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  (modulus/remainder)
console.log(a ** b); // 1000 (exponentiation)

Comparison Operators

JavaScript
// Strict equality (checks value and type)
console.log(5 === 5);    // true
console.log(5 === "5");  // false

// Strict inequality
console.log(5 !== "5");  // true

// Loose equality (type coercion - avoid)
console.log(5 == "5");   // true (not recommended)

// Comparison
console.log(10 > 5);     // true
console.log(10 < 5);     // false
console.log(10 >= 10);   // true
console.log(10 <= 5);    // false
Important: Always use strict equality (===) instead of loose equality (==) to avoid unexpected type coercion bugs.

Destructuring

Destructuring allows you to extract values from arrays or properties from objects into distinct variables:

Array Destructuring

JavaScript
const colors = ["red", "green", "blue"];

// Old way
const firstColor = colors[0];
const secondColor = colors[1];

// Modern way (destructuring)
const [first, second, third] = colors;
console.log(first);  // "red"
console.log(second); // "green"

// Skip elements
const [primary, , tertiary] = colors;
console.log(tertiary); // "blue"

Object Destructuring

JavaScript
const user = {
  name: "Alice",
  age: 28,
  email: "[email protected]"
};

// Extract properties
const { name, age, email } = user;
console.log(name); // "Alice"

// Rename variables
const { name: userName, age: userAge } = user;
console.log(userName); // "Alice"

// Default values
const { name, country = "USA" } = user;
console.log(country); // "USA"

Spread and Rest Operators

Spread Operator (...)

JavaScript
// Spread arrays
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4, 5, 6]

// Spread objects
const person = { name: "John", age: 30 };
const employee = { ...person, role: "Developer" };
console.log(employee); 
// { name: "John", age: 30, role: "Developer" }

// Copy arrays/objects
const original = [1, 2, 3];
const copy = [...original];
copy.push(4);
console.log(original); // [1, 2, 3] (unchanged)

Rest Parameters

JavaScript
// Collect remaining arguments
function sum(...numbers) {
  return numbers.reduce((total, num) => total + num, 0);
}

console.log(sum(1, 2, 3, 4, 5)); // 15

// Destructuring with rest
const [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(first);  // 1
console.log(second); // 2
console.log(rest);   // [3, 4, 5]

Practical Example: User Profile

Let's combine what we've learned to create a simple user profile system:

JavaScript
// Define user data
const user = {
  firstName: "Sarah",
  lastName: "Johnson",
  age: 32,
  email: "[email protected]",
  isActive: true
};

// Destructure user properties
const { firstName, lastName, age, email, isActive } = user;

// Create formatted output using template literals
const userProfile = `
  User Profile
  ============
  Name: ${firstName} ${lastName}
  Age: ${age}
  Email: ${email}
  Status: ${isActive ? "Active" : "Inactive"}
`;

console.log(userProfile);

// Update user with spread operator
const updatedUser = {
  ...user,
  age: 33,
  lastLogin: new Date().toISOString()
};

console.log(updatedUser);

Key Takeaways

  • Use const by default, let when reassignment is needed
  • JavaScript has six primitive data types: String, Number, Boolean, Undefined, Null, Symbol
  • Template literals make string interpolation clean and readable
  • Always use strict equality (===) for comparisons
  • Destructuring simplifies extracting values from arrays and objects
  • Spread operator copies and combines arrays/objects efficiently
  • Rest parameters collect multiple arguments into an array

Practice Exercises

Test your understanding with these hands-on exercises:

Exercise 1: Variable Declaration

Create variables for a product in an online store:

Task
// Create variables for:
// - Product name (should not change)
// - Product price (should not change)
// - Quantity in cart (can change)
// - Is product available (can change)

// Your code here:

Exercise 2: Template Literals

Create a function that generates a product description using template literals:

Task
const product = {
  name: "Laptop",
  brand: "TechPro",
  price: 999,
  inStock: true
};

// Create a formatted description using template literals
// Expected output: "TechPro Laptop - $999 (In Stock)"

Exercise 3: Destructuring Challenge

Extract specific values from nested objects:

Task
const user = {
  id: 1,
  name: "John Doe",
  address: {
    street: "123 Main St",
    city: "New York",
    country: "USA"
  },
  hobbies: ["reading", "gaming", "coding"]
};

// Extract: name, city, and first hobby using destructuring

Exercise 4: Spread Operator

Merge two user objects and add new properties:

Task
const basicInfo = { name: "Alice", age: 25 };
const contactInfo = { email: "[email protected]", phone: "555-0123" };

// Merge both objects and add a new property 'role: "developer"'
// using the spread operator

Additional Resources

What's Next?

In the next lesson, we'll dive deep into functions, exploring arrow functions, scope, closures, and functional programming concepts. These are essential building blocks for writing modular and maintainable JavaScript code.