Thursday, 21 November 2024

Variable types in JavaScript

In JavaScript, variables are used to store and manipulate data. JavaScript has a set of primitive and non-primitive (reference) types that determine what kind of data can be stored and how it behaves.


1. Primitive Types

Primitive types are immutable (they cannot be changed once they are created) and are stored directly in the variable. When you assign a primitive value to a new variable, the value is copied. JavaScript has the following primitive data types:

a) String

A string is a sequence of characters enclosed in single quotes ('), double quotes ("), or backticks (`).

    let name = "John";  // using double quotes

    let greeting = 'Hello, world!';  // using single quotes

    let message = `Hello, ${name}`;  // using backticks (template literals)

b) Number

Numbers in JavaScript can be integers or floating-point values.

    let age = 25;       // integer

    let price = 19.99;   // floating-point

Note: JavaScript does not differentiate between integers and floating-point numbers. They are both considered numbers.

c) BigInt

A BigInt is a numeric type that can represent large integers beyond the safe range of the Number type.

    let largeNumber = 1234567890123456789012345678901234567890n;  // BigInt

d) Boolean

A Boolean represents a truth value: either true or false.

    let isActive = true;

    let hasPermission = false;

e) Undefined

A variable that is declared but not assigned a value is of type undefined. Also, the value undefined can be explicitly assigned to a variable.

    let value;

    console.log(value);  // undefined

    let x = undefined;   // explicit assignment

f) Null

null is a special value representing "no value" or "no object." It is often used to indicate an intentional absence of any object value.

    let person = null;  // explicit null assignment

g) Symbol

A Symbol is a unique and immutable primitive value, often used to create unique property keys for objects.

    let sym1 = Symbol('description');

    let sym2 = Symbol('description');

    console.log(sym1 === sym2);  // false, symbols are unique

h) Object (a special kind of reference type)

Technically, objects are non-primitive types, but we often consider them as a separate category. Objects in JavaScript are collections of properties, and each property has a key-value pair.

    let person = {

      name: "John",

      age: 30

    };


2. Non-Primitive (Reference) Types

These types are reference types, meaning they store a reference to the memory location of the value rather than the value itself. When you assign a reference type to another variable, both variables point to the same object in memory, which means changes made to one will reflect in the other.

a) Object

An object is a collection of properties where each property is a key-value pair. Objects can store multiple values, including other objects and functions.

    let car = {

      make: "Toyota",

      model: "Corolla",

      year: 2020

    };

You can also use object constructors to create objects:

    let person = new Object();

    person.name = "Alice";

    person.age = 25;

b) Array

An array is an ordered collection of values, which can be of any type, including objects, numbers, or even other arrays.

    let fruits = ["apple", "banana", "cherry"];

    console.log(fruits[0]);  // "apple"

Arrays in JavaScript are essentially special kinds of objects that provide methods for managing ordered collections of values.

c) Function

Functions are also objects in JavaScript. Functions can be stored in variables, passed as arguments, and returned from other functions.

    function greet(name) {

      return `Hello, ${name}!`;

    }

    let greeting = greet("Alice");

Functions are first-class objects in JavaScript, meaning they can be manipulated like any other object.

d) Date

The Date object in JavaScript represents dates and times.

    let currentDate = new Date();

    console.log(currentDate);  // Current date and time


Summary of JavaScript Data Types:

Type

Description

Example

String

Textual data

"Hello, World!"

Number

Numeric values (integers and floats)

42, 3.14

BigInt

Large integers

1234567890123456789012345678901234567890n

Boolean

true or false values

true, false

Undefined

Variable declared but not assigned a value

undefined

Null

Represents no value or no object

null

Symbol

Unique, immutable values

Symbol('unique')

Object

Collections of key-value pairs

{name: "Alice", age: 25}

Array

Ordered list of values

[1, 2, 3]

Function

Callable objects

function() { return "Hello"; }

Date

Date and time objects

new Date()

 

Conclusion:

JavaScript provides a range of primitive and reference types to work with, each serving a different purpose. Understanding the differences between these types and how they behave is crucial for writing efficient and bug-free code in JavaScript.

 


No comments:

Post a Comment