edin-m
edin-m

Reputation: 3121

How to use named Array element in javascript?

['a', 'b', 'c'].join([separator = ','])

results in "a,b,c"

[separator=',']

is obviously valid.

How can I create myjoin that uses myseparator as some kind of parameter. How can one use this named array parameter, how to access it and where it can be usable?

My primary intention isn't really crating myseparator but trying to understand this construction since I didn't bump into it before.

Sorry if duplicating question, I just haven't found any other resource.

Upvotes: 1

Views: 96

Answers (3)

Pointy
Pointy

Reputation: 413720

Your statement is syntactically correct, but it's achieving its result in a weird way.

The .join() method does take an argument, and the argument is expected to be a string. If it's not a string, it's coerced to a string by normal means. In your code, the array [separator=','] when converted from an array will be the string ",".

The equivalent (less weird) way to do the join would be

['a', 'b', 'c'].join(",");

Note that the embedded assignment to the variable separator is a side effect that does not have anything to do with the behavior of the .join() function. The fact that that assignment took place before the function call (to .join()) is undetectable by that function.

edit — the MDN documentation for the .join() method describes it like this:

str = arr.join([separator = ','])

That's an unfortunately confusing notational convention used throughout the MDN documentation. The bracketed separator = ',' is a meta-syntactic convention meaning that the function accepts one optional argument. The fact that it's optional is indicated by the square brackets.

Upvotes: 7

Andy
Andy

Reputation: 63524

var arr = ['a', 'b', 'c'];

function myJoin(arr, sep) {
  return arr.join(sep);
}

myJoin(arr, '-'); // "a-b-c"
myJoin(arr, '**'); // "a**b**c"

DEMO

Upvotes: 1

KJ Price
KJ Price

Reputation: 5964

I'm not entirely sure what you are trying to do, but I think you are trying to define the separator before you hit the join method. Does this look like it?

var separator = ',';
['a', 'b', 'c'].join(separator);

Upvotes: 5

Related Questions