0

i am a new learner on javascript language but i have worked before with other programming language such c#

while i was doing a simple operation on javascript, i was astonished about the results makes me wonder how javascript works and why it is different like that

Example i had an array of ['a','b'] , i want to reverse it and check is it the same or not

var char = ['a','b'];

var char_reversed = char.reverse();

normally , char should = ['a','b'] and char_revered should = ['b','a']

but i find that char = char_reversed = ['b','a']

Community
  • 1
  • 1
  • 1
    [`reverse()` works in-place](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse), what's so hard to understand? – Marty Jul 23 '17 at 23:40

4 Answers4

0

The reverse function works in place, therefore the original array is modified.

If you do not want to modify the original list, you can refer to the following post.

https://stackoverflow.com/a/30610528/759762

RMT
  • 7,040
  • 4
  • 25
  • 37
0

The reason this works is that char.reverse() operates on the array char. It does not perform the operation and returns a copy of the array, but changes the array itself. The operation var char_reversed = char.reverse() actually is:

char.reverse() // ['b','a']
char_reversed = char

That is why char = char_reversed = ['b','a']

PressingOnAlways
  • 11,948
  • 6
  • 32
  • 59
  • is this methodology of operating on the variable itself not creating a copy, exist on other methods or is it just the arrays which perform this way – Ahmed Ibrahim Jul 24 '17 at 01:20
0

.reverse() modifies original array.

You can call .slice() first to create a copy of the original array if you are expecting a new array where the elements are literal strings.

var char = ['a','b'];

var char_reversed = char.slice(0).reverse();

console.log(char, char_reversed);
guest271314
  • 1
  • 15
  • 104
  • 177
0

In JavaScript some methods don't create new reference of your data. It's change your your data within the own memory. For example,

var a = [1, 2, 3];
a.reverse();
console.log (a); // a looks like [3, 2, 1]

a.pop();
console.log (a); // a looks like [3, 2] data changes within the memory. 

console.log (a.slice(0, 1)); // output looks like [3]

console.log (a); // a looks like [3, 2]

In slice method that create new memory of your data and modified your new data. So your old data don't change or modified.

Vasi
  • 1,147
  • 9
  • 16