!! operator double negation in typecsript and vue components
Code

!! operator in vue components

!! operator (double negation) transforms values into boolean values. This ’!!’ operator converts any value to TRUE if it’s „truthy„, meaning it’s not a falsy value (such as false, 0, empty value, null, undefined, NaN), otherwise it converts to FALSE.

!! operator examples :

For example, if you have a variable myVar, and you want to check if it’s „truthy” or „falsy”, you can do it using the !! operator like this:

let myVar = "Howdy";

let isTruthy = !!myVar;

console.log(isTruthy); // Output: true


Another example is when the !! operator helps to validate any optional variables. Somethimes we really have no idea what we will get, this can vent some issues if we need to check for a truthy or falsy condition.

<template>
  <div>
    <h2>List of Beers</h2>
    <ul>
      <li v-for="(beer, index) in beers" :key="index">
        {{ !!beer.name }} - {{ !!beer.type }} - Has Name: {{ !!beer.name }}      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      beers: [
        { name: 'Stella Artois', type: 'Lager' },
        { name: 'Guinness', type: 'Stout' },
        { name: 'IPA', type: 'India Pale Ale' },
        { name: 'Heineken', type: 'Pale Lager' },
        { name: 'Blue Moon', type: 'Belgian White' }
      ]
    };
  }
};
</script>

<style scoped>
</style>

The double negation operator (!!) is used to convert the value of beer.name into a boolean. If beer.name is truthy, the result will be true, otherwise, it will be false.

Piotr Kowalski