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 3 years have passed since last update.

【JavaScriptのメモ】条件式ifについての注意事項

Last updated at Posted at 2021-10-13

以下のコードを実行すると、HTMLにどの条件式が実行されるでしょうか?

let hour = 14;
if (hour > 9) {
  document.write('Good Morning');
} else if (hour > 11) {
  document.write('Good Afternoon');
} else if (hour > 17) {
  document.write('Good Evening);
} else if (hour > 22) {
  document.write('sleepy');
} else {
  document.write(hour);
}

答えは、最初にtrueになるif (hour > 9) です。

【注意事項】
if文は一番早くtrueとなる処理だけ実行するので、後ろのelse ifでも条件が当てはまるからといって処理が実行されるわけでは無い。
つまり、先に実行されるtrue処理のみ表示する。
先のtrueの処理が完了すれば、処理そのものが終了し、以降の条件式は実行されない。

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