0

I am following react native docs and I came across this code which converts words to . I tried to modify the code line {text.split(' ').map((word) => word && '').join(' ')} to {text.split(' ').map((word) =>'').join(' ')} (I removed "word &&" ) and it is working exactly same. My doubt is why we need what is the functionality of word && ''. I know "&&" is conditional and, but I am not getting its purpose

import React, { useState } from 'react';
import { Text, TextInput, View } from 'react-native';

const PizzaTranslator = () => {
  const [text, setText] = useState('helloworld');
  return (
    <View style={{padding: 10}}>
      <TextInput
        style={{height: 80}}
        placeholder="Type here to translate!"
        onChangeText={(text) =>{ setText(text)}}
        defaultValue={text}
      />
      <Text style={{padding: 10, fontSize: 42}}>
        {text.split(' ').map((word) => word && '').join(' ')}
      </Text>
    </View>
  );
}

export default PizzaTranslator;
  • 4
    Does this answer your question? [What's the difference between & and && in JavaScript?](https://stackoverflow.com/questions/7310109/whats-the-difference-between-and-in-javascript). Specifically check the part about `&& short-circuiting` in the [current top answer](https://stackoverflow.com/a/7310120/5389131) – Søren D. Ptæus Apr 14 '21 at 07:28

1 Answers1

5

It's there to avoid translating double spaces into an extraneous pizza (since the empty string is falsy).

>>> "hello world".split(' ').map((word) => word && '').join(' ')
" "
>>> "hello    world".split(' ').map((word) => word && '').join(' ')
"    "
>>> "hello    world".split(' ').map((word) => '').join(' ')
"    "
AKX
  • 152,115
  • 15
  • 115
  • 172
  • Which is a bit weird, since it's just wrong splitting in that case: `sentence.split/ +/)` (one or more spaces) or `.split(/\s+/)` (one or more of any whitespace) will clean up multiple spaces just fine. Instead the `.map()` operation is abused to do (semi-)filtering alongside the mapping. Only, it's not really filtering, since the elements are left around, it's `join()` that will clean up all the empty strings in the end. – VLAZ Apr 14 '21 at 08:28
  • @VLAZ I think this is to avoid introducing intimidating new syntax (regexps) to people who don't know about them. Yep, it's weird, but it works. – AKX Apr 14 '21 at 09:05
  • Instead it's introducing new syntax (short-circuit evaluation) that they have to ask on SO about and then introduces bad practices ¯\\_(ツ)_/¯ IMO, the tutorial should have either just not done this at all or just sprinkled magic and said "`.split(/ +/)` is how you split words. Just take it on faith" so you have the correct incantation in your spellbook to make a sentence into words. – VLAZ Apr 14 '21 at 09:11
  • @VLAZ I agree it's not the best... but luckily it's fixable! https://github.com/facebook/react-native-website/blob/master/docs/handling-text-input.md – AKX Apr 14 '21 at 10:01