😳

[JavaScript]ES6入門編で気になった構文たち

2022/03/20に公開

はじめに

これまでJavaScriptといえばjQueryくらいしか触ってこなかったので、TypeScript入門にあたってES6の基本構文をざっと眺めておこうと思い、freeCodeCampさんの動画を流し見しました。その中でちょっと気になったものがいくつかあるので、備忘録をかねてまとめておきます。

引用元はLearn JavaScript - Full Course for Beginnersです。

var, let, const

これは基本のキってかんじですが、varはグローバル変数、letはブロック変数、constは定数なのでvar以外を使いましょうって話だと理解。

variables.js
function test() {
  let a = 1;
  const b = 10;
  if (a > 0) {
    let a = 9;
    var c = 99;
    console.log(a); // 9
    console.log(b); // 10
    console.log(c); // 99
  }
  console.log(a); // 1 -> not 9 because it's a block variable.
  console.log(b); // 10
  console.log(c); // 99 -> accessible bacause it's a global variable.
}
test();

mutable, immutable

constは定数なので再代入不可ですが、オブジェクトを保持していた場合は変更できてしまう(mutable)。ので、変更させないためには(immubable)freezeをつかう。

immutable.js
const a = { test: 10 };
const b = { test: 100 };

// make b immutable
Object.freeze(b);

a.test = 99; // no error
console.log(a.test); // 99 -> means it's mutable
b.test = 999; // ERROR -> means it's immutable

Rest Operator

配列に変換してくれるやつ。

before.js
function add(x,y,z) {
  // create array and calc sum
  const args = [x, y, z];
  return args.reduce((a, b) => a + b, 0);
}
console.log(add(1, 2, 3)) // 6

これを、引数を...にすると

after.js
// use rest operator
function add(...args) {
  return args.reduce((a, b) => a + b, 0);
}
console.log(add(1, 2, 3, 4)) // 10

こうなる。引数の数も指定不要になるので柔軟!

Spread Operator

Rest Operatorとおなじ...をつかって配列の展開ができる。たとえば配列のコピーを考える。

before.js
const a1 = ['a', 'b', 'c'];
let a2;
function change() {
  a2 = a1;
  a1[0] = 'x';
}
change();
console.log(a2); // ['x', 'b', 'c']

これだとa1の最初の要素に対する変更がa2にも影響してしまう。そこでSpread Operatorを使うと要素が同じ要素をもった別の配列として扱える。

after.js
const a1 = ['a', 'b', 'c'];
let a2;
function change() {
  // use spread operator and make it array
  a2 = [...a1];
  a1[0] = 'x';
}
change();
console.log(a2); // ['a', 'b', 'c']

Destructing Assingment

objectから値を取り出して変数代入する動作を簡略化できる。

sample.js
const scores = { math: 80, english: 60 };
// usual assignment
let math = scores.math; // 80
let english = scores.english; // 60

// destructing assignment
const { math: m, english: e } = scores; // m = 80, e = 60

これを使うと、こんな感じに書ける。

destruct.js
const scores = { math: 80, english: 60 };
function getEnglishScore(scores) {
  const { english: englishScore } = scores;
  return englishScore;
}
console.log(getEnglishScore(scores)); // 60

また、{}を重ねることでネストしたobjectからの変数代入も同様に行える。

sample.js
const temperatures = {
  today: {
    min: 15,
    max: 25
  },
  tomorrow: {
    min: 10,
    max: 20
  }
};

// assign value from a nested object
const { tomorrow: { max : tomorrowMax }} = temperatures;
console.log(tomorrowMax); // 20

さらに、配列の値を取り出して変数代入する際にも利用できる。objectとの違いはインデックスの最初から取り出されるということ。要素をスキップする場合は,を使う。

destruct.js
const [x, y, , z] = [1, 2, 3, 4, 5];
console.log(x, y, z); // 1, 2, 4

let a = 10, b = 99;
function switch() {
  [a, b] = [b, a];
}
switch();
console.log(a); // 99
console.log(b); // 10

コード後半は配列のdestructを利用したスワップ。

Destructing Operatorの応用

descructとrestの合わせ技。これは慣れないと読めない。。。

sample.js
const all = [1, 2, 3, 4, 5];
function removeFirstTwo(array1) {
  const [ , , ...array] = array1;
  return array;
}
const removed = removeFirstTwo(all);
console.log(all); // [1, 2, 3, 4, 5]
console.log(removed); // [3, 4, 5]

関数の引数としてobjectを使うときにdestructingを利用する例。
普通に書くとこうなんだけど

before.js
const all = {
  min: 50,
  max: 100,
  middle: 70
}
function getAvearge(obj) {
  return (obj.min + obj.max) / 2;
}
console.log(getAvearge(all)); // 75

こうするとシンプルに書ける。APIコールなどでよく利用するらしい。

after.js
const all = {
  min: 50,
  max: 100,
  middle: 70
}
// use distructing assignment on arguments statement
function getAvearge({ min, max }) {
  return (min + max) / 2;
}
console.log(getAvearge(all)); // 75

Simple Fields

objectへの変換を

before.js
function createObj(name, age) {
  return {name: name, age: age};
}
console.log(createObj('taro', 10)); // { name: 'taro', age: 10}

こう書ける

after.js
function createObj(name, age) {
  return {name, age};
}
console.log(createObj('taro', 10)); // { name: 'taro', age: 10}

ひとまず以上です。色々できすぎて使いこなせているのか意図せずうまく動いているのか分からなくなりそうですね。JavaScriptおそろしや。。。

Discussion