How can i put statement inside an expression?
You can't, currently. Nor, in that example, do you want to. The return value of the forEach
callback isn't used for anything.
See below the horizontal rule for your specific case, but answering the question you actually asked:
On occasion, wanting to do some statement logic and then have an overall expression take the final result of that statement logic does come up. Consequently, there's a proposal for do
expressions working its way through the JavaScript proposals process. It's only at Stage 1 of the process, and so it may not progress, or if it progresses the form of it may change, but for now it looks like this:
let x = do { // Using the `do` expression proposal
let tmp = f(); // (currently just Stage 1, do not use!)
tmp * tmp + 1
};
...where x
would get the result of that last expression within the {}
.
If you really wanted to do that now, you'd probably use an immediately-invoked arrow function:
let x = (() => {
let tmp = f();
return tmp * tmp + 1;
})();
The purpose of do
expression proposal is to make that less verbose, when you need to do.
(Please don't mistake this for my offering an opinion on do
expressions either way. I'm just noting the proposal exists and is working through the process.)
Your specific case of finding the index of an item:
In your specific case, you're looking for the Array#findIndex
function, which returns the index of the entry where the callback returns a truthy value:
const index = MyArray.findIndex(v => v.name == 'john');
(Or you might want Array#find
if you want the entry itself instead of its index.)
Note that since that uses a concise arrow function, the return value of the function is the value of the expression forming the function body. We could use a verbose one instead with an explicit return
:
const index = MyArray.findIndex(v => { return v.name == 'john'; });