Oba Api
Oba Api

Reputation: 261

When to use Boolean(var1)?

In the redux tutorial it says:

const canSave = Boolean(title) && Boolean(content) && Boolean(userId)
const canSave = title && content && userId

Upvotes: 0

Views: 76

Answers (4)

Lin Du
Lin Du

Reputation: 102237

If you use TypeScript with title && content && userId expression, the expression evaluation is a string, the TSC will throw a type mismatch error, see below example:

import React, { useState } from 'react';

export default function Test() {
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [userId, setUserId] = useState('');

  return <button disabled={title && content && userId}>click me</button>;
}

Error:

Type 'string' is not assignable to type 'boolean'.ts(2322) index.d.ts(2054, 9): The expected type comes from property 'disabled' which is declared here on type 'DetailedHTMLProps<ButtonHTMLAttributes, HTMLButtonElement>'

So you need to convert the string to boolean. From the doc Boolean

Do not use a Boolean object to convert a non-boolean value to a boolean value. To perform this task, instead, use Boolean as a function, or a double NOT operator:

var x = Boolean(expression);     // use this...
var x = !!(expression);          // ...or this

So the code should be:

const canSave = Boolean(title) && Boolean(content) && Boolean(userId);
// or
const canSave = !!title && !!content && !!userId;

Both of them are ok.

Upvotes: 1

Aminadav Glickshtein
Aminadav Glickshtein

Reputation: 24590

Instead of using Boolean, you can always use this shortcut instead:

const canSave = !!(title && content && userId)

But !! will convert it to Boolean.

Think for example you need to pass boolean from your server to client, and you don't wish to string string.

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370699

Having to convert to Boolean explicitly would be needed in the (probably slightly unusual) case that the result is checked not for truthyness or falseyness, but against another boolean. To illustrate, the following's logic fails:

const title = '';
const content = 'content';
const userId = 'foo';

const canSave = title && content && userId;
if (canSave === false) {
  console.log('cant save');
  throw new Error();
}
console.log('saving...');

Converting canSave to boolean will fix that.

But a more DRY approach would be to call Boolean on the whole result, instead of on every individual expression.

const canSave = Boolean(title && content && userId);

But userId = 0 would then convert to false

Not sure what you're getting at. If that's an issue, maybe the logic you'd want is typeof userId === 'number'?

Upvotes: 0

Ali
Ali

Reputation: 458

yes you can but imagine you get strange result for some values for title. Imagine someone put false in their title or content. Not sure about userId though

Upvotes: 0

Related Questions