JavaScript Fundamentals to ECMAScript Course

Embark on a journey to master JavaScript, the programming language that brings web pages to life! We'll cover core concepts and essential modern ECMAScript features.


1. What is JavaScript?

JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions. While it is most well-known as the scripting language for web pages, it's also used in many non-browser environments (e.g., Node.js). It's the "behavior" layer of the web, making pages interactive and dynamic.

HTML (Structure) + CSS (Style) + JavaScript (Behavior) = Dynamic Web!

📄+🎨+💻=🚀

2. Variables: `var`, `let`, and `const`

Variables are containers for storing data values. JavaScript has three keywords for declaring variables: `var`, `let`, and `const`. Modern JavaScript primarily uses `let` and `const`.

2.1 `var` (Legacy)

Declares a function-scoped variable. It can be re-declared and updated. Due to hoisting and scope issues, it's generally avoided in modern JS.

var greeting = "Hello";
console.log(greeting); // Output: Hello
var greeting = "Hi"; // Re-declaration is allowed
console.log(greeting); // Output: Hi

Output:

Hello Hi

2.2 `let` (Block-Scoped)

Declares a block-scoped local variable. It can be updated, but not re-declared in the same scope. This is the preferred way to declare variables that might change.

let count = 10;
console.log(count); // Output: 10
count = 20; // Update is allowed
console.log(count); // Output: 20
// let count = 30; // Error: Identifier 'count' has already been declared

Output:

10 20

2.3 `const` (Block-Scoped, Constant)

Declares a block-scoped named constant. Its value cannot be reassigned after initialization. Use `const` for variables whose values should not change.

const PI = 3.14159;
console.log(PI); // Output: 3.14159
// PI = 3.14; // Error: Assignment to constant variable.

const user = { name: "Alice" };
user.name = "Bob"; // Allowed: Object properties can be changed
console.log(user); // Output: { name: "Bob" }

Output:

3.14159{ name: "Bob" }

3. How to Run JavaScript Code Locally (Visual Studio Code)

Visual Studio Code (VS Code) is an excellent environment for writing and running JavaScript. You can execute JavaScript directly in your browser (for front-end JS) or using Node.js (for back-end/server-side JS). For this course, we'll focus on running it in the browser environment, which is common for web development.

Step 1: Install Visual Studio Code

  • Go to the official VS Code website: code.visualstudio.com
  • Download and install the version appropriate for your operating system (Windows, macOS, Linux).
  • Follow the installation prompts.

Step 2: Install the Live Server Extension

The Live Server extension provides a local development server with live reload capability. This is perfect for seeing your HTML and JavaScript changes instantly in the browser.

  • Open VS Code.
  • Click on the **Extensions** icon in the Activity Bar on the side (it looks like four squares, one detached). Or press `Ctrl+Shift+X` (Windows/Linux) or `Cmd+Shift+X` (macOS).
  • In the search bar, type "Live Server".
  • Find the "Live Server" extension by Ritwick Dey and click the **Install** button.

Step 3: Create Your HTML and JavaScript Files

  • In VS Code, go to **File > Open Folder...** and create a new folder for your project (e.g., `my-js-project`).
  • Inside this folder, create two new files:
    • `index.html`
    • `script.js`
  • Paste the following code into `index.html`:
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>My First JS Page</title>
    </head>
    <body>
        <h1>Open your browser's console to see JavaScript output!</h1>
        <p>Right-click anywhere on this page, then select "Inspect" or "Inspect Element". Go to the "Console" tab.</p>
    
        <script src="script.js"></script>
    </body>
    </html>
  • Paste the following code into `script.js`:
    // script.js
    console.log("Hello from JavaScript!");
    
    let message = "This message is from script.js";
    console.log(message);
    
    function add(a, b) {
        return a + b;
    }
    
    let sum = add(10, 5);
    console.log("The sum is: " + sum);

Step 4: Open with Live Server and Check Console

  • With `index.html` open in the editor, **right-click anywhere in the editor window**.
  • Select "Open with Live Server" from the context menu.
  • Your default web browser will open, displaying your `index.html` file.
  • To see the JavaScript output, **open your browser's developer console**:
    • **Chrome/Firefox:** Right-click anywhere on the page and select "Inspect" or "Inspect Element". Then click on the "Console" tab.
    • **Safari:** Go to `Safari > Preferences > Advanced` and check "Show Develop menu in menu bar". Then go to `Develop > Show JavaScript Console`.
  • You should see the "Hello from JavaScript!", "This message is from script.js", and "The sum is: 15" messages printed in the console.

