2
3

デバッグしやすい書き方が掴めてきた気がする

Posted at

最近『セイト先生が教えるプログラミング入門』でJavaScriptの勉強に取り組んでいます。その中でデバッグしやすい書き方が少しだけ掴めてきた気がします。

デバッグ1

まず、第5章第13節「非同期処理を可能にするPromiseオブジェクト」の「Promiseとは」(pp.275-277)でPromiseオブジェクトを使った関数の例(foo)が紹介されていたのですが、1-10 & 12-16行目の { } 内が少し長かったためか、

foo.then((resolve) => {...
});

(p.275. コード12-16行目. { }内は省略)

のところで、fooの後ろに書くべき () が抜けていたことに気付かず、全体をハイライトしてctrl + shift + LでCursorのAIに聞いてみてもどこがおかしいのか自分にはよく分かりませんでした。そのためしばらく苦戦していたのですが、最終的に下記のような形で細かく関数を定義することを思いつきました。その上で再びAIにどこに問題があるのか尋ねたところ、上述の問題点を見つけることが出来ました。

// 教科書p.275. 4-8行目
const function0 = (condition, resolve, reject) => {
    if (condition) {
        resolve("成功");
    } else {
        reject("エラー");
    };
};

//教科書p.275. 2-9行目
const function1 = (resolve, reject) => {
    const condition = true; //教科書p.275. 3行目
    function0(condition, resolve, reject);
};

// 教科書1-10行目
const foo = () => {
    return new Promise(function1);
};

// fooと同様に定義 cf.教科書p.276
const bar = () => {
    return new Promise(function1);
};
const baz = () => {
    return new Promise(function1);
}; 

//教科書p.275. 12-14行目
const function2 = (resolve) => {console.log(resolve);};

//教科書14-16行目
const function3 = (reject) => {console.log(reject);};

// 教科書p.276
//foo().then(function2).catch(function3).finally(() => {
//    console.log("リクエスト処理が完了しました。");
//});

const asyncFunction = async () => {
    await foo().then(function2).catch(function3);
    await bar().then(function2).catch(function3);
    await baz().then(function2).catch(function3);
};
asyncFunction();

デバッグ2

次に躓いたのは、第6章第3節「カウンター・プログラム2」でした。このときは、間違っていたのは本ではなく私の方で、

    for (let index = 0; index < document.getElementsByClassName("js-button").length; index++) {
        document.getElementsByClassName("js-button")[index].addEventListener("click", (e) => clickHandler(e))
    }

(p.301. コード14-16行目)
のaddEventListenerの引数を私は clickHandler(e) と書いていました。このときも以前、関数を設定したのと同じように、変数を設定することで自分にとって読みやすいようにすることにしました(下記)。

const $button = document.getElementsByClassName("js-button");
for (let index = 0; index < $button.length; index++) {
    $button[index].addEventListener("click", (e) => clickHandler(e);
    );
}

結論

初心者の自分が分からないだけで、変数や関数が多くなると何かデメリットがあるのかもしれないが、今勉強しているかぎりでは、括弧の中身は短い方が読みやすくていいと思いました。

2
3
1

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
2
3