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?

条件式を一行でかける発見!!三項演算子との出会い / Discover Conditional Expressions Multiply by One Line! Meet the ternary operator! (日本語 / 英語)

Last updated at Posted at 2024-12-21

image.png

日本語

こんばんわ!
Advent Calendar 2024に参加してまして、20日目の記事を書いていこうと思います。
題材は「脆弱エンジニアの Advent Calendar 2024」ということで、コードのちょっとした発見を書いていこうと思います。

if文って一行でかけるという発見

皆さんはif文というか条件分岐ってどう書きます?
私はこう書いてました

var test = string.empty;
var flag = true;
if (flag){
    test = "OK";
}
else{
    test = "NG";
}

これでいいと思ってました!
ただ、これを仕事でやるともっと簡単にかけと怒られましたw

ではどうすれば。。

三項演算子(条件演算子)との出会い

下記のように、三項演算子(条件演算子)を使えば一行でかけることができるんですね。

var test = flag ? "OK" : "NG";

同じ処理でも、いろいろな書き方があるんだと脆弱ながら学んだ体験でした。

ここまで読んでいただきありがとうございます

ENGLISH

Good evening!
I'm participating in Advent Calendar 2024 and I'm going to write an article for the 20th day.
The subject is “Vulnerable Engineer's Advent Calendar 2024,” so I'd like to write about a small discovery of code.

I discovered that if statements can be written in one line.

How do you write if statements or conditional branching?
I used to write like this

var test = string.empty;
var flag = true;
if (flag){
    test = "OK";
}
else{
    test = "NG";
}

I thought this was fine!
But when I did this at work, I was pissed off that I had to do it more easily. w

So what should I do?

Encounter with ternary operators (conditional operators)

I found out that I can do it in one line by using ternary operators (conditional operators) as shown below.

var test = flag ? "OK" : "NG";

It was an experience where I learned, while being vulnerable, that there are many ways to write the same process.

Thank you for reading this far!

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?