Why does a trailing template literal execute a function? [duplicate] - javascript

This question already has answers here:
Difference between Template literals and Tagged template literals?
(2 answers)
Closed 5 years ago.
Came across this javascript riddle on Twitter today: https://twitter.com/bradleymeck/status/890795540123865088
// #js
const a = f => f``;
const b = f => f``;
console.log(a(_ => _) === b(_ => _));
// what do you think this will/may print
At first glance it actually seems to make some decent sense. a is a function that takes some input f and then does f``. What f`` is a complete mystery to me so I tossed it into the console and received this input.
(()=>{console.log('hi')})``
hi
So it seems that a trailing template literal executes its preceding function. I understand that template literals are code that is executed immediately, but this behavior makes no sense to me. Can someone explain this to me?

Maybe this piece of code can help you:
var test1 = 2;
var test2 = 3;
function fTest(strings, ...params){
strings.forEach((x) => console.log(`string param: ${x}`));
params.forEach((x, index) => console.log(`param ${index}: ${x}`));
}
const a = (f, param1, param2) => f`tagged ${param1} template ${param2} literals`;
a(fTest, test1, test2);
That mistery is a tagged template literal:
essentially you're passing a template literals to your function, which will interpret the place holders as parameters, as well as the strings between them.
You can read here the documentation.
Another thing: if you want to ignore escape sequences you can use the raw function on the strings (see the example).

Related

On arrow function bodies, whats the difference between using brackets, placing direclty the condition, or using pharentesis? [duplicate]

This question already has answers here:
When do we have to use () and {} in ES6 Arrow Functions
(2 answers)
Arrow function without curly braces
(9 answers)
Curly Brackets in Arrow Functions
(3 answers)
What does the comma operator do in JavaScript?
(5 answers)
Closed 2 months ago.
In my years of JS development I've seen the following examples:
let a = () => console.log("a");
let b = () => { console.log("b"); }
let c = () => (console.log("c"));
I know the difference between the first two options, but the last one always seem'd a little off to me. I've also tried to do the following, which surprisingly works:
let c = () => (console.log("c1"), console.log("c2")); // Outputs both console logs.
And also this:
let c = () => (1, 2, 3, 4 ,5);
let x = c(); // 5
I've searched about this way of defining function bodies, yet I'm not satisfied with what I have found since every example I've stumbled on was poorly explained.
Can anyone please explain to me a bit more in-depth the difference between the three examples, and also what's special about the last one?
Thanks in advance.
let c = () => (console.log("c"))
I know the difference between the first two options, but the last one always seem'd a little off to me.
Arrow syntax allows you to return the value of the expression directly without having to enclose in curly braces and using a return statement. In the example above, enclosing the value (returned by console.log) in brackets does not change its value.
And also this:
let c = () => (1, 2, 3, 4, 5);
What you are seeing is the comma operator in action. It will return the value of the last operand, which is why c returns 5.
I've also tried to do the following, which surprisingly works:
let c = () => (console.log("c1"), console.log("c2")); // Outputs both console log
In this case, both expressions are evaluated, and thus both strings are logged. However, the expression yields a value of undefined, since console.log returns undefined.
First of all, you're talking specifically about arrow (=>) functions. Traditional functions must have a body enclosed in { }.
An arrow function can have a traditional body enclosed in { }. It can also have a single expression as its body, in which case the result of evaluating the expression is implicitly the return value. Given that, note that any expression in JavaScript in any context can be enclosed in parentheses ( ) and the value is the same as the enclosed expression.
The comma effect is the operator in the JavaScript expression grammar ,, which allows disparate expressions to be chained together into a list that, syntactically, is still a single expression. The comma operator is useful sometimes because expressions can have side-effects; for example, a function call is an expression, and a function call may do almost anything. The value of a list of expressions in a comma operator list is the value of the last one of the expressions after evaluation.

Turn a string into function in JS [duplicate]

