DEV Community

Caner Demirci
Caner Demirci

Posted on

if (!var) - What does it mean exactly? Let's Explore with TypeScript

if (!variable) What does it mean exactly? I think there's no need to explain much about this. This piece of code show us enough.

const nameof = (n: any) : string => Object.keys({n})[0];

const valueOrType = (n: any) : any => {
  if (n === undefined)
    return 'undefined';

  if (n === null)
    return 'null';

  if (n === '')
    return 'empty string';
}

const isFalsy = (n: any) : boolean => !n ? true : false;
const logInputIsFalsy = (inp: any) => console.log(`[${nameof(inp)}] - value : [${valueOrType(inp)}] - is ${isFalsy(inp) ? 'falsy' : 'not falsy'}`);

logInputIsFalsy('');
logInputIsFalsy(null);
logInputIsFalsy(undefined);
logInputIsFalsy(false);
logInputIsFalsy(0);
logInputIsFalsy('word');
logInputIsFalsy(1);
Enter fullscreen mode Exit fullscreen mode

Console outputs:

  • "[n] - value : [empty string] - is falsy"
  • "[n] - value : [null] - is falsy"
  • "[n] - value : [undefined] - is falsy"
  • "[n] - value : [false] - is falsy"
  • "[n] - value : [0] - is falsy"
  • "[n] - value : [word] - is not falsy"
  • "[n] - value : [1] - is not falsy"

Top comments (0)