1

Lesson 2: Variables and Data Types

What Are Variables?

In JavaScript, variables are used to store data that can be referenced and manipulated in a program. You can think of variables as containers for storing values. JavaScript allows you to declare variables using var, let, and const.

Declaring Variables

JavaScript provides three ways to declare variables:

  • var - Declares a variable that can be reassigned later. It has function-level scope.
  • let - Similar to var, but it has block-level scope. Use let when the variable's value will change.
  • const - Declares a variable with a constant value that cannot be reassigned. Use const for values that will not change.

Example

Here’s an example of how to declare and use variables:

// Using var
      var name = "John";
      console.log(name);  // Output: John
      
      // Using let
      let age = 25;
      console.log(age);  // Output: 25
      
      // Using const
      const country = "USA";
      console.log(country);  // Output: USA

Data Types in JavaScript

JavaScript provides different types of data that can be stored in variables. These are called data types. JavaScript is a dynamically typed language, meaning you don’t have to specify the data type of a variable when declaring it.

Primitive Data Types

  • String: Represents text, enclosed in single or double quotes. Example: "Hello"
  • Number: Represents numerical values. Example: 42 or 3.14
  • Boolean: Represents a logical value, either true or false.
  • Undefined: A variable that has been declared but not yet assigned a value.
  • Null: Represents the intentional absence of a value.

Example

// String
      let greeting = "Hello World";
      console.log(greeting);  // Output: Hello World
      
      // Number
      let score = 100;
      console.log(score);  // Output: 100
      
      // Boolean
      let isJavaScriptFun = true;
      console.log(isJavaScriptFun);  // Output: true
      
      // Undefined
      let undefinedVar;
      console.log(undefinedVar);  // Output: undefined
      
      // Null
      let emptyVar = null;
      console.log(emptyVar);  // Output: null

Assignment

Your task: Create variables using var, let, and const to store a string, number, and boolean value. Print each variable to the console. Then, experiment with undefined and null.