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?

[JavaScript] 演算子とは

Posted at

概要

JavaScriptには多くの「演算子 (operator)」が存在します。
演算子は、計算・代入・比較・論理判定・型チェック・非同期処理など、幅広い場面で使用されます。

本記事では、

  • 演算子をカテゴリ別に整理
  • if文以外での実務的な活用場面を説明

という観点でまとめます。

目次

演算子一覧(カテゴリ別)

カテゴリ 主な演算子 説明
算術演算子 (Arithmetic) +, -, *, /, %, ** a + b 四則演算、剰余、べき乗
代入演算子 (Assignment) =, +=, -=, *=, /=, %= x += 3 変数へ値を代入・更新
比較演算子 (Comparison) ==, ===, !=, !==, >, <, >=, <= a === b 値および型の比較、真偽値を返す
論理演算子 (Logical) &&, ||, ! a && b AND / OR / NOT の条件処理
ビット演算子 (Bitwise) &, |, ^, ~, <<, >>, >>> a & b ビット単位の処理(低レベル向け)
型判定演算子 (Type-related) typeof, instanceof typeof x 型やインスタンスを判定する
条件(三項)演算子 (Ternary) 条件 ? A : B age >= 20 ? "成人" : "未成年" if文の簡略表現
文字列演算子 (String) + "A" + "B" 文字列連結
スプレッド / 残余演算子 (Spread / Rest) ... [...arr], (...args) 配列・オブジェクト展開、引数集約
Null合体演算子 (Nullish Coalescing) ?? value ?? "default" null / undefined の場合のみ代替値
オプショナルチェーン演算子 (Optional chaining) ?. obj?.prop 安全なプロパティ参照
コンマ演算子 (Comma) , (a = 1, b = 2) 複数式を順に評価し最後の値を返す
delete演算子 delete obj.key delete user.name オブジェクトプロパティ削除
in演算子 "key" in obj "name" in user プロパティ存在判定
new演算子 new Class() new Date() コンストラクタからインスタンス生成
void演算子 void expr void 0 undefined を返す
await演算子 await promise await fetch(url) Promise の完了を待つ(非同期制御)

活用例

論理演算子(条件式の簡略化)

const userName = input || "Guest";
const isNotAdmin = !user.isAdmin;

三項演算子(if文の置き換え)

const message = age >= 20 ? "成人" : "未成年";

React JSX でも頻出:

{isLoggedIn ? <Dashboard /> : <Login />}

Null合体演算子(未定義対策)

const name = user.name ?? "No Name";

オプショナルチェーン(安全なプロパティ参照)

console.log(user?.profile?.email);

型判定(関数引数チェックなど)

if (typeof x === "string") console.log("文字列です");
if (arr instanceof Array) console.log("配列です");

スプレッド・残余(データ展開)

const arr = [1, 2, 3];
const newArr = [...arr, 4];

await(非同期制御)

const data = await fetch("/api/user").then(r => r.json());

new(インスタンス化)

const now = new Date();

まとめ

分類 主な用途
算術演算子 計算処理、インデックス制御
代入演算子 集計・状態更新
比較 / 論理演算子 条件分岐と条件表現の簡略化
三項・Null合体・オプショナルチェーン UI・API・型安全な値処理
typeof / instanceof 型チェック・バリデーション
スプレッド / 残余 データ展開・オブジェクト操作
await / new 非同期処理・インスタンス生成

参考リンク

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?