2

Hey first time poster/user, I have been working through some coding exercises. I wrote a piece of code that passed tests but I am unsure if this is best practice

In this sample I am iterating over an array using the filter function. I am using a call back function that will return words with length greater than 5.

sample code

const words = ['unique', 'uncanny', 'pique', 'oxymoron', 'guise'];

const interestingWords = words.filter(word => {
    return word ? word.length > 5 : null
})

In my head if the condition isn't met it shouldn't even try to return. What is happening when I return a null? or is this a case where I wouldn't use ternary at all.

The best I got was from MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null

The value null is written with a literal: null. null is not an identifier for a property of the global object, like undefined can be. Instead, null expresses a lack of identification, indicating that a variable points to no object. In APIs, null is often retrieved in a place where an object can be expected but no object is relevant.

So should I refrain from returning a null in this context?

1
  • words.filter(word=>word.length>5); Commented Jul 12, 2021 at 1:03

2 Answers 2

3

All .filter's callback cares about is the truthy or falsey value returned inside it. Here, it'd be better to return that comparison directly, no conditional operator needed:

const interestingWords = words.filter(word => word.length > 5);

A construction like

return word ? word.length > 5 : null

could make sense if you needed to check a sub-property, but only if the array element existed first, eg:

const objects = [
  null,
  { word: 'foo' },
  { word: 'barbar' },
  null
];

const interestingObjects = objects.filter(
  obj => obj ? obj.word.length > 5 : null
);
console.log(interestingObjects);

Sign up to request clarification or add additional context in comments.

Comments

1

If elements of the array might be null or undefined, you can use the optional chaining operator.

const interestingWords = words.filter(word => {
    return word?.length > 5
})

1 Comment

You know I have seen chaining in SWIFT before. Its something I need to get more familiar with thanks for your feedback

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.