I came across the following code which is very simple as it's meant to determine whether a variable is a string or not.
const is_string = value => {
return typeof value() === 'string';
};
let example = 'Hello, world!';
console.log(is_string(() => example)); // true
My confusion is related to the use of the input parameter. Specifically the second line with the parenthesis after the parameter: value()
and the way the function is invoked: is_string(() => example)
. The later looks like an arrow function in itself.
I rewrote the code like
const is_string = (value) => {
return typeof value === 'string';
};
let example = 'Hello, world!';
console.log(is_string(example)); // true
and it does pretty much the same, so what is the real difference/advantage of using the notation of the first code? Is it useful in specific cases?
Thanks in advance.
EDITION:
The key word in this discussion is the Lambda expression. I was not fully aware the code was passing a function as the input parameter, I wasn't familiar with that notation.
In the first case you’re passing a function and evaluating whether the return value of that function is a string.
In the latter case you’re testing the argument itself.
As presented in your examples, where it’s just an arrow function that returns a variable you already have, there’s no point in turning it into an arrow function and doing so incurs a (tiny) bit of memory and performance overhead. Passing the value directly is unquestionably the better approach.