Open In App

Difference Between Variables and Objects in JavaScript

Last Updated : 13 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The variables and objects are fundamental concepts but they serve different purposes. The Variables are used to store data values while objects are used to group related data and functions into a single entity.

JavaScript Variable

A variable in JavaScript is a named container that stores a value. It can be created using the var, let, or const.

Syntax:

let variable_name = value;
const variable_name = value;

Example: In this example, age is a variable that holds a numeric value and name is a variable holding the string value.

Javascript




let age = 35;
const name = 'Kumar';
console.log("Age: " + age);
console.log("Name: " + name);


Output:

Age: 35
Name: Kumar

JavaScript Object

An object in JavaScript is a complex data structure that groups related data together using the key-value pairs.

Syntax :
let object_name = {
key1 : value1,
key1 : value1,
...
};

Example: In this example, The person is an object with the properties like name, age, hobbies and address. It includes both the primitive data types and other objects.

Javascript




let person = {
    name: 'Kumar',
    age: 25,
    hobbies: ['reading', 'painting'],
    address: {
        street: '127 Main St',
        city: 'Bangalore City'
    }
};
console.log("Name: " + person.name);
console.log("Age: " + person.age);
console.log("Hobbies: " + person.hobbies.join(', '));
console.log("Street: " + person.address.street);
console.log("City: " + person.address.city);


Output:

Name: Kumar
Age: 25
Hobbies: reading, painting
Street: 127 Main St
City: Bangalore City

Difference between variables and object in JavaScript

Characteristics

Variable

Object

Definition

Containers for the storing single data values.

The Complex data structures that store collections of the data and entities.

Usage

The Holds single data values.

The Stores complex entities and data structures.

Declaration

Declared using the keywords like var, let, const.

To Declared by defining key-value pairs within the curly braces.

Mutability

Can be updated or reassigned with the different values.

Properties can be added, updated or deleted.

Example

let num = 10;

const name = ‘John’;

let person = { name: ‘Alice’, age: 25 };

Access

Access using the variable name.

Access properties using the dot notation or bracket notation.

Data Type

Can hold different data types.

Can contain any data type including the other objects.

Purpose

Used for the storing individual values.

Used for the grouping related data or entities together.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads