www.xbdev.net
xbdev - software development
Thursday March 27, 2025
Home | Contact | Support | JavaScript... so much power in such a few lines of code..
     
 

JavaScript...

so much power in such a few lines of code..

 


Exploring Javascript Arrays: The Good, The Bad and the Undefined



Arrays are very important! They make managing our data effortless.
Arrays are very important! They make managing our data effortless.



Probably the simplest and easiest way to create an array in Javascript is using literal:

const arr = [0,1,9];


Of course, it's the easiest, but not the only way - it's also not the best way in all cases (e.g., when creating very large arrays).


Key points to think about when creating arrays:
• Arrays with holes (i.e., undefined values)
• References in the array (objects link to the same item)
• Order of the array (sequential)
• Size of the array (very large or small)


While holes in arrays (undefined elements) might does not cause problems for the developer, it does cause problems for the underlying web-browser performance. A dense or packed array can be stored in contiguously memory, otherwise, if even one hole exists, a dictionary or a complex structure is needed to manage the array (like a linked list); causing performance slowdowns.

Creating Arrays


Array constructor


Create an array by passing the length:

const LEN 3;
const 
arr = new Array(LEN);
assert.equal(arr.lengthLEN);


Some points to think about when using this approach:
• The array is full of undefined values
• You'd have to do a second pass to fill the array (e.g., initialize it with all zeros, such as .fill())


The .fill() method changes an existing Array and fills it with a specified value. That helps with initializing an Array after creating it via new Array():

const LEN 3;
const 
arr = new Array(LEN).fill(0);
assert.deepEqual(arr, [000]);


References and Values


If you .fill() an Array with an Object - all the elements refer to teh same instance (it's NOT cloned).

const LEN 3;
const 
obj = {};

const 
arr = new Array(LEN).fill(obj);
assert.deepEqual(arr, [{}, {}, {}]);

obj.prop true;
assert.deepEqual(arr,
  [ {
prop:true}, {prop:true}, {prop:true} ]);



There is also the method of filling an array using Array.from() which has advantages over Array.fill().


.push() method


const LEN 3;
const 
arr = [];
for (
let i=0LENi++) {
  
arr.push(0);
}
assert.deepEqual(arr, [000]);


The array was created and fillsed using push(). After array is created it's filled (no undefined or additional passes needed to initialize or fill).


Filling Arrays with undefined


Array.from()
converts iterables and Array-like values to Arrays. It treats holes as if they were undefined elements. You use that to convert each hole to an undefined:

> Array.from({length3})
undefinedundefinedundefined ]


The parameter
{length: 3}
is an Array-like object with
length
3 that contains only holes. It is also possible to instead use
new Array(3)
, but that usually creates larger objects.

Spreading into Arrays only works for iterable values and has a similar effect to
Array.from()
:

> [...new Array(3)]
undefinedundefinedundefined ]


So,
Array.from()
creates its result via
new Array()
, so you still end up with a sparse Array.


Mapping with Array.from()


You can use Array.from() to map, if you provide a mapping function as its second parameter.

Example of filling an Array with values using
Array.from()
:

> Array.from({length3}, () => 0)
00]


Example of creating an Array with unique (unshared) objects:

> Array.from({length3}, () => ({}))
[ {}, {}, {} ]


Example of creating an Array with ascending integers:

> Array.from({length3}, (xi) => i)
01]


Example of creating an arbitrary range of integers:

> const START=2END=5;
> Array.
from({lengthEND-START}, (xi) => i+START)
23]


Another way of creating an Array with ascending integers is via
.keys()
, which also treats holes as if they were undefined elements:

> [...new Array(3).keys()]
01]
.
keys() returns an iterableWe use spreading to convert it to an Array.



Less Theory More Practice - Real-Worl Array (Hacking) Creating


What is the quickest and most concise way to create an array of a specific size (that is initialized)?

Create an array ,using
new Array
- but it's filled with holes:
new Array(3)
[
undefinedundefinedundefined]


Same again, we can create an array using
Array.from(..)
but it's still filled with holes:
Array.from({length2})
[
undefinedundefined]


We can even use the triple dot syntax to create an array, but we end up with holes:
[...new Array(2)]
[
undefinedundefined]


Established three ways of creating arrays, but we want to tweak these approaches so the created arrays are densly packed (with no undefines).


Push the data into an empty array as needed using
.push()
:
const a=[]; for (let i=0i<3i++) a.push(0);
[
000]


The trusty
fill()
function

new Array(3).fill(0)
[
000]


