JS ショートコード・ショートハンド集

冗長になりがちなソースコードを短く書く方法。日頃のコーティングを楽にする方法。
JavaScriptをもっと短く書く方法を集めてみました。
すぐに使えるJavaScriptのショードハンドをご紹介。

ES6のコードを含んでいます。
ES6の各ブラウザ対応状況は以下からどうぞ。
ECMAScript 6 compatibility table

ES6とは?
ECMASCriptの6th Editionのこと。ECMAScript 6th editionの6を取ってES6と呼ばれていたが、2015年に標準化されたため正式名称はES2015になりました。
(ES6 = ES2015)

短いコードで生産性を高めるのは重要だが、やりすぎると可読性を失いワケワカメのコードになるのでほどほどに。

index

三項演算子

const x = 20;let answer;if (x > 10) {    answer = 'is greater';} else {    answer = 'is lesser';}
const answer = x > 10 ? 'is greater' : 'is lesser';

短絡演算に使えるショートハンド

if (variable1 !== null || variable1 !== undefined || variable1 !== '') {     let variable2 = variable1;}
const variable2 = variable1  || 'new';

変数宣言のショートハンド

let x;let y;let z = 5;
let x, y, z=5;

値の存在確認に使えるショートハンド

if (likeJavaScript === true)
if (likeJavaScript)

値の存在確認に使えるショートハンド2

let a;if ( a !== true ) {}
let a;if ( !a ) {}

JavaScriptのループ文のショートハンド

for (let i = 0; i < allImgs.length; i++)
for (let index in allImgs)
function logArrayElements(element, index, array) {  console.log("a[" + index + "] = " + element);}[2, 5, 9].forEach(logArrayElements);

短絡評価

let dbHost;if (process.env.DB_HOST) {  dbHost = process.env.DB_HOST;} else {  dbHost = 'localhost';}
const dbHost = process.env.DB_HOST || 'localhost';

10の累乗を指数で指定

for (let i = 0; i < 10000; i++) {}
for (let i = 0; i < 1e7; i++) {}1e0 === 1;1e1 === 10;1e2 === 100;1e3 === 1000;1e4 === 10000;1e5 === 100000;

オブジェクトプロパティのショートハンド

const obj = { x:x, y:y };
const obj = { x, y };

アロー関数のショートハンド

function sayHello(name) {  console.log('Hello', name);}setTimeout(function() {  console.log('Loaded')}, 2000);list.forEach(function(item) {  console.log(item);});
sayHello = name => console.log('Hello', name);setTimeout(() => console.log('Loaded'), 2000);list.forEach(item => console.log(item));

アロー関数

var fn = function (a, b) {  return a + b;};
const fn = (a, b) => {  return a + b;};const fn = (a, b) => a + b;const fn = (a, b) => ({ sum: a + b });

暗黙の戻り値のショートハンド

function calcCircumference(diameter) {  return Math.PI * diameter}
calcCircumference = diameter => (  Math.PI * diameter;)

パラメーター初期値

function volume(l, w, h) {  if (w === undefined)    w = 3;  if (h === undefined)    h = 4;  return l * w * h;}
volume = (l, w = 3, h = 4 ) => (l * w * h);volume(2) //output: 24

テンプレート文字列

const welcome = 'You have logged in as ' + first + ' ' + last + '.'const db = 'http://' + host + ':' + port + '/' + database;
const welcome = `You have logged in as ${first} ${last}`;const db = `http://${host}:${port}/${database}`;

分割代入のショートハンド

const observable = require('mobx/observable');const action = require('mobx/action');const runInAction = require('mobx/runInAction');const store = this.props.store;const form = this.props.form;const loading = this.props.loading;const errors = this.props.errors;const entity = this.props.entity;
import { observable, action, runInAction } from 'mobx';const { store, form, loading, errors, entity } = this.props;
const { store, form, loading, errors, entity:contact } = this.props;

複数行にわたる文字列のショートハンド

const lorem = 'Lorem ipsum dolor sit amet, consectetur\n\t'    + 'adipisicing elit, sed do eiusmod tempor incididunt\n\t'    + 'ut labore et dolore magna aliqua. Ut enim ad minim\n\t'    + 'veniam, quis nostrud exercitation ullamco laboris\n\t'    + 'nisi ut aliquip ex ea commodo consequat. Duis aute\n\t'    + 'irure dolor in reprehenderit in voluptate velit esse.\n\t'
const lorem = `Lorem ipsum dolor sit amet, consectetur    adipisicing elit, sed do eiusmod tempor incididunt    ut labore et dolore magna aliqua. Ut enim ad minim    veniam, quis nostrud exercitation ullamco laboris    nisi ut aliquip ex ea commodo consequat. Duis aute    irure dolor in reprehenderit in voluptate velit esse.`

