No history yet

JavaScript Basics

The Building Blocks

Programming is all about working with information. But before we can work with it, we need a place to store it. In JavaScript, we use variables to hold data. Think of a variable as a labeled box where you can keep a value. You give the box a name, and you can look at what's inside or change it later.

variable

noun

A container for storing a data value.

To declare a variable, we use the keywords let or const. Use const when you know the value won't change, like the number of days in a week. Use let for values that might change, like a user's score in a game.

An older keyword, var, also exists, but let and const are generally preferred in modern JavaScript because they work in a more predictable way.

// Use const for values that don't change
const birthYear = 1995;

// Use let for values that might change
let currentScore = 0;
currentScore = 100;

Variables can hold different kinds of data. These are called data types. JavaScript has several fundamental types.

String: Text, like a name or a sentence. Always wrap strings in single or double quotes. Number: Any kind of number, including integers and decimals. Boolean: Represents a logical value, either true or false. Null: Represents the intentional absence of any value. It's a box that's deliberately empty. Undefined: A variable that has been declared but hasn't been given a value yet.

let greeting = "Hello, world!"; // String
let userAge = 28;             // Number
let isLoggedIn = true;        // Boolean
let userPhoto = null;         // Null
let lastSeen;                 // Undefined

Making Things Happen

Once you have data stored in variables, you need to be able to work with it. That's where operators come in. Operators are symbols that perform operations on values and variables.

Operator TypeSymbolExampleDescription
Arithmetic+, -, *, /5 + 2Performs math calculations.
Assignment=let x = 10Assigns a value to a variable.
Comparison===, !==, >, <age > 18Compares two values and returns a boolean (true or false).
Logical&&, `, !`

Let's see them in action. Arithmetic operators do what you'd expect from a calculator. Assignment operators put values into variables. But comparison and logical operators are the key to making decisions in your code.

let score = 10;
let lives = 3;

// Add 5 to score
score = score + 5; // score is now 15

// Check if the game is over
let isGameOver = score > 100 || lives <= 0;
// isGameOver will be true if score is over 100 OR lives are 0 or less

// Use the strict equality operator (===) to check both value and type
let value1 = 10;   // a number
let value2 = "10"; // a string

console.log(value1 == value2);  // true, because it only checks the value
console.log(value1 === value2); // false, because it checks value AND type

It's a best practice to use the strict equality (===) and strict inequality (!==) operators. They prevent subtle bugs by making sure you're comparing things of the same data type.

Controlling the Flow

A script usually runs from top to bottom, one line at a time. But often, you'll want to run some code only if a certain condition is met, or run a block of code over and over again. Control structures let you manage this flow.

The most common conditional is the if...else statement. It checks if a condition is true. If it is, one block of code runs. If not, another block runs.

let temperature = 75;

if (temperature > 80) {
  console.log("It's hot outside!");
} else if (temperature < 60) {
  console.log("Better bring a jacket.");
} else {
  console.log("It feels just right.");
}

When you need to repeat an action, you use a loop. A for loop is great when you know how many times you want to repeat something. A while loop is better when you want to loop until a specific condition is no longer true.

// A 'for' loop that counts from 1 to 5
for (let i = 1; i <= 5; i++) {
  console.log("Count is: " + i);
}

// A 'while' loop that runs as long as a condition is true
let fuel = 10;
while (fuel > 0) {
  console.log("Burning fuel...");
  fuel = fuel - 1; // or fuel--
}
console.log("Out of fuel!");

Reusable Instructions

If you find yourself writing the same piece of code in multiple places, it's time to create a function. A function is a reusable block of code that performs a specific task. You define it once and can call it whenever you need it.

Functions can take inputs, called parameters, which act like variables inside the function. They can also produce an output by using the return keyword.

// This function takes two numbers and returns their sum
function addNumbers(num1, num2) {
  return num1 + num2;
}

// Call the function and store the result in a variable
let result1 = addNumbers(5, 10); // result1 is 15
let result2 = addNumbers(100, 3); // result2 is 103

console.log(result1);

Functions help keep your code organized, readable, and efficient. This principle is often called DRY: Don't Repeat Yourself.

Organizing with Objects

As programs get more complex, it helps to group related data and functions together. In JavaScript, the main way to do this is with objects. An object is a collection of key-value pairs. The keys are called properties, and the values can be any data type, including other objects or even functions.

When a function is a property of an object, it's called a method.

// An object literal representing a user
const user = {
  firstName: "Alex",
  lastName: "Chen",
  age: 30,
  isVerified: true,
  
  // This is a method
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
};

// Access properties using dot notation
console.log(user.firstName); // Outputs: Alex

// Call the method
console.log(user.fullName()); // Outputs: Alex Chen

Objects let you model real-world things in your code. You can have a user object, a product object, or a car object, each with its own data and behavior bundled together neatly. This is a fundamental concept in object-oriented programming (OOP).

Time to check your understanding of these core concepts.

Quiz Questions 1/6

When should you use the const keyword to declare a variable in JavaScript?

Quiz Questions 2/6

What is the result of the following expression in JavaScript? 10 === "10"

These are the essential building blocks of JavaScript. With variables for storing data, operators for manipulating it, control structures for directing its flow, functions for reusing code, and objects for organizing it all, you have the foundation to build almost anything.