Variables and Data Types


Variables in JavaScript

A variable is a container for storing data. You can think of it as a named storage location. In JavaScript, variables can hold various types of data, including numbers, strings, and objects.

Example 1: Declaring Variables

// Declaring variables using 'let' keyword
let name = "John";
let age = 30;

// Variables can also be declared using 'var' (older syntax)
var country = "USA";
  • let and var are keywords used to declare variables. let is the modern and recommended way to declare variables, as it has block scope (limited to the block where it’s defined), whereas var has function scope (limited to the function where it’s defined).
  • name, age, and country are variable names. They should be descriptive and meaningful.
  • = is the assignment operator used to assign a value to a variable.

Data Types in JavaScript

JavaScript has several data types, including numbers, strings, booleans, objects, and more. Understanding data types helps you work with different kinds of information in your programs.

Example 2: Data Types

let number = 42;             // Number
let greeting = "Hello";      // String
let isTrue = true;           // Boolean

let person = {
    firstName: "John",
    lastName: "Doe"
};                           // Object (key-value pairs)

let fruits = ["apple", "banana", "cherry"]; // Array
  • number, greeting, and isTrue are variables holding different data types: number, string, and boolean, respectively.
  • person is an object. It contains key-value pairs (properties and their values).
  • fruits is an array. It’s a collection of values, each identified by an index.

Using Variables in JavaScript

Once you’ve declared variables, you can use them to perform operations, concatenate strings, and more.

Example 3: Using Variables

let firstName = "John";
let lastName = "Doe";

let fullName = firstName + " " + lastName; // Concatenation

let age = 30;
let nextYearAge = age + 1; // Mathematical operation

let isAdult = age >= 18;   // Comparison
  • In Example 3, we demonstrate how to use variables in various operations, including concatenation, mathematical operations, and comparisons.

Leave a Reply

Your email address will not be published. Required fields are marked *