Why do I get undefined values when I DO NOT use implicit return?

Hey all,
I’m trying to finish the JavaScript Arrays, Loops, Objects, Iterators practice task (found here: https://www.codecademy.com/paths/back-end-engineer-career-path/tracks/becp-22-javascript-syntax-part-ii/modules/wdcp-22-practice-javascript-syntax-arrays-loops-objects-iterators/lessons/intermediate-javascript-coding-challenge/exercises/find-my-keys).

I’ve noticed that most of the solutions for each task use implicit return. When I don’t implement implicit return I seem to always get the value of “undefined”.

This brings me to my two questions: Why am I getting undefined? Also, how can I correctly solve each task without using implicit return?

I’ve included two codebytes. In each one, I’m trying to get the index for the element that matches with “keys”.

// Here it shows "undefined" // I use curly braces const findMyKeys = (arr) => {arr.findIndex((item) => {item === 'keys'}) } // object const randomStuff = [ "credit card", "screwdriver", "receipt", "gum", "keys", "used gum", "plastic spoon", ]; console.log(findMyKeys(randomStuff));
// Here, I get a value const findMyKeys = arr => arr.findIndex(item => item === 'keys') const randomStuff = [ "credit card", "screwdriver", "receipt", "gum", "keys", "used gum", "plastic spoon", ]; console.log(findMyKeys(randomStuff));

Thank you to all who answered!

If you’re not using the implicit return, then return has to be inside the function if you want it to return something.

const findMyKeys = arr => arr.findIndex(item =>  item === 'keys');

would be the same as

const findMyKeys = (arr) => { return arr.findIndex((item) => { return item === 'keys'}) };

if you’re avoiding using any implicit return.

Also note that

const doubleIt = x => x * 2;

is the same as

const doubleIt = x => { return x * 2; };

or

function doubleIt(x) { return x * 2; }
2 Likes

Really nice explanation, thank you!