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.
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!
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`.
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
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
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" }
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.
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.
<!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>
// 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);
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!
JavaScript has several data types, categorized into primitive and non-primitive (object) types.
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
Objects are complex data types that can store collections of data. Arrays and Functions are also types of objects.
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
Operators are symbols that perform operations on values and variables.
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
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
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
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
Control flow statements dictate the order in which instructions are executed.
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.
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!
Loops are used to repeatedly execute a block of code.
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
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
Functions are blocks of code designed to perform a particular task. They are reusable.
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
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
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!
Arrays are ordered lists of values. They are zero-indexed.
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[0]); // Output: Apple
console.log(fruits.length); // Output: 3
Output:
Apple 3
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 ]
Objects are collections of properties, where each property has a name (key) and a value.
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
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' }
ECMAScript 2015 (ES6) introduced many significant features that greatly improved JavaScript. Here are a few key ones:
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.
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
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
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!