スプレッド演算子のショートハンド

const odd = [1, 3, 5];const nums = [2 ,4 , 6].concat(odd);const arr = [1, 2, 3, 4];const arr2 = arr.slice();
const odd = [1, 3, 5 ];const nums = [2 ,4 , 6, ...odd];console.log(nums); const arr = [1, 2, 3, 4];const arr2 = [...arr];
const odd = [1, 3, 5 ];const nums = [2, ...odd, 4 , 6];const { a, b, ...z } = { a: 1, b: 2, c: 3, d: 4 };console.log(a);console.log(b);console.log(z);

必須パラメーターのショートハンド

function foo(bar) {  if(bar === undefined) {    throw new Error('Missing parameter!');  }  return bar;}
mandatory = () => {  throw new Error('Missing parameter!');}foo = (bar = mandatory()) => {  return bar;}

Array.findのショートハンド

const pets = [  { type: 'Dog', name: 'Max'},  { type: 'Cat', name: 'Karl'},  { type: 'Dog', name: 'Tommy'},]function findDog(name) {  for(let i = 0; i<pets.length; ++i) {    if(pets[i].type === 'Dog' && pets[i].name === name) {      return pets[i];    }  }}
pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy');console.log(pet); 

Object [キー]構文を利用したショートハンド

function validate(values) {  if(!values.first)    return false;  if(!values.last)    return false;  return true;}console.log(validate({first:'Bruce',last:'Wayne'})); 
const schema = {  first: {    required:true  },  last: {    required:true  }}const validate = (schema, values) => {  for(field in schema) {    if(schema[field].required) {      if(!values[field]) {        return false;      }    }  }  return true;}console.log(validate(schema, {first:'Bruce'})); console.log(validate(schema, {first:'Bruce',last:'Wayne'})); 

ビット否定演算子を2度使うショートハンド

Math.floor(4.9) === 4  //true
~~4.9 === 4  //true

小数点の省略

1+0.5;
1+.5;

小数点の切捨てをビット演算で行う

Math.floor(1.2345)
1.2345|0~~1.2345

四捨五入をビット演算で行う

a=Math.round(10.3);b=Math.round(10.6);console.log(a,b);
a=10.3+.5|0;b=10.6+.5|0;console.log(a,b);

べき乗演算子

Math.pow(-3,2)
-3**2

-1判定をビット演算で行う

z='abcdefg';if(z.indexOf('a')!==-1){  console.log('a in z');} else {  console.log('a not in z');}
z='abcdefg';if(~z.indexOf('a')){  console.log('a in z');} else {  console.log('a not in z');}

true/falseを!0/!1で代用

true,false
!0,!1

配列型のように文字列から一文字を抜き出す。

'あいうえお'.charAt(2)
'あいうえお'[2]

文字列を一文字ずつ配列に格納

a='abcdefg'.split('');
a=[...'abcdefg'];

同じ文字の繰り返し

aaaaaaaaaaaaaa
'a'.repeat(13)Array(13).join`a`Array(17).fill('a') //配列のまま

乱数生成にDateを利用する

Math.random()*2&1
new Date&1

配列やオブジェクトの連結にスプレッド構文を使う

a=[1,2,3],b=[4,5,6];a.push.apply(a,b);console.log(a);
a=[1,2,3],b=[4,5,6];a.push(...b);console.log(a);a=[1,2,3],b=[4,5,6];console.log([...a,...b]);//[1, 2, 3, 4, 5, 6]

オブジェクトのマージ

a={z1:1,z2:2,z3:3}b={z2:4,z3:5,z4:6}c=Object.assign(a,b) console.log(c)
a={z1:1,z2:2,z3:3}b={z2:4,z3:5,z4:6}c={...a,...b} console.log(c)

配列の先頭を削る

a=[1,2,3,4,5,6];b=a.slice(1);console.log(b);
a=[1,2,3,4,5,6];[,...b]=a;console.log(b);
[2, 3, 4, 5, 6]

16進数文字列の10進数化の省略