Now, whenever you save changes to `index.html` or `script.js` in VS Code, Live Server will automatically refresh your browser, and you can check the console for your updated JavaScript output!


4. Data Types

JavaScript has several data types, categorized into primitive and non-primitive (object) types.

4.1 Primitive Data Types

  • String: Textual data (e.g., `"hello"`).
  • Number: Numeric data (integers and floating-point numbers, e.g., `10`, `3.14`).
  • Boolean: Logical entities (`true` or `false`).
  • Undefined: A variable that has been declared but not assigned a value.
  • Null: Represents the intentional absence of any object value.
  • Symbol (ES6): A unique and immutable primitive value.
  • BigInt (ES2020): For integers larger than `Number.MAX_SAFE_INTEGER`.
let name = "John Doe";
let age = 30;
let isStudent = true;
let city; // undefined
let car = null;
let id = Symbol('id');
let bigNumber = 9007199254740991n; // BigInt

console.log(typeof name); // string
console.log(typeof age); // number
console.log(typeof isStudent); // boolean
console.log(typeof city); // undefined
console.log(typeof car); // object (a historical bug, it's primitive)
console.log(typeof id); // symbol
console.log(typeof bigNumber); // bigint

Output:

string number boolean undefined object symbol bigint

4.2 Non-Primitive Data Type: Object

Objects are complex data types that can store collections of data. Arrays and Functions are also types of objects.

  • Object: A collection of key-value pairs (properties).
  • Array: An ordered collection of values.
  • Function: A block of code designed to perform a particular task.
let person = {
    firstName: "Jane",
    lastName: "Doe",
    age: 25
};

let colors = ["red", "green", "blue"];

function greet(name) {
    return "Hello, " + name + "!";
}

console.log(typeof person); // object
console.log(typeof colors); // object
console.log(typeof greet); // function (special type of object)

Output:

object object function

5. Operators

Operators are symbols that perform operations on values and variables.

5.1 Arithmetic Operators

Perform mathematical calculations.

let a = 10;
let b = 3;
console.log(a + b); // Addition: 13
console.log(a - b); // Subtraction: 7
console.log(a * b); // Multiplication: 30
console.log(a / b); // Division: 3.333...
console.log(a % b); // Modulus (remainder): 1
console.log(a ** b); // Exponentiation (ES6): 1000

Output:

13 7 30 3.3333333333333335 1 1000

5.2 Assignment Operators

Assign values to variables.

let x = 5;
x += 3; // x = x + 3; (x is now 8)
console.log(x);
x -= 2; // x = x - 2; (x is now 6)
console.log(x);

Output:

8 6

5.3 Comparison Operators

Compare two values and return a boolean (`true` or `false`).

let num1 = 10;
let num2 = "10";
console.log(num1 == num2); // Loose equality (compares value only): true
console.log(num1 === num2); // Strict equality (compares value and type): false
console.log(num1 != num2); // Loose inequality: false
console.log(num1 !== num2); // Strict inequality: true
console.log(num1 > 5); // Greater than: true
console.log(num1 <= 10); // Less than or equal to: true

Output:

true false false true true true

5.4 Logical Operators

Combine conditional statements.

let isAdult = true;
let hasLicense = false;
console.log(isAdult && hasLicense); // AND: false
console.log(isAdult || hasLicense); // OR: true
console.log(!isAdult); // NOT: false

Output:

false true false

6. Control Flow

Control flow statements dictate the order in which instructions are executed.

6.1 `if`, `else if`, `else`

Executes a block of code if a specified condition is true.

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

Output:

It's warm.

6.2 `switch` Statement

Evaluates an expression and executes code based on matching cases.

let day = "Monday";
let message;
switch (day) {
    case "Monday":
        message = "Start of the week!";
        break;
    case "Friday":
        message = "Almost weekend!";
        break;
    default:
        message = "Just another day.";
}
console.log(message);

Output:

Start of the week!

7. Loops

Loops are used to repeatedly execute a block of code.

7.1 `for` Loop

Repeats a block of code a specified number of times.

for (let i = 0; i < 3; i++) {
    console.log("Iteration " + i);
}

Output:

Iteration 0 Iteration 1 Iteration 2

7.2 `while` Loop

Repeats a block of code as long as a specified condition is true.

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

Output:

Count: 0 Count: 1 Count: 2

8. Functions

Functions are blocks of code designed to perform a particular task. They are reusable.

8.1 Function Declaration

