Variables and Data Types in JavaScript

Js Basics

Data Type in JavaScript

JavaScript is a dynamically typed language, which means you don't need to specify the data type explicitly when declaring a variable. The data type of a variable is determined automatically based on the assigned value

JavaScript has the following basic data types:

  1. Numbers (int, float)

  2. Strings

  3. Booleans

  4. Undefined

  5. Null

  6. Object

  7. Symbol (introduced in ES6)

    Example

     let age = 25; // Number data type
     let name = "Subham"; // String data type
     let isStudent = true; // Boolean data type
     let address; // Undefined data type (not explicitly assigned)
     let job = null; // Null data type
     let person = { firstName: "Subham", lastName: "Singh" }; // Object data type
     let uniqueKey = Symbol("unique"); // Symbol data type
    

    Variables in JavaScript

    Variables are like containers that store data, they are declared using var, let and const keywords.

    1. The let keyword allows you to store data value in a block scope.

    2. The const keyword is used for constants whose value cannot be changed after the assignment.

    3. The var was traditionally used in ES5 (ECMAScript 5) and earlier versions of JavaScript. Unlike let and const it is not block scoped.

       let age = 25; // Declaring a variable using let
       const height = 181; // Declaring a constant using const
       var name = "Subham"; // Declaring a variable using var (not recommended in modern JS)
      

      The issues with hoisting, function scoping, and the lack of block scoping, var can lead to subtle bugs and make code harder to reason about. For these reasons, developers usually prefer let variables that may change their values and that should remain constant throughout the program. As a result, the use of var is not recommended in modern JavaScript development practices.

      Note: Will understand more about the difference between var and let / const in upcoming articles.