2

I compile CoffeeScript with node. In a script I have a function which clears arrays. I want to console.log the empty array. I can't see the difference between the 3 block logs:

clearArray = (arr) ->
  arr.splice 0 , arr.length

#Block 1
arr = [1,2]
clearArray arr
console.log arr

#Block 2
array = [1,2]
console.log clearArray array

#Block 3
console.log clearArray [1,2] 

#Block 1 logs: []
#Block 2 & 3 log: [ 1, 2 ]

In my understanding all Blocks should log "[ ]" and return an empty array, since clearArray returns the result of arr.splice(). It seems like #Block2 &3 do not execute the splice function?! Any help is much appreciated.

2 Answers 2

4

Splice() modifies the array in place and returns an array with the elements you remove.

var arr = [1, 2];
var a = arr.splice(0, 2);

console.log(arr);
[] 

console.log(a);
[1, 2]
Sign up to request clarification or add additional context in comments.

Comments

2

As Rodrigo says splice returns the initial array, which leads to a missunderstanding caused by Coffee's implicit return statement. Your function is equivalent to this:

clearArray = (arr) ->
  return arr.splice 0 , arr.length

To solve this you have to return the sliced array

clearArray = (arr) ->
  arr.splice 0 , arr.length
  return arr

Wich again is the same as

clearArray = (arr) ->
  arr.splice 0 , arr.length
  arr

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.