Anurag Mishra
Anurag Mishra

Reputation: 699

my If Else condition not working properly in React.js

I am saving a record on button click but it always throwing an error.

I am including an if else condition. I have surpassed all the conditions but still my code is going to the if condition but It should not go to if condition.

code is -

my this.state.question.options value is -

[
    {
        id:3250,
        label:'good answer',
        assert:1
        position:1
    },
    {
        id:3249,
        label:'bad answer',
        assert:0
        position:2
    }
]

and I am checking if else condition as -

if (this.state.question.options.filter(o => o.assert === true).length <= 0) {
    hasError = true
    errorKey = 'add-question-modal-missing-assert-options'
}
else {
    alert("test");
}

my code should goto else part and print test as alert but it is going to if part and showing error. Why ?

I wanna show else part i.e test as alert

Upvotes: 0

Views: 1555

Answers (5)

Dostonbek Oripjonov
Dostonbek Oripjonov

Reputation: 1674

Do u want this kind of code

if (this.state.question.options.length <= 0) {
    assert = true;
    hasError = true;
    errorKey = 'add-question-modal-missing-assert-options'
}
else {
    alert("test");
}

Upvotes: 0

Jaisa Ram
Jaisa Ram

Reputation: 1767

this.state.question.options value is -

[
    {
        id:3250,
        label:'good answer',
        assert:1,
        position:1
    },
    {
        id:3249,
        label:'bad answer',
        assert:0,
        position:2
    }
]

and then

if (this.state.question.options.filter(o => o.assert == true)).length <= 0) {
    hasError = true
    errorKey = 'add-question-modal-missing-assert-options'
} else {
    alert("test");
}

replace === strict type with ==

Upvotes: 0

Yann Bertrand
Yann Bertrand

Reputation: 3114

In JavaScript, 1 is not strictly equal to true. However, it is a good practice to use the strict equality operator ===.

You should compare o.assert with the real possible value o.assert === 1.

In terms of readability I would also consider comparing the length to 1 instead of 0:

this.state.question.options.filter(option => option.assert === 1).length < 1

Upvotes: 0

Leander
Leander

Reputation: 148

You are using the strict comparison operator (===) while comparing 2 different values. In your example, 1 is being parsed as an integer, while true is being parsed as a boolean. A strict comparison operator is used to check 2 values on equal values AND equal types.

To fix the error in your code, use a loose comparison (==) or convert the integer to a boolean by using !!1

Upvotes: 2

Javad Khodadadi
Javad Khodadadi

Reputation: 408

if (this.state.question.options.filter((el) => {return !!el.assert}).length <= 0) {
    hasError = true
    errorKey = 'add-question-modal-missing-assert-options'
}
else {
    alert("test");
}

Upvotes: 0

Related Questions