Code snippets for your daily life

Find useful snippets, bookmark and share them with other developers.

Latest Snippets

  • const transformer = {
      fraction: 'Autobots',
      hasOwnProperty() {
        return 'Decepticons!';
      },
    };
    
    // output: 'Decepticons'
    console.log(transformer.hasOwnProperty('fraction'));
    // output: true
    console.log(Object.hasOwn(transformer, 'hasOwnProperty'));
    Copy

    August 5th, 2022

    # Check if an object has a specific property

    Add to bookmarks

    A safe way to check if an object has a specific property, is to use Object.hasOwn. It is possible to do the same with Object.prototype.hasOwnProperty, but the problem is, that the object could have it's own proerty named hasOwnProperty.

  • const decepticons = ['Megatron', 'Starscream', 'Blitzwing'];
    const lastDecepticon = decepticons.at(-1);
    console.log(lastDecepticon); // output: 'Blitzwing'
    Copy

    August 4th, 2022

    # Negative indexing of arrays

    Add to bookmarks

    To get the last item of an array, we had to write array[array.length-1]. A shorter way is to use the at() method.

  • class Transformer {
      #transform() {
        console.log('Fancy sound! 🎶');
      }
    
      canTransform() {
        return #transform in this;
      }
    }
    
    const optimusPrime = new Transformer();
    console.log(optimusPrime.canTransform()); // true
    Copy

    August 3rd, 2022

    # Private attribute check

    Add to bookmarks

    We can use the in operator to check if an object has a given private property.

  • class transformer {
      name: 'Optimus Prime';
      #previousName: 'Orion Pax'; // private attribute
    
      rollOut() {
        //...
      }
    
      // private method
      #transform() {
        //...
      }
    }
    Copy

    August 2nd, 2022

    # Private class attributes and methods

    Add to bookmarks

    Until now, the convention was to use the _ for private attributes and methods. However, this had not been able to prevent the abuse.

    To declare a private attribute or method, just put a # in front of it.

  • class Autobot {
      name = 'Optimus Prime';
      fraction = 'Autobots';
    }
    
    const transformer = new Autobot();
    
    // output: I am Optimus Prime and leader of the Autobots!
    console.log(`I am ${transformer.name} and leader of the ${transformer.fraction}!`);
    Copy

    August 1st, 2022

    # Class attribute declaration

    Add to bookmarks

    In object-oriented programming, class attributes are often declared in the constructors. In JS, no constructor is needed.

HomeBookmarks