Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript mystery: variables in functions

OK, I'm stumped, mainly because I don't use javascript enough. I know this is an array pointer problem (I must have to copy the array in the function...), but not sure how to fix it. Can I trouble you for an explanation why my Javascript version doesn't work and the Python version does? It is supposed to reverse an array (I know there is a built-in), but my question is: How are arrays in Javascript treated differently than in Python?

Javascript (does not work): 

function reverseit(x) {

  if (x.length == 0) { return ""};
  found = x.pop();
  found2 = reverseit(x);
  return  found + " " + found2 ;

};

var out = reverseit(["the", "big", "dog"]);

// out == "the the the"

==========================

Python (works):

def reverseit(x):
    if x == []: 
        return ""
    found = x.pop()
    found2 = reverseit(x)
    return  found + " " + found2

out = reverseit(["the", "big", "dog"]);

// out == "dog big the"     
like image 292
wgw Avatar asked Jul 28 '26 02:07

wgw


1 Answers

It should be...

  var found = x.pop();
  var found2 = reverseit(x);

Without localizing these variables you'll declare them as global ones - and rewrite their values each time reverseit is called. By the way, these errors can be prevented with 'use strict'; directive (MDN), if it's supported by the developer's browser (and it should be, in my opinion).

Obviously the code works in Python because found and found2 are local there.

But look at the bright side of JS life: you could just write that function like this:

function reverseit(x) {
  return x.length 
         ? x.pop() + " " + reverseit(x) 
         : "";
};
console.log(reverseit(['the', 'big', 'dog']));

... without declaring any local variables at all.

like image 110
raina77ow Avatar answered Jul 30 '26 15:07

raina77ow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!