3

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

lonelearner
  • 1,637
  • 4
  • 14
  • 22
  • 1
    `(word) => word && ''` is the same as `(word) => { if (word) return ''; }` – James Jul 28 '21 at 18:05
  • 1
    Duplicate of [What is “x && foo()”?](/q/6970346/4642212). See [What does this symbol mean in JavaScript?](/q/9549780/4642212) and the documentation on MDN about [expressions and operators](//developer.mozilla.org/docs/Web/JavaScript/Reference/Operators) and [statements](//developer.mozilla.org/docs/Web/JavaScript/Reference/Statements). – Sebastian Simon Jul 29 '21 at 03:35

3 Answers3

3

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.

Nima
  • 112
  • 1
  • 2
  • 12
1

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

Akolade Adesanmi
  • 1,152
  • 11
  • 15
0

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);
Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39