What does && operator and the word variable does in the map of react native official doc example

Viewed 424

would anyone be able to advise what does word in word && '' does in example from the link below. I don't quite understand why && operator, a conditional operator is doing inside it.

I have enclosed the code extract below.

{text.split(' ').map((word) => word && '').join(' ')}

When i remove word, so that it become the following:

{text.split(' ').map((word) =>  '').join(' ')}

I could observe one pizza there before any text is type.

https://reactnative.dev/docs/handling-text-input

3 Answers

It's handling the edge case of an empty text.

"".split(" ") returns an array of one empty string:

> "".split(" ")
[ '' ]

We need to make sure word is not an empty string before returning a .

Note that empty string is a falsy value in Javascript.

Word in that context is used as an inline conditional statement to return . For Instance, in the traditional javascript code would be:

if (word) return ''

In Reactjs, You may embed expressions in JSX by wrapping them in curly braces. This includes the JavaScript logical && operator. It can be handy for conditionally including an element

So, Given the sentence or text Hello there Bob. The map function go through each word and replace the word with , the final output of the given text would be

Check and-operator-in-reactjs or dont-understand-in-this-javascript-jsx-syntax or understanding-the-use-of-and-in-a-react-component. Learn javascript logics and ref

With the && operator you are ensuring that the first second condition is run only if the word value is truthy. Empty string "" is a falsy value.

Mostly irrelevant in your case, it would help when you have an input with multiple consecutive whitspaces. If you do not use &&, then ' ' will be considered as one more character.

let text1 = "I love 0 pizza a lot   - false";
let text2 = "I love 0 pizza a lot   - false";

let newText = text1.split(' ').map((word) => word && '').join(' ');
let newText2 = text2.split(' ').map((word) => '').join(' ');

console.log(newText);
console.log(newText2);

Related