No history yet

JavaScript Basics

The Building Blocks of Code

At its heart, programming is about storing and manipulating information. In JavaScript, we store information in variables. Think of a variable as a labeled container where you can keep a value. To create one, you'll most often use the let keyword.

let userAge = 30;

Here, userAge is the variable's name, and its value is 30. We can change this value later if we need to. If you have a value that should never change, like the number of days in a week, use const instead. This makes your code safer by preventing accidental changes.

const daysInWeek = 7;

Variables can hold different types of data. These data types are fundamental to how JavaScript works.

  • String: Text, wrapped in quotes. "Hello, world!"
  • Number: Any kind of number, including integers and decimals. 42 or 3.14
  • Boolean: A simple true or false value. true
  • Null: Represents the intentional absence of any value. null
  • Undefined: A variable that has been declared but not yet assigned a value. undefined

JavaScript is dynamically typed, which means you don't have to specify the data type when you create a variable. The language figures it out automatically based on the value you assign.

Making Things Happen

Once you have data, you need to do things with it. That's where operators come in. They are the symbols that perform operations, from simple math to making logical comparisons.

Arithmetic Operators are for math:

let a = 10;
let b = 5;

console.log(a + b); // 15 (addition)
console.log(a - b); // 5 (subtraction)
console.log(a * b); // 50 (multiplication)
console.log(a / b); // 2 (division)

Assignment Operators assign values:

let score = 100;
score += 10; // score is now 110 (same as score = score + 10)

Comparison Operators compare two values and return a boolean (true or false). These are crucial for making decisions in your code.

OperatorDescriptionExample
===Strict equality (value and type)5 === 5 is true
!==Strict inequality5 !== '5' is true
>Greater than10 > 5 is true
<Less than10 < 5 is false

Pro-tip: Always use the strict equality (===) and inequality (!==) operators. They prevent common bugs by checking that both the value and the data type are the same.

Logical Operators let you combine boolean values.

let isRaining = true;
let haveUmbrella = false;

// && (AND): both must be true
console.log(isRaining && haveUmbrella); // false

// || (OR): at least one must be true
console.log(isRaining || haveUmbrella); // true

// ! (NOT): inverts the value
console.log(!isRaining); // false

Controlling the Flow

Your code doesn't just run from top to bottom. Control structures allow you to make decisions and repeat actions, creating dynamic and intelligent programs. The most common way to make a decision is with an if...else statement.

let temperature = 25;

if (temperature > 30) {
  console.log("It's a hot day!");
} else if (temperature > 20) {
  console.log("The weather is pleasant.");
} else {
  console.log("It's a bit chilly.");
}

When you have many possible conditions, a switch statement can be cleaner than a long chain of if...else statements.

let day = "Monday";

switch (day) {
  case "Saturday":
  case "Sunday":
    console.log("It's the weekend!");
    break;
  case "Monday":
    console.log("Back to work.");
    break;
  default:
    console.log("It's a weekday.");
}

To repeat an action, you use loops. A for loop is great when you know how many times you want to repeat something.

// This loop will run 5 times, printing numbers 0 through 4.
for (let i = 0; i < 5; i++) {
  console.log("The current number is " + i);
}

A while loop is better when you want to keep looping as long as a certain condition is true.

let count = 0;
while (count < 3) {
  console.log("Looping...");
  count++; // Important: increment the counter to avoid an infinite loop!
}

Reusable Code with Functions

Writing the same code over and over is tedious and error-prone. Functions solve this by bundling up a piece of code that you can run whenever you need it. You define a function once and then "call" it by name as many times as you like.

A function can take inputs, called parameters, which act as variables inside the function. When you call the function, you provide values for these parameters, called arguments.

// Defining a function with two parameters: name and language
function greet(name, language) {
  if (language === "Spanish") {
    return `Hola, ${name}!`;
  } else {
    return `Hello, ${name}!`;
  }
}

// Calling the function with two arguments
let message = greet("Maria", "Spanish");
console.log(message); // Outputs: "Hola, Maria!"

The return keyword is key. It specifies the value that the function should output. When JavaScript sees return, it immediately stops the function and sends that value back to where the function was called.

Grouping Data with Objects

Sometimes, you have pieces of data that are all related to one thing. For example, a user has a name, an age, and an email. Instead of creating separate variables like userName, userAge, and userEmail, you can group them together in an object.

An object is a collection of key-value pairs. The keys are strings (also called properties), and the values can be any data type, including other objects or even functions.

const user = {
  firstName: "Alex",
  lastName: "Chen",
  age: 28,
  isEnrolled: true
};

You can access the data inside an object using dot notation.

console.log(user.firstName); // Outputs: "Alex"
console.log(user.age); // Outputs: 28

Objects aren't just for storing data; they can also have actions. A function that is part of an object is called a method. It lets the object do something.

const user = {
  firstName: "Alex",
  lastName: "Chen",
  // This is a method
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
};

// Call the method to get the full name
console.log(user.fullName()); // Outputs: "Alex Chen"

Notice the this keyword. Inside a method, this refers to the object itself (user in this case), allowing you to access its other properties.

Ready to test your knowledge? Let's see what you've learned.

Quiz Questions 1/6

You are writing a program to calculate the area of a circle. Which keyword is most appropriate for declaring a variable to store the value of Pi (π), which is approximately 3.14159?

Quiz Questions 2/6

A variable has been declared, but no value has been assigned to it. What is its value?

These are the fundamental building blocks of JavaScript. With variables, operators, control structures, functions, and objects, you have the tools to start building powerful and interactive applications.