0
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.

初期値を入れる方法

Last updated at Posted at 2022-12-07

引数に=をつけて初期値を入れる。


function hoge(num=1){
    console.log(num)
}

こうやってもいい。


function hoge(num){
    const number = num || 1
    console.log(number)
}


:追記
上のコードは間違えてたけど、

最近この記事を読んで、直せるかなと試してみた。

修正版

function hoge(num){
    const number = num ?? 1
    console.log(number)
}

hoge(0); // 0
hoge(''); //''

おおっ! いいぞ!

hoge(null); // 1

・・・やっぱり三項演算子を使いましょう。


オブジェクトはこんな感じかな。

function hoge(obj={num: 1,club:'soccer'}){
    console.log(obj)
}
function hoge(obj){
    Object.assign({
        num: 1,
        club:'soccer'
    }, obj);
    console.log(obj)
}

0
0
4

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
0
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?