1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【ひとりカレンダー】フロントエンド開発成長日記Advent Calendar 2022

Day 12

JavaScriptの便利な構文 -分割代入とスプレット構文

Last updated at Posted at 2022-12-11

はじめに

JavaScriptには便利な記法が多く、
使いこなすことでシンプルなコードを書くことが可能になりますが、
フロントエンド開発をしているなかで、あまり意識できずにたらたらと長いコードを書きがちです。

便利な構文をピックアップしました。

分割代入

const [a, b] = ['hoge', 'fuga'];
console.log(a, b); // hoge fuga
const profile = { id: 1, name: '田中', age: 28 };
const { id, name } = profile;
console.log(id, name); // 1 '田中'
const [, , a, , b] = [1, 2, 3, 4];
console.log(a, b); // 3 undefined

活用してみると、

const data = {
  users: [
    {
      id: 1,
      name: '田中',
      email: 'tanaka@example.com',
    },
    {
      id: 2,
      name: '鈴木',
      email: 'suzuki@example.com',
    },
    {
      id: 3,
      name: '佐藤',
      email: 'sato@example.com',
    },
  ],
  url: 'https://hogehoge.com',
  params: {
    hoge: 'hoge',
    fuga: 'fuga'
  }
}

const { users, params: parameters, status = 200 } = data

console.log(users)
// [
//   { id: 1, name: '田中', email: 'tanaka@example.com' },
//   { id: 2, name: '鈴木', email: 'suzuki@example.com' },
//   { id: 3, name: '佐藤', email: 'sato@example.com' }
// ]

console.log(parameters)
// { hoge: 'hoge', fuga: 'fuga' }

console.log(status)
// 200

のように書ける。

スプレット構文

const hoge = ['a', 'b', 'c'];
const fuga = [...hoge, 'd', 'e'];
const hogehoge = ['Y', 'Z', ...fuga]
console.log(fuga) // ['a', 'b', 'c', 'd', 'e'];
console.log(hogehoge) // ['Y', 'Z', 'a', 'b', 'c', 'd', 'e'];

先ほどの分割代入と組み合わせて↓のようにも書ける

const users = {
  id: 1,
  name: '田中',
  email: 'tanaka@example.com',
}

const { id, ...ExceptId } = users

console.log(id)
// 1

console.log(ExceptId)
// { name: '田中', email: 'tanaka@example.com' }

うまく使ってシンプルなコーディングを心がけましょう!

1
0
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?