Marketing Cloud - SSJS new Array(n) constructor reads n as value versus length of array
Trailblazer Community

Marketing Cloud - SSJS new Array(n) constructor reads n as value versus length of array

Marketing Cloud Email Studio , Marketing Cloud API

Last updated 2019-04-23 ·Reference W-6061268 ·Reported By 0 users

No Fix

Summary
When using MC's Server Side Javascript and creating a new array via:

var testVar = new Array(5);

This will actually return an array equal to [5] versus [null,null,null,null,null]. If a number is passed to this, it should be reading that as the new array's length but is instead treating it as a value in the array.

Repro
<script runat=server>
Platform.Load("Core","1.1.1");
var testArray = new Array(5);
Write("This is the string to new Array(5)");
Write("<br>");
Write(testArray[0]);
</script>

Renders:

This is the string to new Array(5)
5

If you instead output testArray[1] it's empty.

Workaround
Utilize the Javascript push function to add values to an array such as this:

<script runat=server>
Platform.Load("Core","1");

var data = [];

data.push('0');
data.push('1');

Write("data[0] = ");
Write(data[0]);
Write("<br>");
Write("data[1] = ");
Write(data[1]);
Write("<br>");
Write("data.length = ");
Write(data.length);

</script>

Reported By (0)

Any unreleased services, features, statuses, or dates referenced in this or other public statements are not currently available and may not be delivered on time or at all. Customers who purchase our services should make their purchase decisions based upon features that are currently available.