A traditional way to define a function. They are hoisted.

function add(a, b) {
    return a + b;
}
console.log(add(5, 3)); // Output: 8

Output:

8

8.2 Function Expression

Defines a function as part of an expression, often assigned to a variable. Not hoisted.

const multiply = function(a, b) {
    return a * b;
};
console.log(multiply(4, 2)); // Output: 8

Output:

8

8.3 Arrow Functions (ES6)

A shorter syntax for writing function expressions. They do not have their own `this` context.

const subtract = (a, b) => a - b;
console.log(subtract(10, 4)); // Output: 6

const greetUser = name => {
    return `Hello, ${name}!`;
};
console.log(greetUser("Alice")); // Output: Hello, Alice!

Output:

6 Hello, Alice!

9. Arrays

Arrays are ordered lists of values. They are zero-indexed.

9.1 Declaration & Access

let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[0]); // Output: Apple
console.log(fruits.length); // Output: 3

Output:

Apple 3

9.2 Common Methods

  • `push()`: Adds an element to the end.
  • `pop()`: Removes the last element.
  • `unshift()`: Adds an element to the beginning.
  • `shift()`: Removes the first element.
  • `map()` (ES6): Creates a new array by calling a function on every array element.
  • `filter()` (ES6): Creates a new array with elements that pass a test.
let numbers = [1, 2, 3];
numbers.push(4); // [1, 2, 3, 4]
console.log(numbers);

let last = numbers.pop(); // last is 4, numbers is [1, 2, 3]
console.log(last, numbers);

let doubled = numbers.map(num => num * 2); // [2, 4, 6]
console.log(doubled);

let evens = numbers.filter(num => num % 2 === 0); // [2]
console.log(evens);

Output:

[ 1, 2, 3, 4 ] 4 [ 1, 2, 3 ] [ 2, 4, 6 ] [ 2 ]

10. Objects

Objects are collections of properties, where each property has a name (key) and a value.

10.1 Declaration & Access

Access properties using dot notation (`.`) or bracket notation (`[]`).

let book = {
    title: "The Great Gatsby",
    author: "F. Scott Fitzgerald",
    year: 1925
};

console.log(book.title); // Output: The Great Gatsby
console.log(book["author"]); // Output: F. Scott Fitzgerald

Output:

The Great Gatsby F. Scott Fitzgerald

10.2 Manipulating Properties

let car = { make: "Toyota", model: "Camry" };
car.year = 2020; // Add new property
console.log(car);

car.model = "Corolla"; // Update property
console.log(car);

delete car.year; // Delete property
console.log(car);

Output:

{ make: 'Toyota', model: 'Camry', year: 2020 }
{ make: 'Toyota', model: 'Corolla', year: 2020 }
{ make: 'Toyota', model: 'Corolla' }

11. Essential ES6+ Features

ECMAScript 2015 (ES6) introduced many significant features that greatly improved JavaScript. Here are a few key ones:

11.1 Template Literals (`` ` ``)

Allow for embedded expressions and multi-line strings using backticks (` `).

const name = "World";
const greeting = `Hello, ${name}!`;
console.log(greeting);

const multiLine = `This is a
multi-line
string.`;
console.log(multiLine);

Output:

Hello, World! This is a multi-line string.

11.2 Destructuring Assignment

Allows you to extract values from arrays or properties from objects into distinct variables.

// Array Destructuring
const colors = ["red", "green", "blue"];
const [firstColor, secondColor] = colors;
console.log(firstColor, secondColor); // Output: red green

// Object Destructuring
const person = { name: "Charlie", age: 40 };
const { name, age } = person;
console.log(name, age); // Output: Charlie 40

Output:

red green Charlie 40

11.3 Spread Operator (`...`)

Expands an iterable (like an array) into individual elements. Useful for copying arrays, merging arrays/objects, and passing arguments to functions.

// Copying an array
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
console.log(arr2); // Output: [1, 2, 3, 4, 5]

// Merging objects
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
console.log(obj2); // Output: { a: 1, b: 2, c: 3 }

// Function arguments
function sum(x, y, z) {
    return x + y + z;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers)); // Output: 6

Output:

[ 1, 2, 3, 4 ]{ a: 1, b: 2, c: 3 }6

Congratulations!

You've completed the JavaScript Fundamentals to ECMAScript Course! You now have a strong foundation in JavaScript's core concepts and modern features.

Keep practicing by building small projects and exploring more advanced topics like asynchronous JavaScript, DOM manipulation, and frameworks!