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

【Javascript】if文をワンライナー(1行)で書ける三項演算子とは?

Posted at

Javascript 三項演算子(if文を一行で書く)

なにこれ

Javascriptを学習中に、下記のコードを見て「ワンライナー?何これ?」と思ったので、
備忘録として記事化しました。(確か前にも同じ箇所でつまずいた)

count += todo.done ? 100 : 1;

答えは三項演算子

if文をワンライナー(一行)で書く方法の一つ
構文は下記

条件式 ? trueの時 : falseの時

例文

trueの場合

test.js
test = true;
console.log(test ? 100 : 1);
  // 表示結果:100

falseの場合

test.js
test = false;
console.log(test ? 100 : 1);
  // 表示結果:1

余談

紛らわしいのでif文で書きたい(本音)
でもワンライナーで書いた方がコードが短くなって可読性上がる。この葛藤。

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