This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed 2 years ago.
My problem is simple and I couldn't find the proper answer in this forum. My bad...
I want to do that :
const dataReceived = foo;
foo(state);
How can I do that?
I read it is better to avoid eval, and I couldn't get success with new Function.
Thanks for your help!
EDIT
Thanks for your answers.
I work with React.
In my reducer, I have a create_item case.
I can reach action.category, that can be the word 'currency' or 'country'.
What I want to do is to launch either the method createCurrency or createCountry according what is inside action.category.
That's why I tried to join 'create' and 'action.category' to create a dynamic function name.
But it seems to be a poor idea...
The simplest approach is to create an object which contains an entry where:
the key is a string
the value is a function.
Example:
const myObject = {
myFunction: () => { [... DO SOMETHING...] }
}
Subsequently you will be able to invoke the function, using:
myObject.myFunction();
The above becomes more powerful when you use brackets notation.
Example:
const myString = 'myFunction';
myObject[myString]();

What is the different of using =, =>, : in react? [duplicate]

This question already has an answer here:
What does this symbol mean in JavaScript?
(1 answer)
Closed 3 years ago.
I'm a bit new to react. I can use them with my past experiences. For example, I need sth to describe, I found a similar declaration and use the same shape. But I would like to learn the fundamentals. I mean when should I use below operators;
const sth : ...
() => ...
const sth = ...
If you list the basis of these usages, I would add on them with docs.
Those are fundamentals of Javascript and Typescript (or any type definition with js) and not React, please refer to A re-introduction to JavaScript (JS tutorial) in MDN docs.
Arrow function
(param1, param2, …, paramN) => { statements } // const sth = () => ...
Assignment operator
const sth = ...
Typescript type or any kind of type definition like flow
let isDone: boolean = false;

Javascript: Create dictionary from array of strings [duplicate]

This question already has answers here:
ECMAScript 6 arrow function that returns an object
(6 answers)
Closed 3 years ago.
I have an array of strings that I get from an endpoint and I need to convert it to key-value pairs for the frontend to display them correctly. I have tried different concepts such as reduce and map but have not been able to get it working successfully. I assume it might be one-liner for someone familiar with FE but has taken forever for a BE person like me.
Here is what I have tried:
var input = ['quiz1', 'quiz2'];
const mapping = input.map(x => {"id":x, "label":x};);
console.log(mapping);
I am expecting an output of the format
[{"id":"quiz1", "label":"quiz1"}, {"id":"quiz2", "label":"quiz2"}]
Thanks for looking!
It's simply two syntax errors:
var input = ['quiz1', 'quiz2'];
const mapping = input.map(x => ({"id":x, "label":x}));
console.log(mapping);
Firstly, no semicolon in a un-braced arrow function body.
This is invalid: (() => 3;). This is valid: (() => 3).
Secondly, wrap return obj in ().
This is invalid: () => {x: 3}. This is valid: () => ({x: 3}).

Double parentheses But not IIFE or closures,What is it? is it Valid JS syntax? [duplicate]

This question already has answers here:
Why does babel rewrite imported function call to (0, fn)(...)?
(3 answers)
Closed 4 years ago.
i was trying to learn and understand KnexJS source Code, until i came to a block of code which i don't have any idea what is it.
config = (0, _lodash.assign)({}, config, {
connection: (0, _parseConnection2.default)(config.connection).connection
});
in Simplified version
config = (0, Args1)({}, config, {Args2});
what makes me confused is that,there is no 'function' keywords or any 'identifier' before the parentheses...
i have found same but not similiar question here: double parentheses and that is understandable and different...is it Valid JS? if Yes, what it's mean?
It's the comma operator (evaluates a comma-separated list of expressions, resolving to the value of the last expression), combined with a call of _lodash.assign with a global calling context, rather than a calling context of _lodash. Here's a simpler example:
const obj = {
abc: function(arg) {
console.log(this);
console.log('abc called with ' + arg);
}
}
obj.abc('foo');
(0, obj.abc)('foo')
As you can see, calling obj.abc alone results in the calling context being obj, while (0, obj.abc)('foo') results in the calling context being window. I think it's a minification technique - saner, more understandable code would look like
obj.abc.call(window, 'foo')
or
const theFn = obj.abc;
theFn('foo')

Categories