Code snippets for your daily life

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

Latest Snippets

  • const words = ['will', 'rock', 'you!']
    
    // output ['will', 'rock', 'you!']
    console.log(words)
    
    // returns 4
    words.unshift('We')
    
    // output ['We', 'will', 'rock', 'you!']
    console.log(words)
    Copy

    December 5th, 2019

    # Add items to the beginning of an array

    Add to bookmarks

    unshift() adds items to the beginning of an array and returns the length of the new array.

  • const words = ['Hello', 'World', 42]
    
    // output: ['Hello', 'World', 42]
    console.log(words)
    
    // returns 42
    words.pop()
    
    // output: ['Hello', 'World']
    console.log(words)
    Copy

    December 4th, 2019

    # Remove an item from the end of an array

    Add to bookmarks

    pop() removes the last item from the original array and returns it.

  • const words = ['Ohayou', 'Gozaimasu']
    
    // output ['Ohayou', 'Gozaimasu']
    console.log(words)
    
    // returns 'Ohayou'
    words.shift()
    
    // output ['Gozaimasu']
    console.log(words)
    Copy

    December 4th, 2019

    # Remove an item from the beginning of an array

    Add to bookmarks

    shift() removes an item from the beginning of an array and returns the remove item.

  • const words = ['No', 'one', 'lives']
    
    // output: ['No', 'one', 'lives']
    console.log(words)
    
    // returns 4 <- length of the new array
    words.push('Forever!')
    
    // output: ['No', 'one', 'lives', 'Forever!']
    console.log(words)
    Copy

    December 4th, 2019

    # Add items to the end of an array

    Add to bookmarks

    push() adds items to the end of an array and returns the length of the new array.

  • const obj1 = {a: 1, b: 2}
    const obj2 = {c: 3, a: 4}
    
    // option #1: Object.assign
    const obj3 = Object.assign(obj1, obj2)
    
    // option #2: spread operator
    const obj4 = {...obj1, ...obj2}
    
    // output: { a: 4, b: 2, c: 3 }
    console.log(obj3)
    
    // output: { a: 4, b: 2, c: 3 }
    console.log(obj4)
    Copy

    December 1st, 2019

    # Clone an object

    Add to bookmarks

    Both the Spread Operator (...) and Object.assign(target, ...sources) can be used to copy an object by it's values and creates a new object without reference to the source object.

HomeBookmarks