a='10';console.log(parseInt(a,16));
a='10';console.log('0x'+a-0);
16

配列数の評価にlengthプロパティではなくin演算子を使う

a=[1,2,3];console.log(a.length>3); 
a=[1,2,3];console.log(3 in a); 
false

文字列数の評価にlengthプロパティではなく文字列オブジェクトを使う

a='xyz';console.log(a.length>3); 
a='xyz';console.log(!!a[3]); 
false

window オブジェクトをthisで取得

console.log(window);
console.log(this);
Window

document.getElementByIdの省略

document.getElementById('id').innerText
t.innerText

new演算子の対象のカッコを省略

new Date()new Array()
new Datenew Array

繰り返し使うメソッドやオブジェクトを変数に格納

Math.ceil(12.5),Math.ceil(0.2)
a=Math.ceil;a(12.5),a(0.2);

頻出するオブジェクトをwith句でまとめる

Math.ceil(1.5)+Math.floor(1.5)+Math.round(1.5);
with(Math)ceil(1.5)+floor(1.5)+round(1.5);

メソッドに配列でアクセスする

test1.classList.add('a');test2.classList.remove('b');test3.classList.add('c');
test1[x='classList'][y='add']('a');test2[x].remove('b');test3[x][y]('c');

setTimeout、setIntervalの第一引数を文字列で渡す

setTimeout(function(){    console.log('あ');},1000);
setTimeout("console.log('あ')",1000);

setTimeout、setInterval 1ミリ秒であれば第二引数を省略できる。

setTimeout("console.log('あ')");
setTimeout`console.log('あ')`;

文字列を渡すメソッドや関数の()を省略する(ES6)

alert('あ'); test.classList.add('a'); 
alert`あ`;test.classList.add`a`

ifの省略 else節の無いif文を論理演算子で代用

a='あ';if(a=='あ'){    console.log(a+a);}
a='あ';(a=='あ')&&console.log(a+a);
'ああ'

ifの省略 else節の無いif文を論理演算子で代用

a=0;if(!a){    console.log(a);}
a=0;a||console.log(a);

if...else文を三項演算子に書き換える。

var a=1,b=2,c;if(a==1){    c=a+b;} else {    c=a-b;}console.log(c);
var a=1,b=2,c;c=(a==1)?a+b:a-b;console.log(c);
3

型の判定

typeof a==='string' typeof a==='number' typeof a==='boolean' typeof a.b==='undefined' isFinite(a) typeof b==='function' Array.isArray(a) 
''+a===a+a===a!!a===aa.b===0[0]a!==1/0/^f/.test(typeof b)a.pop

for文の省略 ブレースを省略する

a=b=0;for(var i=0;i<10;i++){    a+=i;    b+=i;}console.log(a,b);
a=b=0;for(var i=0;i<10;i++)a+=i,b+=i;console.log(a,b);
45 45

for文の省略 デクリメントで記述し条件式を省略する

a=b=0;for(var i=0;i<10;i++){    a+=i;    b+=i;}console.log(a,b);
a=b=0;for(var i=10;i--;){    a+=i;    b+=i;}console.log(a,b);
45 45

for文の省略 for文のネストを省略する

for(i=10;i--;)for(j=5;j--;)console.log(i,j);
for(k=50;k--;)console.log(k/5|0,k%5);

switch文の省略

$(document).on('keypress', function(e){    switch (e.keyCode){        case 39:            console.log('next');            break;        case 37:            console.log('prev');            break;        default:            break;    }});
$(document).on('keypress', function(e){    (b=({39:'next',37:'prev'})[e.keyCode])&&console.log(b);});

代入を処理文の中に書く

mes='あ';console.log(mes);a=1,b=2;c=a+b;console.log(c);
console.log(mes='あ');c=(a=1)+(b=2);console.log(c);

配列、オブジェクトの初期化

var a = new Array(),    b = new Object;
var a=[],b={};

functionをアロー関数で記述し省略する。(ES6)

var a = function(r){    return 'あ'+r;};console.log(a('い'));
var a=(r)=>{    return 'あ'+r};console.log(a('い'));var a=(r)=>{return 'あ'+r};console.log(a('い'));var a=r=>'あ'+r;console.log(a('い'));
あい

Template literalを使い文字列操作を省略する(ES6)

a='い',b='う';console.log('あ'+a+b+'え\nお');
a='い',b='う';console.log(`あ${a+b}えお`);
あいうえお