Home > front end >  When to use Boolean(var1)?
When to use Boolean(var1)?

Time:12-30

In the redux tutorial it says:

const canSave = Boolean(title) && Boolean(content) && Boolean(userId)
  • But userId = 0 would then convert to false
  • Can't you just use the following?
const canSave = title && content && userId

CodePudding user response:

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

CodePudding user response:

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'?

CodePudding user response:

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.

CodePudding user response:

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.

  • Related