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)
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.
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.
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.
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.
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.
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';
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}"`;
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With