Search code examples
javascriptarraysstring

Javscript Array to String (Automatic Conversion)


New to JS, so still learning lots

I came across this (See Image) on https://www.w3schools.com/js/js_array_methods.asp

It states this "JavaScript automatically converts an array to a comma separated string when a primitive value is expected."

On their own website, this works fine and they state it should return the same result (String)

But when I try it on Chrome Console, I get the following results:

const fruits = ["Banana", "Orange", "Apple", "Mango"];

console.log(fruits);

Result: (4) ['Banana', 'Orange', 'Apple', 'Mango']

0: "Banana"
1: "Orange"
2: "Apple"
3: "Mango"
length: 4

Note: This returns an Array


const fruits = ["Banana", "Orange", "Apple", "Mango"];

console.log(fruits.toString());

Result: Banana,Orange,Apple,Mango

Note: This returns a string

I someone could clarify which is the correct way, that would be much appreciated

Thanks

Array to String


Solution

  • console.log in modern browsers is a debugging tool that can display arbitrary objects and arrays for the developer to inspect. "conversion" makes non sense here, console.log just displays what it gets from you.

    you can use someArray.toString() to convert an array to a string but I would strongly advise against that. besser use .join (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join) in order to have more control about the output.

    also, MDN is a much better source of documentation for everything JS/web