1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

オブジェクトのキーと変数名が同じ場合の省略記法(JavaScript)

Last updated at Posted at 2024-10-26

概要

  • JavaScriptでオブジェクトのキーと変数名が同じ場合、変数名を省略して記述出来る(オブジェクトリテラルの省略記法)
  • オブジェクトを省略して記述できるのは便利だが、スプレッド構文と組み合わせた場合など勘違いしやすい

コード

  • 省略記法を使用しない場合
const title = 'JavaScriptの学習';
const time = 2;

{
    title: title,
    time: time
}
  • 省略記法を用いた場合(キー名と変数名が同じなので値を省略できる)
const title = 'JavaScriptの学習';
const time = 2;

{
    title,
    time
}
  • 間違えやすい状況
    スプレッド構文と合わせてオブジェクトリテラルの省略記法が使われている場合、{}がオブジェクトを表しているのかJavaScriptを埋め込んでいるのか分かりづらい
const newRecords = [...records, {title, time}];
1
1
2

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?