No history yet

JavaScript Basics

Storing Information

Think of a computer program as a recipe. Before you can cook, you need ingredients. In programming, these ingredients are data, and you store them in variables.

A variable is like a labeled jar. You give it a name and put something inside. In JavaScript, you create a variable using the keywords let or const.

// Use 'let' for variables that might change.
let userAge = 30;

// Use 'const' for variables that won't change.
const birthday = "January 1";

The information you put inside these variables has a specific type. JavaScript has several fundamental data types you'll use all the time.

Data TypeDescriptionExample
StringA sequence of characters, or text."Hello, world!"
NumberAny number, including decimals.42 or 3.14
BooleanA value that is either true or false.true
nullRepresents the intentional absence of a value.null
undefinedA variable that has been declared but not assigned a value.undefined
let greeting = "Welcome to JavaScript"; // A String
let accountBalance = 150.75;      // A Number
let isLoggedIn = false;             // A Boolean

let favoriteColor; // This is currently undefined

favoriteColor = "blue"; // Now it's a String

Making Things Happen

Once you have data stored in variables, you can manipulate it using operators. These are the symbols that perform actions, like math or comparisons.

The most familiar are arithmetic operators.

let price = 10;
let quantity = 3;

let total = price * quantity; // Multiplication. total is 30
let pricePerPerson = total / 2; // Division. pricePerPerson is 15

You also have assignment operators to assign or update values. The most basic is =, but there are shortcuts.

let score = 100;

// Add 50 to the current score
score = score + 50; // score is now 150

// A shorter way to do the same thing
score += 50; // score is now 200

Comparison operators check how two values relate to each other. They always produce a boolean (true or false) result, which is perfect for making decisions.

let myAge = 25;
let requiredAge = 18;

let canVote = myAge >= requiredAge; // Is myAge greater than or equal to requiredAge? `canVote` is true.

let item = "apple";
let isFruit = item === "apple"; // Does `item` equal "apple"? `isFruit` is true.

A quick tip: Always use === (strict equality) instead of == (loose equality). The triple-equals checks both the value and the data type, which prevents many common bugs.

Finally, logical operators let you combine multiple boolean conditions.

OperatorNameDescription
&&ANDReturns true only if both conditions are true.
``
!NOTFlips a boolean value (true becomes false).

Controlling the Flow

By default, code runs straight from top to bottom. But what if you only want to run code if a certain condition is met? Or what if you want to run the same code over and over? That's where control structures come in.

The if...else statement is your primary tool for making decisions.

let temperature = 75; // in Fahrenheit

if (temperature > 80) {
  console.log("It's hot outside!");
} else if (temperature < 50) {
  console.log("Better bring a jacket.");
} else {
  console.log("The weather is pleasant.");
}

The code inside the if block runs only if its condition is true. If not, the program checks the else if condition. If none of the conditions are true, the else block runs.

When you need to repeat an action, you use a loop. The for loop is a common way to run a block of code a specific number of times.

// This loop will run 5 times.
// 'i' starts at 0 and increases by 1 each time.
for (let i = 0; i < 5; i++) {
  console.log("This is loop number " + (i + 1));
}

Another useful loop is the while loop, which continues as long as its condition remains true.

let battery = 100;

while (battery > 0) {
  console.log("Using device... battery at " + battery + "%");
  battery -= 10; // Decrease battery by 10
}

console.log("Battery is empty!");

Packaging Your Code

As your scripts get more complex, you'll find yourself writing the same lines of code in multiple places. Functions are how you package up these reusable blocks of code. You define a function once and can then call it whenever you need it.

A function can take inputs, called arguments, and can return an output.

// This function is defined to take two numbers
// and return their sum.
function addNumbers(num1, num2) {
  return num1 + num2;
}

// Now we can call the function.
let result = addNumbers(5, 10); // result is 15
let anotherResult = addNumbers(100, 200); // anotherResult is 300

Functions make your code more organized, readable, and efficient. If you need to change how the addition works, you only have to change it in one place.

Handling Errors

Sometimes, things go wrong. A user might enter text where a number is expected, or you might try to connect to a server that is offline. Without a plan, these errors can crash your script. Error handling is your plan for dealing with potential problems gracefully.

In JavaScript, you can use a try...catch block to handle errors. You put the code that might fail in the try block, and the code that should run if an error occurs goes in the catch block.

try {
  // This code might cause an error.
  // For example, someFunction might not exist.
  someFunction();
} catch (error) {
  // If an error happens in the `try` block,
  // this `catch` block will run.
  console.log("Something went wrong!");
  console.log("The error was: " + error.message);
}

This prevents the script from stopping unexpectedly. Instead of a crash, you can log the error or show a friendly message to the user, making your programs more robust.

Quiz Questions 1/5

In JavaScript, what is the primary difference between a variable declared with let and one declared with const?

Quiz Questions 2/5

What will the following JavaScript expression evaluate to?

(10 > 5) && (7 < 4)