Push new element into array using for loop

The idea is that now I have an original array, let’s say

[1,2,3,4,5]

and I want to add in new element: ["a"]

why is the code below not working?

function add(new_element){
	let arr = [1,2,3,4,5];
	for(let i=0;i<arr.length;i++)
	{
		arr.push(new_element);
	}

	return arr;
}

console.log(add("a"));

Did I just created a code snippet that will run indefinitely? hence exceeding the memory limit??
This is the error I get when trying to execute this code using node.


<--- Last few GCs --->

[63372:0x102801000]     2645 ms: Mark-sweep 667.2 (674.8) -> 667.2 (674.8) MB, 196.6 / 0.0 ms  allocation failure GC in old space requested
[63372:0x102801000]     2848 ms: Mark-sweep 667.2 (674.8) -> 667.2 (671.8) MB, 203.2 / 0.0 ms  last resort GC in old space requested
[63372:0x102801000]     3044 ms: Mark-sweep 667.2 (671.8) -> 667.2 (671.8) MB, 196.2 / 0.0 ms  last resort GC in old space requested


<--- JS stacktrace --->

==== JS stack trace =========================================

Security context: 0x19d80bc25879 <JSObject>
    1: add [/Users/zhouxiang/Desktop/JS/sublime.js:~1] [pc=0x2078c0a86c09](this=0x19d822f8c209 <JSGlobal Object>,new_element=0x19d875e883a9 <String[1]: a>)
    2: /* anonymous */ [/Users/zhouxiang/Desktop/JS/sublime.js:11] [bytecode=0x19d83ab56879 offset=22](this=0x19d875ece889 <Object map = 0x19d8a40023b9>,exports=0x19d875ece889 <Object map = 0x19d8a40023b9>,require=0x19d875ece841 <JSFunction r...

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
 1: node::Abort() [/usr/local/bin/node]
 2: node::FatalException(v8::Isolate*, v8::Local<v8::Value>, v8::Local<v8::Message>) [/usr/local/bin/node]
 3: v8::internal::V8::FatalProcessOutOfMemory(char const*, bool) [/usr/local/bin/node]
 4: v8::internal::Factory::NewUninitializedFixedArray(int) [/usr/local/bin/node]
 5: v8::internal::(anonymous namespace)::ElementsAccessorBase<v8::internal::(anonymous namespace)::FastPackedObjectElementsAccessor, v8::internal::(anonymous namespace)::ElementsKindTraits<(v8::internal::ElementsKind)2> >::GrowCapacity(v8::internal::Handle<v8::internal::JSObject>, unsigned int) [/usr/local/bin/node]
 6: v8::internal::Runtime_GrowArrayElements(int, v8::internal::Object**, v8::internal::Isolate*) [/usr/local/bin/node]
 7: 0x2078c09042fd
[Finished in 3.1s with exit code -6]
[cmd: ['/usr/local/bin/node', '/Users/zhouxiang/Desktop/JS/sublime.js']]
[dir: /Users/zhouxiang/Desktop/JS]
[path: /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/share/dotnet:~/.dotnet/tools:/Library/Frameworks/Mono.framework/Versions/Current/Commands:/Applications/Xamarin Workbooks.app/Contents/SharedSupport/path-bin]
1 Like

Your code crashed my computer! Yes, it is an infinte loop. Everytime you push a new element into the array, its length increases by 1. So when the loop condition i<arr.length is re-assessed, it never evaluates to false, thus causing an infinite loop. You should use a condition which doesn’t change when you push an element.

3 Likes

Generally speaking, it is a very bad idea to mutate an array that you are iterating over.

2 Likes

I see. Sorry about crashing your com though! :joy:

1 Like

Maybe I should create an identical array then change it instead?

1 Like

I am trying to work on this challenge: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/write-higher-order-arrow-functions/

const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34];
const squareList = (arr) => {
  "use strict";
  // change code below this line
  const squaredIntegers = arr;
  // change code above this line
  return squaredIntegers;
};
// test your code
const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers);

It requires me to out put an array that contains square of 4,42,6. Right now I can only out put those individually.

const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34];
const squareList = (arr) => {
  "use strict";

  for(let i=0;i<realNumberArray.length;i++){

  	if(realNumberArray[i]>0 && Number.isInteger(realNumberArray[i])){
  		var new_array = [];
  		new_array.push(realNumberArray[i]*realNumberArray[i]);
  		console.log(new_array);
  	}

  }
};

const squaredIntegers = squareList(realNumberArray);

Here is my answer. console.log will give out the correct answer I think. Is this correct?

const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34];
const squareList = (arr) => {
  "use strict";
	var new_array = [];
  for(let i=0;i<realNumberArray.length;i++){

  	if(realNumberArray[i]>0 && Number.isInteger(realNumberArray[i])){
  		new_array.push(realNumberArray[i]*realNumberArray[i]);
  		console.log(new_array);
  	}

  }
  return new_array;
};


const squaredIntegers = squareList(realNumberArray);
console.log(squareList);

1 Like

wait I think I got it.
But I still need to convert it into arrow function.

const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34];
const squareList = (arr) => {
  "use strict";
  /**/
	var squaredIntegers = [];
  for(let i=0;i<realNumberArray.length;i++){

  	if(realNumberArray[i]>0 && Number.isInteger(realNumberArray[i])){
  		squaredIntegers.push(realNumberArray[i]*realNumberArray[i]);
  	}

  }
  return squaredIntegers;
};


const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers);