JavaScript – ES6 Cheat Sheet

Sedikit catatan dari contoh penggunaan sehari-hari code javascript dengan standard ES6,

Sedikit catatan dari contoh penggunaan sehari-hari code javascript dengan standard ES6,

Arrow Function

const sum = (a,b) => a + b;
    console.log(sum(2,6)) // prints 8

Default Parameters

function print(a = 5) {
       console.log(a)
    }
    
    print() // prints 5
    print(22) // prints 22

Let Scope

let a = 3
    if (true) {
      let a = 5
      console.log(a) // prints 5
    }
    console.log(a) // prints 3

const

// can be assigned only once
    const a = 55
    a = 44 // throws an error

Multi-line String

const names = "World"
    const message = `Hello ${names}`
    console.log(message)
    
    // prints "Hello World"

Template String

const names = "World"
    const message = `Hello ${names}`
    console.log(message)
    
    // prints "Hello World"

Exponent Operator

const byte = 2 ** 8
    
// expected result = 256
// Same as: Math.pow(2, 8)

Spread Operator

/* Ini sama dengan `array_merge($arr1,$arr2)` pada php */

    const a = [ 1, 2 ]
    const b = [ 3, 4 ]
    const c = [ ...a, ...b ]
    
    console.log(c) 
    
    // [1, 2, 3, 4]

String Includes

console.log('Dankdev'.includes('s'))
    
    // prints true
    
    console.log('Dankdev'.includes('m'))
    
    // prints false
    
    
    
    // includes() method ini case sensitive, contohnya 
    console.log('Dankdev'.includes('E'))
    
    // prints false
    
    console.log('Dankdev'.includes('D'))
    // prints true

String startsWith()

console.log('Dankedev'.includes('Da'))
    
    // prints true
    
    console.log('Dankedev'.includes('an'))
    
    // prints false

String Repeat

console.log('ha'.repeat(3))
    
    // prints "hahaha"