0

Can you please explain how to worship JavaScript gods and work around this one.

var array = ['old'];
    
function manageArray(targetArray) {
  targetArray = ['new'];
}

manageArray(array);
alert(array);

The reason for this is to create a pattern that will have filter logic and instead of declaring explicit methods for each array have one universal to rule over all.

Desired logic

var numbers = ['1', '2']
var words = ['room', 'car']
var color = ['red', 'blue']

function manageArray(targetArray, value) {
  targetArray = targetArray.filter(existingValue, () => {
    return existingValue != value
  })
}

manageArray(words, 'car');
alert(words);
1
  • 1
    What are you expecting to happen here? targetArray is scoped to your function Commented May 13, 2017 at 12:52

2 Answers 2

1

From what I understand, you want to pass your variable by reference. It is sad that Javascript pass array as value. There are a few ugly workaround.

var array = {v: ['old'] };

function manageArray(targetArray) {
  targetArray.v = ['new'];
}

manageArray(array);

or

var array = ['old'];

function manageArray(targetArray) {
    return ['new'];
}

array = manageArray(array);

For further reading:

Sign up to request clarification or add additional context in comments.

Comments

1

You'll be able to access the array if you have your function return it:

var array = ['old'];
    
function manageArray(targetArray) {
  targetArray = ['new'];
  return targetArray
}

array = manageArray(array);
alert(array);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.