Обновлено с ECMAScript 2015 (ES6) вкусности. Смотри внизу.
Наиболее распространенные условные сокращения:
a = a || b // if a is falsy use b as default
a || (a = b) // another version of assigning a default value
a = b ? c : d // if b then c else d
a != null // same as: (a !== null && a !== undefined) , but `a` has to be defined
Буквенное обозначение объекта для создания объектов и массивов:
obj = {
prop1: 5,
prop2: function () { ... },
...
}
arr = [1, 2, 3, "four", ...]
a = {} // instead of new Object()
b = [] // instead of new Array()
c = /.../ // instead of new RegExp()
Встроенные типы (числа, строки, даты, логические значения)
// Increment/Decrement/Multiply/Divide
a += 5 // same as: a = a + 5
a++ // same as: a = a + 1
// Number and Date
a = 15e4 // 150000
a = ~~b // Math.floor(b) if b is always positive
a = +new Date // new Date().getTime()
// toString, toNumber, toBoolean
a = +"5" // a will be the number five (toNumber)
a = "" + 5 + 6 // "56" (toString)
a = !!"exists" // true (toBoolean)
Объявление переменной:
var a, b, c // instead of var a; var b; var c;
Символ строки в индексе:
"some text"[1] // instead of "some text".charAt(1);
Стандартные сокращения ECMAScript 2015 (ES6)
Это относительно новые дополнения, поэтому не ожидайте широкой поддержки среди браузеров.
Они могут поддерживаться современными средами (например, более новыми node.js) или с помощью транспортеров. «Старые» версии, конечно же, продолжат работать.
Функции стрелок
a.map(s => s.length) // new
a.map(function(s) { return s.length }) // old
Параметры покоя
// new
function(a, b, ...args) {
// ... use args as an array
}
// old
function f(a, b){
var args = Array.prototype.slice.call(arguments, f.length)
// ... use args as an array
}
Значения параметров по умолчанию
function f(a, opts={}) { ... } // new
function f(a, opts) { opts = opts || {}; ... } // old
деструктурирующие
var bag = [1, 2, 3]
var [a, b, c] = bag // new
var a = bag[0], b = bag[1], c = bag[2] // old
Определение метода внутри литералов объекта
// new | // old
var obj = { | var obj = {
method() { ... } | method: function() { ... }
}; | };
Вычисляемое свойство Имена Внутри литералов объекта
// new | // old
var obj = { | var obj = {
key1: 1, | key1: 5
['key' + 2]() { return 42 } | };
}; | obj['key' + 2] = function () { return 42 }
Бонус: новые методы для встроенных объектов
// convert from array-like to real array
Array.from(document.querySelectorAll('*')) // new
Array.prototype.slice.call(document.querySelectorAll('*')) // old
'crazy'.includes('az') // new
'crazy'.indexOf('az') != -1 // old
'crazy'.startsWith('cr') // new (there's also endsWith)
'crazy'.indexOf('az') == 0 // old
'*'.repeat(n) // new
Array(n+1).join('*') // old
Бонус 2: функции стрелок также делают self = this
захват ненужным
// new (notice the arrow)
function Timer(){
this.state = 0;
setInterval(() => this.state++, 1000); // `this` properly refers to our timer
}
// old
function Timer() {
var self = this; // needed to save a reference to capture `this`
self.state = 0;
setInterval(function () { self.state++ }, 1000); // used captured value in functions
}