Learn The Web

Basics

Variables, Data Types, and Operators

You've decided to learn JavaScript - great choice! Before you can start building complex web applications, you need to understand the fundamental building blocks of the language. This section will cover the essential basics: variables, data types, and operators. Think of these as the alphabet and basic grammar rules of JavaScript.

Variables

A variable is a named storage location in your computer's memory that you can use to store data. You can think of it as a labeled box where you can put different values.

In JavaScript, you declare variables using the let, const, or var keywords:

  • let: Declares a block-scoped variable. This means the variable is only accessible within the block of code where it's defined (e.g., inside an if statement or a for loop). let is the preferred way to declare variables in modern JavaScript.
let message = "Hello, world!";
console.log(message); // Output: Hello, world!
  • const: Declares a block-scoped constant. A constant is a variable whose value cannot be changed after it's initialized. Use const for values that should never be reassigned.
const PI = 3.14159;
console.log(PI); // Output: 3.14159
 
// PI = 3.14; // This will cause an error!
  • var: Declares a function-scoped variable. This means the variable is accessible throughout the entire function where it's defined (or globally if it's defined outside of any function). var is an older way to declare variables, and it's generally recommended to use let or const instead. It doesn't follow the current scope standards.
function myFunction() {
  var name = "John";
  console.log(name); // Output: John
}
 
myFunction();
// console.log(name); // This will cause an error (name is not defined outside the function)!

Recommendation: Use const for variables whose values should not change and let for variables whose values may change. Avoid using var in modern JavaScript.

Data Types

A data type specifies the kind of value that a variable can hold. JavaScript has several built-in data types:

  • Number: Represents numeric values, both integers and floating-point numbers.
let age = 30;
let price = 9.99;
  • String: Represents textual data. Strings are enclosed in single quotes (') or double quotes (").
let name = "Alice";
let greeting = "Hello, " + name + "!"; // String concatenation
console.log(greeting); // Output: Hello, Alice!
  • Boolean: Represents a logical value that can be either true or false.
let isLoggedIn = true;
let isAdult = age >= 18; // Evaluates to true if age is 18 or greater
console.log(isAdult); // Output: true
  • Undefined: Represents a variable that has been declared but has not been assigned a value.
let city;
console.log(city); // Output: undefined
  • Null: Represents the intentional absence of a value.
let user = null; // User is not currently logged in
console.log(user); // Output: null
  • Symbol: Represents a unique and immutable identifier (introduced in ECMAScript 2015). Symbols are often used as keys in objects.
const mySymbol = Symbol("description");
console.log(mySymbol); // Output: Symbol(description)
  • Object: Represents a collection of key-value pairs. Objects are used to store more complex data structures.
let person = {
  name: "Bob",
  age: 40,
  city: "New York",
};
 
console.log(person.name); // Output: Bob
console.log(person.age); // Output: 40
  • Array: Represents an ordered list of values.
let colors = ["red", "green", "blue"];
console.log(colors[0]); // Output: red
console.log(colors.length); // Output: 3

Operators

Operators are symbols that tell JavaScript to do something with values.

  • Math Operators: Used for calculations.
    • + (add)
    • - (subtract)
    • * (multiply)
    • / (divide)
let x = 10;
let y = 5;
 
console.log(x + y); // Output: 15
console.log(x - y); // Output: 5
console.log(x * y); // Output: 50
console.log(x / y); // Output: 2
  • Comparison Operators: Used to compare values.
    • == (equal to)
    • != (not equal to)
    • > (greater than)
    • < (less than)
let b = 10;
let c = 5;
 
console.log(b > c); // Output: true
console.log(b < c); // Output: false
  • Logical Operators: Used to combine or modify boolean expressions.
    • && (logical AND)
    • || (logical OR)
    • ! (logical NOT)
let isLoggedIn = true;
let isAdmin = false;
 
console.log(isLoggedIn && isAdmin); // Output: false
console.log(isLoggedIn || isAdmin); // Output: true
console.log(!isLoggedIn); // Output: false
  • String Operators:
    • + (concatenation): Used to concatenate strings.
let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName; // String concatenation
console.log(fullName); // Output: John Doe
  • Ternary Operator: A shorthand way of writing an if...else statement.
let age2 = 20;
let isAdult2 = age2 >= 18 ? "Yes" : "No";
console.log(isAdult2); // Output: Yes

Control Flow: if...else and Loops

if...else Statements

if...else statements allow you to execute different blocks of code based on a condition.

let age3 = 15;
 
if (age3 >= 18) {
  console.log("You are an adult.");
} else {
  console.log("You are a minor.");
}
// Output: You are a minor.

You can also chain if...else if...else statements for multiple conditions:

let score = 75;
 
if (score >= 90) {
  console.log("A");
} else if (score >= 80) {
  console.log("B");
} else if (score >= 70) {
  console.log("C");
} else {
  console.log("D");
}
// Output: C

Loops

Loops allow you to repeat a block of code multiple times. JavaScript provides several types of loops: while, for, and forEach.

  • while Loop: The while loop executes a block of code as long as a condition is true.
let i = 0;
 
while (i < 5) {
  console.log(i);
  i++;
}
// Output: 0 1 2 3 4
  • for Loop: The for loop is commonly used to iterate a specific number of times.
for (let j = 0; j < 5; j++) {
  console.log(j);
}
// Output: 0 1 2 3 4
  • forEach Loop: The forEach loop is used to iterate over the elements of an array.
let colors2 = ["red", "green", "blue"];
 
colors2.forEach(function(color) {
  console.log(color);
});
// Output: red green blue

You can also use arrow function syntax for a more concise forEach loop:

colors2.forEach(color => console.log(color));
// Output: red green blue

Practice and Experiment

Understanding variables, data types, operators, if...else statements and loops is essential for writing any JavaScript code. Practice using these concepts in different scenarios. The more you experiment, the better you'll understand how they work!

Last updated on

On this page