Then we have the
Array.from(..)
,
{length:3}
and
assignment
iterator:
Array.from({length3}, () => ({}))
[{}, {}, {}] (
unique objects)


Going beyond just 0s, but integer values (index or arbitary values):

Array.from({length3}, (xi) => i)
[
012]


Take advantage of the modulus - we also add a scaling so the number is greater than the modulus triggering the number to roll-around:
Array.from( {length12}, (xi) => (i*100%22) )
[
0,12,2,14,4,16,6,18,8,20,10,0]


Need little trick to use the
keys
. When the array is created, it's a dictionary until the array has been filled in:

[...new Array(3).keys()]
[
012]


Readability vs Performance



If you're working with Javascript, I don't you'll be cycle counting and trying to sqeeze performance! A rule of thumb, focus on readability and good coding practices - then if you do find something suspicous is causing problems (stuttering, stablity or slowdowns) - you can do some profiling and analysis later on.

Web-browsers are very powerful these days - and the underlying system does a lot of optimzations - you can write dirtly slow code and it'll still perform lighting fast.

We're at the point were vanilla applications run as fast as web-based ones.

Larger web-based applications with high-def graphics, simulations, LLM, etc - might use hundreds of megs/gigs of memory/data!


Food for Thought


Do you need to create an empty Array that you'll fill later on? (doesn't matter if it has undefined elements)
new Array(LEN)


Do you need to create an Array initialized with some default constant (e.g., 0 or 9)?
new Array(LEN).fill(0)


Do you need to create an Array initialized with objects?
Array.from({length: LEN}, () => ({}))


Do you need to create an array with random integer values?
Array.from( {length: LEN}, (x, i) => (i*LEN*5%LEN) )


If you are dealing with Arrays of integers or floats, consider Typed Arrays. They can't have holes and are always initialized with zeros.


Typed Arrays (That's Another Story)


Just to end typed arrays - here is a list (so you can see what's available). Typically, you'd use typed arrays if you're working with hardware, like WebGPU or WebGL and are creating vertex and index buffers for the data.

Of course, it's very easy to convert from a normal array to a typed array.

let b Float32Array.from(  new Array(3).fill(0) );
[{
"0":0,"1":0,"2":0}]


Data Type Range Size
Int8Array -128 to 127 1 byte
Uint8Array 0 to 255 1 octet
Uint8ClampedArray 0 to 255 1 octet
Int16Array -32768 to 32767 2 short
Uint16Array 0 to 65535 2 unsigned short
Int32Array -2147483648 to 2147483647 4 long
Uint32Array 0 to 4294967295 4 unsigned long
Float32Array -3.4e38 to 3.4e38 4 unrestricted float
Float64Array -1.8e308 to 1.8e308 8 unrestricted double
BigInt64Array -2^63 to 2^63 - 1 8 bigint
BigUint64Array 0 to 2^64 - 1 8 bigint









































101 WebGPU Programming Projects. WebGPU Development Pixels - coding fragment shaders from post processing to ray tracing! WebGPU by Example: Fractals, Image Effects, Ray-Tracing, Procedural Geometry, 2D/3D, Particles, Simulations WebGPU Games WGSL 2d 3d interactive web-based fun learning WebGPU Compute WebGPU API - Owners WebGPU Development Cookbook - coding recipes for all your webgpu needs! WebGPU & WGSL Essentials: A Hands-On Approach to Interactive Graphics, Games, 2D Interfaces, 3D Meshes, Animation, Security and Production Kenwright graphics and animations using the webgpu api 12 week course kenwright learn webgpu api kenwright programming compute and graphics applications with html5 and webgpu api kenwright real-time 3d graphics with webgpu kenwright webgpu for dummies kenwright webgpu api develompent a quick start guide kenwright webgpu by example 2022 kenwright webgpu gems kenwright webgpu interactive compute and graphics visualization cookbook kenwright wgsl webgpu shading language cookbook kenwright WebGPU Shader Language Development: Vertex, Fragment, Compute Shaders for Programmers Kenwright WGSL Fundamentals book kenwright WebGPU Data Visualization Cookbook kenwright Special Effects Programming with WebGPU kenwright WebGPU Programming Guide: Interactive Graphics and Compute Programming with WebGPU & WGSL kenwright Ray-Tracing with WebGPU kenwright



 
Advert (Support Website)

 
 Visitor:
Copyright (c) 2002-2025 xbdev.net - All rights reserved.
Designated articles, tutorials and software are the property of their respective owners.