2.variables in JavaScript

Table of contents

No heading

No headings in the article.

Certainly! In JavaScript, variables are used to store and manage data. Here's a basic overview of how to declare and use variables:

  1. Declaration: You declare a variable using the var, let, or const keyword, followed by the variable name.

     // Using var (old way, not recommended)
     var myVar;
    
     // Using let (block-scoped)
     let myLet;
    
     // Using const (block-scoped, constant value)
     const myConst;
    
  2. Initialization: You can also assign a value to a variable at the time of declaration.

     let myVar = 10;
     const myConst = "Hello, World!";
    

    Note: const variables must be initialized at the time of declaration, and their value cannot be changed later.

  3. Data Types:

    • JavaScript is a dynamically-typed language, which means you don't explicitly declare the data type of a variable.

    • Common data types include:

      • Number (e.g., let num = 42;)

      • String (e.g., let greeting = "Hello";)

      • Boolean (e.g., let isTrue = true;)

      • Array (e.g., let myArray = [1, 2, 3];)

      • Object (e.g., let person = { name: "John", age: 25 };)

  4. Variable Naming Rules:

    • Variable names can contain letters, digits, underscores, and dollar signs.

    • They must begin with a letter, underscore, or dollar sign.

    • JavaScript is case-sensitive, so myVar and myvar are different variables.

// Example usage:
let firstName = "John";
let age = 25;
let isStudent = true;

console.log(firstName); // John
console.log(age); // 25
console.log(isStudent); // true