This is the 9th day of my participation in the August More Text Challenge. For details, see:August is more challenging

Don’t bullshit… On dry goods.

  • let/const

ES2015(ES6) adds two important JavaScript keywords: let and const.

Variables declared by a let are valid only within the block of code in which the let command resides.

Const declares a read-only constant. Once declared, the value of the constant cannot be changed.

  • Object.assign()

We can use object.assign () to operate on or merge two or more objects.

var obj1 = { a: 1.b: 2 }; 
var obj2 = { c: 3.d: 4 }; 
var obj3 = { e: 5.f: 6 };
		 
// ES5
for (var k in obj2) {
    obj1[k] = obj2[k]
}
		
for (var k in obj3) {
    obj1[k] = obj3[k]
}
		
// ES6
Object.assign(obj1, obj2, obj3)
		
// result
obj1 = { a: 1.b: 2.c: 3.d: 4.e: 5.f: 6 }
Copy the code
  • Template string

A template string is an enhanced version of a string and is enclosed in backquotes. It can be used as a normal string, to define multi-line strings, or to embed variables in strings.

// Traditional template splicing
var temp = ' ';
for (let i = 0; i < 5; i++) {
	temp += '<div>' + 
			'<p>' + i + '</p>' + 
		'</div>'
}
document.getElementById("main").innerHTML = temp;

// ES6 template a string
var temp = ' ';
for (let i = 0; i < 5; i++) {
	temp += `<div>
			<p> ${i} </p> 
		</div>`
}
document.getElementById("main").innerHTML = temp;
Copy the code
  • Arrow function

This binding is a common source of errors in JS programs, especially when it is easy to control the value of this within a function, often leading to unexpected behavior.

Arrow function implementation:

arr.map(item= > {
    console.log(item)
})
Copy the code
  • The default parameters
// ES5
function add(x, y) {
    x = x || 0
    y = y || 0
    return x + y
}

// ES6
function add(x=0, y=0) {
    return x + y
}

add(3.6) / / 9
add(3) / / 3
Copy the code
  • Extension operator
console.log(... [1.2.3])
/ / 1 2 3

console.log(1. [2.3.4].5)
// 1, 2, 3, 4, 5
Copy the code
  • Set (usually heavy)
const arr = [1.1.2.11.32.1.2.3.11]

const newArr = function(arr) {
    return[...new Set(arr))]
}

console.log(newArr(arr))
// [1, 2, 11, 32, 3]
Copy the code
  • Async Await
    async function main() { 
        var data = await yourPromise() 
        console.log(data) 
    }
Copy the code
  • includes()/startWith()/endsWith()

Includes () : determines whether the string contains certain strings

StartWith () : Returns true if specified text is detected at the beginning of the string

EndsWith () : Returns true if the specified text is detected at the end of the string

    const str = 'aabbcc' 
    const subStr = 'aa' 
    console.log(str.includes(subStr)) // true
    console.log(str.startWith(subStr)) // true
    console.log(str.endsWith(subStr)) // false
Copy the code