1

I am trying to understand source code from ionic codePen: http://codepen.io/ionic/pen/rxysG The developer has used the following piece of code in his demo:

 $scope.messages = messageOptions.slice(0, messageOptions.length);

Why the developer didn't write:

$scope.messages = messageOptions;   //messageOptions is an array defined in the code which you can check from the codepen link that I have pasted.
Satpal
  • 132,252
  • 13
  • 159
  • 168
Deep Arora
  • 1,900
  • 2
  • 24
  • 40
  • 1
    Becouse he wanted to create copy of an array: http://stackoverflow.com/questions/3978492/javascript-fastest-way-to-duplicate-an-array-slice-vs-for-loop – lucas Aug 18 '15 at 07:56

2 Answers2

4

The statement $scope.messages = messageOptions.slice(0, messageOptions.length); create a clone/copy of array and assigning it to $scope.messages

You can also achieve same using

 $scope.messages = messageOptions.slice();

Code to demonstrate

var messageOptions = [1, 2];
var messages = messageOptions.slice(0, messageOptions.length);

//Update 
messageOptions[0] = 100;

snippet.log("messages: " + JSON.stringify(messages));
snippet.log("messageOptions: " + JSON.stringify(messageOptions));
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Satpal
  • 132,252
  • 13
  • 159
  • 168
0

For messageOptions may be an array-like object like arguments instead of an instance of Array and they probably want the latter.

Doing that assures that arrays remain arrays, while array-like objects are properly mapped on an array instance.

skypjack
  • 49,335
  • 19
  • 95
  • 187