-3
let names = ['mdv','venkatesh','nani']

// array methhods join 

let result = names.join('-');

console.log(result); o/p  mdv-venkatesh-nani
console.log(names);  o/p  ['mdv','venkatesh','nani']

I heard that array are the reference data types in JavaScript correct me if I am wrong.

I have changed the array using the join method why is it showing to the old reference?

Why do the changes not effect names array?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • Its unclear what you are asking please can you clarify? If you need clarification on anything go to w3schools.com – SPlatten Aug 15 '19 at 13:44
  • 5
    [`join()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join) doesn't change (mutate) the array, it generates a string using the array's elements. – Titus Aug 15 '19 at 13:44
  • @SPlatten MDN is almost *always* a better JS resource than w3. – Dave Newton Aug 15 '19 at 13:47

2 Answers2

1

Some methods change the reference array and others just return the value of the change.

Join is a method that only returns the changed array without changing it.

I suggest that when using some function, read its documentation to understand these details.

Join documentation on W3Schools: https://www.w3schools.com/jsref/jsref_join.asp

0

The array method join (MDN ref) does not change the original array, it returns a string. Other methods do change the original array, such as push (MDN ref) or shift (MDN ref).

But you are correct, arrays are references. For example, consider this snippet. Try to think what the result will be before running it.

var arr1 = "john".split('');
var arr2 = arr1.reverse();
var arr3 = "jones".split('');
arr2.push(arr3);
console.log("array 1: length=" + arr1.length + " last=" + arr1.slice(-1));
console.log("array 2: length=" + arr2.length + " last=" + arr2.slice(-1));

I got the snippet from this site. Here is the explanation:

The reverse() method returns a reference to the array itself (i.e., in this case, arr1). As a result, arr2 is simply a reference to (rather than a copy of) arr1. Therefore, when anything is done to arr2 (i.e., when we invoke arr2.push(arr3);), arr1 will be affected as well since arr1 and arr2 are simply references to the same object.