Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does .join`` mean in JavaScript? [duplicate]

Tags:

javascript

I came across this code:

new Array(10).fill('1').join``;

I do not know what the meaning of the signs `` used immediately after .join is.

I thought the correct syntax would be new Array(10).fill('1').join('').

Any ideas are welcome thanks!

const data = new Array(10).fill('1').join``;
console.log(data)
like image 630
Radex Avatar asked Nov 24 '20 19:11

Radex


People also ask

What does Backtick do in JavaScript?

Backticks are an ES6 feature that allows you to create strings in JavaScript. Although backticks are mostly used for HTML or code embedding purposes, they also act similar to single and double quotes. Besides, using backticks makes it easier for string operations.

How to repeat a string in js?

JavaScript String repeat() The repeat() method returns a string with a number of copies of a string. The repeat() method returns a new string. The repeat() method does not change the original string.

What is mean by join in JavaScript?

The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

What does () => mean in JavaScript?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.


3 Answers

What you're seeing is a tagged template literal, part of the ES6 specification. That pattern is heavily used in e.g. Google's Polymer Project (now lit-element). It invokes the supplied function (or in this case method) with the supplied template literal.

In addition to being used to create a Domain-Specific Language (DSL) of sorts, it's also frequently used to reduce the byte count for Javascript answers in code golf In the case of the Google project I linked, it's used as part of a domain-specific HTML templating language.

like image 80
Jared Smith Avatar answered Oct 16 '22 00:10

Jared Smith


arr.join``; is a tagged template literal.

It applies join (or any other function) to "the content of the template literal string".

When I say "applies to the content of the template literal string" it is actually a little bit more complicated than that: all static parts of the string are put into an array as the first argument and the interpolated values as the remaining arguments.

A simple example will make it easier to understand:

var demo = (str, ...names) => {
  console.log(str);
  console.log(names);
};

var users = ['john', 'jane', 'joe'];

demo`Members: ${users[0]}, ${users[1]} and ${users[2]}.`;
// LOG: ["Members: ", ", ", " and ", "."]
// LOG: ["john", "jane", "joe"]

demo``;
// LOG: [""]
// LOG: []

The last line answers your question because arr.join``; is the same as arr.join(""); just two characters shorter which is useful when you compete in JS1K for example.

In this particular case I'm not sure that the author wanted to save a few bytes because we can shorten the initial statement as follow:

new Array(10).fill('1').join``;
new Array(10).fill(1).join``;
Array(10).fill(1).join``;
'1'.repeat(10);
'1111111111';

Is a tagged template just a glorified function call?

These two expressions may look similar but they are not:

var yy = 20;
year`19${yy}`;
year(`19${yy}`);

In the first expression we have access to the static and dynamic parts of the string: "19" and 20. In the second expression we only get the "final" string "1920".

This is useful when one wants to preserve intent yet allow complex text processing behind the scene.

We know that this is unsafe:

var sql = `SELECT * FROM users where email="${email}" AND password="${password}"`;

To mitigate the risk of SQL injection, it is not uncommon to see things like:

var sql = select('*').from('users').where('AND').eq('email', email).eq('password', password);

However it could be argued that we have traded the expressiveness of SQL with a somewhat awkward API that people are less likely to be familiar with.

If a tagged template literal has access to both static and dynamic parts of a string we can build domain-specific tagged template literals:

var sql = safe_sql`SELECT * FROM users where email="${email}" AND password="${password}"`;
like image 33
customcommander Avatar answered Oct 16 '22 01:10

customcommander


This syntax is called Tagged Template literals , Calling a function by passing backitlists.

It works that way

function taggedTemplate(str, ...exps){
   //str is an [] containg the strings in the tagged literals.
   //exps is an [] containg the expressions passes in the tagged literals
   console.log(str[0]) // "Number "
   console.log(exps[0]) // "19"
 }
taggedTemplate`Number ${19}`

So, The join method supports tagged literals, It could be something like this.

Array.prototype.join = function(arg){
  let str = typeof arg === "string" ? arg : arg[0];
  //joins the array using str
}
like image 29
Sherif Wael Avatar answered Oct 16 '22 00:10

Sherif Wael