5 JavaScript Methods You May Not Know

July 25th, 2018

I’ve recently been doing quite a bit of vanilla JavaScript to top my skills. I’ve used some great resources from: Javascript30Treehouse and Codewars and feel like I’ve learn’t quite a bit. Especially from Codewars. Seeing how other people tackle solutions is a great way to improve.

Along the way I’ve found some handy methods that I wanted to share:

 

  1. Easily view an object in the console with console.table()
    const inventors = [
      { first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 },
      { first: 'Isaac', last: 'Newton', year: 1643, passed: 1727 },
      { first: 'Galileo', last: 'Galilei', year: 1564, passed: 1642 },
      { first: 'Marie', last: 'Curie', year: 1867, passed: 1934 },
      { first: 'Johannes', last: 'Kepler', year: 1571, passed: 1630 },
      { first: 'Nicolaus', last: 'Copernicus', year: 1473, passed: 1543 },
      { first: 'Max', last: 'Planck', year: 1858, passed: 1947 },
      { first: 'Katherine', last: 'lodgett', year: 1898, passed: 1979 },
      { first: 'Ada', last: 'Lovelace', year: 1815, passed: 1852 },
      { first: 'Sarah E.', last: 'Goode', year: 1855, passed: 1905 },
      { first: 'Lise', last: 'Meitner', year: 1878, passed: 1968 },
      { first: 'Hanna', last: 'Hammarström', year: 1829, passed: 1909 }
    ]
    
    console.table(inventors)
  2. Filling all items in an array with Array.prototype.fill()
    Array(7).fill(0)
    
    // => [0, 0, 0, 0, 0, 0, 0]
  3. Removing the white space with String.prototype.trim()
    const greeting = "   Hello world!   ";
    
    console.log(greeting.trim());
    // expected output: "Hello world!";
    
  4. Tests whether at least one element in the array passes Array.prototype.some()
    const array = [1, 2, 3, 4, 5];
    
    const even = function(element) {
      // checks whether an element is even
      return element % 2 === 0;
    };
    
    console.log(array.some(even));
    // expected output: true
    
  5. See if an item is in an array Array.prototype.includes()
    const pets = ['cat', 'dog', 'bat'];
    
    console.log(pets.includes('cat'));
    // expected output: true