Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

219
Visualizações
Difference between if(x) and if(x==true) in a reactjs component

When I was writing the ReactJs code below, I first used if(this.state.username==true) and did not get the result I expected. But When I used if(this.state.username) it worked as I needed. Therefore, I can obviously see that there is a difference between if(x==true) and if(x). I also know that sometimes, they can mean the same and produce the same result. My question is if my constructor is set up as below, why would the two expressions behave differently. What is the true meaning of if(this.state.username) here? Thanks for helping me understand.

  constructor(props){
    super(props)
    this.state = {username:""}
  }

The two codes are below:

class MyForm extends React.Component {
  constructor(props){
    super(props)
    this.state = {username:""}
  }
  changeName = (e) =>{
    let target = e.target;
    let name   = target.name; 
      let value  = target.value;
    this.setState ({[name]: value});
  }
  render(){
    let myHeader;
    if(this.state.username==true){
        myHeader = <h1>Hello {this.state.username}</h1>;
    }else{
        myHeader = "";
    }
    return (
      <form>
        {myHeader}
        <h1>{this.state.username}</h1>
        <p>Enter your name:</p>
        <input
          name='username'
          type="text"
          onChange = {this.changeName}
        />
      </form>
    );
  }
}   
ReactDOM.render(<MyForm />, document.getElementById('root'));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>


<div id="root"></div>

And

class MyForm extends React.Component {
  constructor(props){
    super(props)
    this.state = {username:""}
  }
  changeName = (e) =>{
    let target = e.target;
    let name   = target.name; 
      let value  = target.value;
    this.setState ({[name]: value});
  }
  render(){
    let myHeader;
    if(this.state.username){
        myHeader = <h1>Hello {this.state.username}</h1>;
    }else{
        myHeader = "";
    }
    return (
      <form>
        {myHeader}
        <h1>{this.state.username}</h1>
        <p>Enter your name:</p>
        <input
          name='username'
          type="text"
          onChange = {this.changeName}
        />
      </form>
    );
  }
}   
ReactDOM.render(<MyForm />, document.getElementById('root'));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>


<div id="root"></div>

over 4 years ago · Santiago Trujillo
4 Respostas
Responde à pergunta

0

if (expr) would be considered true if the expr is "truthy".

'<str>' == true expression would be considered true if <str> equals '1'.

In your case it probably makes more sense to do

if (this.state.username !== '') {

References:

  • https://tc39.es/ecma262/#sec-equality-operators
  • https://tc39.es/ecma262/#sec-islooselyequal
over 4 years ago · Santiago Trujillo Relatório

0

There's a difference between using if(this.state.username==true) and if(this.state.username). Using the former compares the value of this.state.username with true, which of course is false unless it returns a string value of 1, in which case it will return true.
However, doing the latter casts this.state.username to boolean and checks if this.state.username has a value (like not undefined).
So if you want to use if(this.state.username==true), you will have to cast this.state.username to boolean first by using !! (or Boolean):

if(!!this.state.username==true) {
  // your code goes here
}
over 4 years ago · Santiago Trujillo Relatório

0

data type username is not boolean but string, string validation using !== ''

over 4 years ago · Santiago Trujillo Relatório

0

Haha, that is so funny. I've tried it with all truthies and falsies. Lets's see the result:

console.log('Truthies:')
console.log('"a" == true           returns:', "a" == true)
console.log('"1" == true           returns:', "1" == true)
console.log('1 == true             returns:', 1 == true)
console.log('3 == true             returns:', 3 == true)
console.log('-1 == true            returns:', -1 == true)
console.log('[] == true            returns:', [] == true)
console.log('{} == true            returns:', {} == true)
console.log('function a(){return true} == true    returns:', function
a(){return true} == true)
console.log('"true" == true        returns:', "true" == true)

console.log('')
console.log('Falsies:')
console.log('NaN == false          returns:', NaN == false)
console.log('"" == false           returns:', "" == false)
console.log('`` == false           returns:', `` == false)
console.log('0 == false            returns:', 0 == false)
console.log('undefined == false    returns:', undefined == false)
console.log('null == false         returns:', null == false)


console.log('')
console.log('Truthies not-equal false:')
console.log('"a" !== false           returns:', "a" !== false)
console.log('1 !== false             returns:', 1 !== false)
console.log('"1" !== false           returns:', "1" !== false)
console.log('3 !== false             returns:', 3 !== false)
console.log('-1 !== false            returns:', -1 !== false)
console.log('[] !== false            returns:', [] !== false)
console.log('{} !== false            returns:', {} !== false)
console.log('function a(){return true} !== false     returns:', function
a(){return true} !== false)
console.log('"true" !== false         returns:', "true" !== false)

console.log('')
console.log('Truthies not-equal true:')
console.log('"a" !== true           returns:', "a" !== true)
console.log('1 !== true             returns:', 1 !== true)
console.log('"1" !== true           returns:', "1" !== true)
console.log('3 !== true             returns:', 3 !== true)
console.log('-1 !== true            returns:', -1 !== true)
console.log('[] !== true            returns:', [] !== true)
console.log('{} !== true            returns:', {} !== true)
console.log('function a(){return true} !== true     returns:', function
a(){return true} !== false)
console.log('"true" !== true         returns:', "true" !== true)

There are some tricky things. E.g. both 1 == true and 1 !== true are true 😆.

Anyways... you'd better to use !! to stay on the safe side:

const { useState } = React

const MyForm = () => {
  const [state, setState] = useState({ username: '' })

  const handleChange = ({ target: { name, value } }) => {
    setState({ [name]: value })
  }
  
  return (
    <form>
      {!!state.username && (
        <h1>Hello {state.username}</h1>
      )}
      <p>Enter your name:</p>
      <input
        name="username"
        type="text"
        onChange={handleChange}
      />
    </form>
  )
}

ReactDOM.render(<MyForm />, document.getElementById('root'));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>


<div id="root"></div>

And you can use hooks, functional component, inline jsx operators and deconstruction for simplicity.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda