Back to Blog

November 11, 2017: Quick Comments on JavaScript

Over a couple hours of debugging and searching the interwebs for answers, I learned a few important things about JavaScript that I wouldn't have necessarily expected coming from mainly coding in Python. While I have also had C++ and Java experience several years ago, it'd been a while since writing anything in a language similar to this.

Lesson 1

Consider the following example. Set

var x = [[0,1],[1,1],[2,7]];

That is, let x be a variable that is a nested array. Now set

var y = x;

Here, JavaScript, like many languages, thinks you want to copy the references for some reason, which has always seemed unnatural to me. In Python, something like y=np.copy(x) works, but with nested arrays in JavaScript, you have to loop through the arrays. At least for singly nested arrays like the one above, a solution is fairly straightforward.

The solution I found on the interwebs that worked for me is

var y = x.map(function(arr) {return arr.slice();});

Lesson 2

You cannot simply pass an array to Math.min or Math.max. Instead, if x is a non-nested array, then use

var max_x = Math.max.apply(null,x);

Until next time, imaginary blog readers.

Back to Blog