Learn JavaScript

JavaScript Fundamentals

Welcome to the foundational JavaScript lesson! JavaScript is a versatile and powerful programming language that enables you to create dynamic and interactive web content. Let's dive into the core concepts.

1. Variables: Storing Information

Variables are like containers that hold data. In JavaScript, you declare variables using var, let, or const.


let name = "Alice";
const age = 30;
var isStudent = true;

name = "Bob"; // allowed with let
// age = 31; // This would cause an error with const
            

2. Data Types: The Kind of Data

JavaScript has several built-in data types:

3. Operators: Performing Actions

Operators are symbols that perform operations on values and variables.


let x = 10;
let y = 5;
let sum = x + y; // sum is 15
let isGreater = x > y; // isGreater is true
let isEqual = (x === 10); // isEqual is true
            

4. Control Flow: Making Decisions

Control flow statements allow you to execute code based on certain conditions.


let hour = 14;
if (hour < 12) {
    console.log("Good morning!");
} else if (hour < 18) {
    console.log("Good afternoon!");
} else {
    console.log("Good evening!");
}

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

Example Output:

Good afternoon!

Iteration: 0

Iteration: 1

Iteration: 2

Iteration: 3

Iteration: 4

5. Functions: Reusable Blocks of Code

Functions are blocks of code designed to perform a particular task. They make your code more organized and reusable.


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

let message = greet("Charlie");
console.log(message); // Output: Hello, Charlie!
            

Example Output:

Hello, Charlie!

6. Arrays: Ordered Lists

Arrays are special variables that can hold multiple values in a single variable. They are ordered and can contain different data types.


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

fruits.push("Date"); // Adds "Date" to the end
console.log(fruits); // Output: ["Apple", "Banana", "Cherry", "Date"]

console.log(fruits.length); // Output: 4
            

Example Output:

Apple

Array(4) [ "Apple", "Banana", "Cherry", "Date" ]

4

7. Objects: Key-Value Pairs

Objects are collections of properties, where each property is a key-value pair. Keys are usually strings, and values can be any data type, including other objects or functions.


let person = {
    firstName: "Jane",
    lastName: "Doe",
    age: 25,
    isEmployed: false,
    greet: function() {
        return "Hi, I'm " + this.firstName + " " + this.lastName;
    }
};

console.log(person.firstName); // Output: Jane
console.log(person['lastName']); // Output: Doe
console.log(person.greet()); // Output: Hi, I'm Jane Doe
            

Example Output:

Jane

Doe

Hi, I'm Jane Doe