Is this approach correct for sending a request JS?

Viewed 92

Based on boolean value condition it should send that message to backend. Currently I made it like this:

async submit() {
...   

 await api.submitProduct (
              productId,
              product.instock.unlimited == false ? 'book' : 'ebook'
              )

So it should check product's instock proper contains unlimited value which is false than it should submit 'book' else ebook. Is this the correct approach? The question is related to the following line:

 product.instock.unlimited == false ? 'ebook' : 'book'
3 Answers

The answer depends on the condition you need to apply.

The abstract equality operator does not enforce type checking and is therefore not a best practise. Infact, you can make do without == in almost any situation.

See the difference between the two equality operators on MDN.

In example below, if you are looking to send false when your value is infact of type boolean and false, then you can use strict equality operator

value === false ? 'first' : 'second';

However, if you are looking for 'second' for any falsy value then the check could easily be changed to

value ? 'false' : 'second';

Note that the following are all falsy values in js.

"" (Empty string)
0 (Number 0)
undefined
null
false

As I initially pointed out, you're using == which will not specifically check the type, and so items that have a value of undefined, which is a "falsy" value, will end up being assigned to the book category. That's because the double equals operator coerces the operands if their types are not the same.

Using === will prevent that from occurring, as only items that specifically have a boolean value of false will meet the test criteria. It's generally a best practice to use === to avoid these kinds of scenarios.

product.instock.unlimited === false ? 'book' : 'ebook'

You are confused with the use of ===, this one checks the type and the value at the same time so you don't need to use a big function to check if the var is false or undefined but a right operator ===.

const test = (value) => value === false ? 'book' : 'ebook'

// test with false, return book
console.log(test(false))

// test with undefined, return ebook
console.log(test(undefined))

Related