惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

G
GRAHAM CLULEY
S
Security @ Cisco Blogs
P
Proofpoint News Feed
Cisco Talos Blog
Cisco Talos Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
Cyber Attacks, Cyber Crime and Cyber Security
T
Tor Project blog
WordPress大学
WordPress大学
Project Zero
Project Zero
S
Schneier on Security
P
Proofpoint News Feed
小众软件
小众软件
P
Privacy International News Feed
美团技术团队
L
LangChain Blog
Know Your Adversary
Know Your Adversary
J
Java Code Geeks
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
The Register - Security
The Register - Security
N
Netflix TechBlog - Medium
Microsoft Security Blog
Microsoft Security Blog
Engineering at Meta
Engineering at Meta
I
InfoQ
量子位
Vercel News
Vercel News
博客园 - 三生石上(FineUI控件)
Spread Privacy
Spread Privacy
D
DataBreaches.Net
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
U
Unit 42
P
Privacy & Cybersecurity Law Blog
C
Cybersecurity and Infrastructure Security Agency CISA
T
The Blog of Author Tim Ferriss
Latest news
Latest news
K
Kaspersky official blog
MongoDB | Blog
MongoDB | Blog
L
LINUX DO - 热门话题
Simon Willison's Weblog
Simon Willison's Weblog
云风的 BLOG
云风的 BLOG
S
Securelist
AWS News Blog
AWS News Blog
F
Fortinet All Blogs
T
Threat Research - Cisco Blogs
Stack Overflow Blog
Stack Overflow Blog
Scott Helme
Scott Helme
Help Net Security
Help Net Security
Y
Y Combinator Blog
宝玉的分享
宝玉的分享
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
T
Tenable Blog

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
Sparse vs Dense Arrays in JavaScript
Dmitri Pavlutin · 2021-10-27 · via Dmitri Pavlutin Blog

Arrays in JavaScript are pretty easy to use. However, there's a nuance you should be aware of: some arrays might have holes in them.

In this post, I'm going to describe the difference between sparse and dense arrays in JavaScript. Also, you'll find the common ways to create sparse arrays, just to be aware of.

1. Dense arrays

An array in JavaScript is an object representing an ordered collection of items.

The items in the array have an exact order. You can access the nth item of the array using a special number — the index.


const names = ['Batman', 'Joker', 'Bane'];

console.log(names[0]); // logs 'Batman'

console.log(names[1]); // logs 'Joker'

console.log(names[2]); // logs 'Bane'

console.log(names.length); // logs 3


Open the demo.

names[0] accesses the item of the array at index 0 (the first element).

The array also has a property length, which indicates the number of items in the array. In the previous example, names.length is 3 since the number of items in the array is 3.

names array created above is a dense array: meaning that it contains items at each index starting 0 until names.length - 1.

Here's a function isDense(array) that determines whether the array has items at each index:


function isDense(array) {

for (let index = 0; index < array.length; index++) {

if (!(index in array)) {

return false;

}

}

return true;

}

const names = ['Batman', 'Joker', 'Bane'];

console.log(isDense(names)); // logs true


Open the demo.

where index in array determines if the array has an item at index position.

Here's an interesting question: are all arrays in JavaScript dense? Or there might be arrays when isDense(array) would return false?

Let's dig more!

2. Sparse arrays

Unfortunately... there are situations when JavaScript arrays can have holes in them. Such arrays are named sparse.

For example, if you use the array literal but omit indicating an item, then a hole is created in the place of the missing item. And as result a sparse array is created:


const names = ['Batman', , 'Bane'];

console.log(names[0]); // logs 'Batman'

console.log(names[1]); // logs undefined

console.log(names[2]); // logs 'Bane'

console.log(isDense(names)); // logs false


Open the demo.

['Batman', , 'Bane'] array literal creates a sparse array, having a hole at the 1 index. If you access the value of a hole — names[1] — it evaluates to undefined.

To check explicitly whether there's a hole at a specific index you need to use index in names expression:


const names = ['Batman', , 'Bane'];

// No hole

console.log(0 in names); // logs true

// Hole

console.log(1 in names); // logs false


Open the demo.

Of course, if you run isDense() on a sparse array it will return false:


const names = ['Batman', , 'Bane'];

console.log(isDense(names)); // logs false


Open the demo.

Now you have a clue about the sparse arrays. But what are the common ways to create sparse arrays?

Let's find out in the next section.

3. Ways to create sparse arrays

Here's a list of the most common ways to create sparse arrays in JavaScript.

3.1 Array literal

As already mentioned, omitting a value when using the array literal creates a sparse array (note the empty word in the logger array):


const names = ['Batman', , 'Bane'];

console.log(names); // logs ['Batman', empty, 'Bane']


Open the demo.

3.2 Array() constructor

Invoking Array(length) or new Array(length) (with a number argument) creates a fully sparse array:


const array = Array(3);

console.log(isDense(array)); // logs false

console.log(array); // logs [empty, empty, empty]


Open the demo.

3.3 delete operator

When you use delete array[index] operator on the array:


const names = ['Batman', 'Joker', 'Bane'];

delete names[1];

console.log(isDense(names)); // logs false

console.log(names); // logs ['Batman', empty, 'Bane']


Open the demo.

Initially, names array is dense.

But executing delete names[1] deletes the item at index 1 and makes names array sparse.

3.4 Increase length property

If you increase length property of an array, then you also create holes in the array:


const names = ['Batman', 'Joker', 'Bane'];

names.length = 5;

console.log(isDense(names)); // logs false

console.log(names); // logs ['Batman', 'Joker', 'Bane', empty, empty]


Open the demo.

Initially names array had 3 items, and it was a dense array.

However, increasing the names.length to 5 items creates 2 holes — at 3 and 4 indexes.

On a side note, decreasing the length property doesn't create a sparse array but removes items from the end of the array.

4. Array methods and sparse arrays

A problem of the sparse arrays is that many array built-in methods just skip the holes in a sparse array.

For example, array.forEach(eachFunc) doesn't not invoke eachFunc on the holes:


const names = ['Batman', , 'Bane'];

names.forEach(name => {

console.log(name);

});

// logs 'Batman'

// logs 'Bane'


Open the demo.

Same way array.map(mapperFunc), array.filter(predicateFunc), and more functions do skip the holes. If you've accidentally created a sparse array, you might find a hard time understanding why an array method doesn't work as expected.

Challenge: do you know array functions in JavaScript that don't skip the empty holes?

5. Conclusion

In JavaScript, an array can be dense or sparse.

An array is dense if there are items at each index starting 0 until array.length - 1 . Otherwise, if at least one item is missing at any index, the array is sparse.

While you won't deal much with sparse arrays, you should be aware of the situations when one can be created:

  • when skipping a value inside an array literal [1, , 3]
  • when using Array(length)
  • when using delete array[index]
  • when increasing array.length property

The problem with sparse arrays is that some JavaScript functions (like array.forEach(), array.map(), etc.) skip empty holes when iterating over the array items.

What other ways to create sparse arrays in JavaScript do you know?