Invalid array length allocation failed

Issue

I have the following script:

var doYou = "No", var reason = "I'm lazy";   
var doYou = "Ja", var reason = "Det kunne være fedt!";
var doYou = "Maybe", var reason = "Hmmm";
var doYou = "yes", var reason = "I'm ready for it!";

console.log(DoYouWannaScript(doYou, reason));

function DoYouWannaScript(answer, reason) {
    var obj = ['']
    var notValidString = 'Not a valid answer';
    var shortReasonMsg = 'Please state reason in more details';

    switch(answer) {
        case 'yes' :
          obj.push('Nice!');
          break;
        case 'no':
          obj.push('NOOOO!');
          break;
        case 'maybe':
          obj.push('Come on!');
          break;
        default:
          obj.push(notValidString);
    }

    if(validate(reason) && obj.indexOf(notValidString)==-1) {
        obj.push(shortReasonMsg); 
    }

    var objLength = obj.length;

    for (var i = 0; i < obj.length; i++) {
        obj.push("It's nice to work at Bass Pro Shop!"); 
    }

    return obj;
}

function validate(reason) {
    return reason.split(' ').length < 3
}

Output

I’m receiving this error when trying to run my JS:

FATAL ERROR: invalid array length Allocation failed – JavaScript heap out of memory

I’ve checked other similar posts that say to increase the memory size f.x., node --max-old-space-size=16000 yourFile.js or from FATAL ERROR to my script they both don’t work. Any help would be greatly appreciated.

Solution

Took me a while to write your code down. You shouldn’t be posting images of code.

Anyway, the problem lies here:

for(var i = 0; i < obj.length; i++)
{
    obj.push("It's nice to work at Devoteam!");
}

You are looping the same array to where you push more data inside the loop, thus the loop will never end and the array size becomes too large.

Answered By – Swiffy

Answer Checked By – Willingham (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.