Open In App

Set vs Array in JavaScript

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

In JavaScript, Set and Array are common data structures used to store collections of data. These data structures are different because of their unique features. Let us look at the implementation of both of these data structures.

JavaScript Set

Sets are used to store collections of unique value without allowing duplication. The set is similar to the array and supports both insertion and deletion methods of the array. Sets are faster than arrays in terms of searching as they use a hash table internally for storing data and can be used to replace duplicates from other data types.

Syntax:

new Set([it]);

Parameter: 

  • it: It is an iterable object whose all elements are added to the new set created, If the parameter is not specified or null is passed then a new set created is empty.

Return Value:

A new set object.

Example: In this example, we will implement a set.

Javascript




let sample = new Set();
sample.add("Hello");
sample.add(1)
sample.add("Bye")
sample.add("@");
for (let item of sample) {
    console.log(item);
}


Output

Hello
1
Bye
@

JavaScript Array

The array is a data structure that is used to store data in a sequential manner of the same type. Arrays allow duplication of data and data is indexed which means that the data can be accessed according to its unique index.

Syntax:

let arrayName = [value1, value2, ...]; // Method 1
let arrayName = new Array(); // Method 2

Example: In this example, we will implement an array and access its element.

Javascript




let sample = new Array();
sample.push("Hello");
sample.push("1")
sample.push("Bye")
sample.push("@");
console.log(sample);
console.log(sample[3])


Output

[ 'Hello', '1', 'Bye', '@' ]
@

What to use?

The usage of the data structure depends on the requirement. If you want to have a unique list of items where each element can only be present once and also want faster access to the elements then use set otherwise if you want to access the element according to its insertion order then use array.

Difference between Set and Array

Set Array
Collection of unique value Sequential collection of data
Duplication is not allowed Duplication is allowed
Accessing elements is faster Searching is slow comparatively
Elements are accessed using hash table Elements are accessed using index


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads