Home > Software design >  Difference between if(x) and if(x==true) in a reactjs component
Difference between if(x) and if(x==true) in a reactjs component

Time:12-22

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>

CodePudding user response:

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:

CodePudding user response:

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
}

CodePudding user response:

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

  • Related