LoginSignup
1
0

More than 3 years have passed since last update.

JavaScriptのショートハンドまとめた

Last updated at Posted at 2020-06-05

初めに

今回はJavaScriptのショートハンドについて展開します。
構文をすっきり書けることが可読性がいいプログラムコードにつながると信じています。
しかし、省略しすぎると逆に追うのが面倒になってしまうのがネックです。(そこは綺麗な設計でカバーできるかも)
JavaScriptはいろんなショートハンドがありわかりにくいですが、覚えた方がいい物ではあります。

コード

条件式

before

main.js
var x = false;
if (x) {
 console.log("hello world!");
} else {
  console.log("Test1!");
} 

after

main.js
var x = false;
console.log(x ? "hello world!" : "Test1!");

条件式(elseなし)

before

main.js
var x = true;
if (x) {
 console.log("hello world!");
}

after

main.js
var x = true;
x&&console.log("hello world!");
console.log(x ? "hello world!" : "Test1!");

boolean型の反転

main.js
flg = !flg;

for文

配列の中身を順番に抽出
before

main.js
var testList = ["Test","Test1","Test2"];
for (let i = 0; i < testList.length; i++) {
  console.log(testList[i]);
}

after

main.js
var testList = ["Test","Test1","Test2"];
for (let index in testList) {
    console.log(testList[index]);
}

関数の呼び出し

before

main.js
let a = "aaa";
function Test() {
  console.log('test')
};
function Test1() {
  console.log('testTest')
};
if (a == "aaa") {
  Test();
} else {
  Test1();
}

after

main.js
let a = "aaa";
function Test() {
  console.log('test')
};
function Test1() {
  console.log('testTest')
};
(a=="aaa" ? Test:Test1)();

終わりに

これらをうまく活用することで重複するような(似たような)コードを書かなくてすみます。
何に対しても整理整頓が大事ということです。

1
0
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0