JavaScriptの論理和演算子

論理和演算子はオペランドのうち1つ以上がtrueの場合にtrueを返す使い方が一般的ですが、0や空文字、falseの場合に別の値を返す使い方もできます。

null

const foo = null;
let msg = foo || 'sample';
console.log(msg); // "sample"

undefined

const foo = undefined;
let msg = foo || 'sample';
console.log(msg); // "sample"

数値

const foo = 0;
let msg = foo || 'sample';
console.log(msg); // "sample"
const foo = 1;
let msg = foo || 'sample';
console.log(msg); // 1

文字列

const foo = '';
let msg = foo || 'sample';
console.log(msg); // "sample"
const foo = 'the world';
let msg = foo || 'sample';
console.log(msg); // "the world"

論理値

const foo = false;
let msg = foo || 'sample';
console.log(msg); // "sample"
const foo = true;
let msg = foo || 'sample';
console.log(msg); // true
このエントリーをはてなブックマークに追加
にほんブログ村 IT技術ブログへ

スポンサードリンク

関連コンテンツ

コメント

メールアドレスが公開されることはありません。 が付いている欄は必須項目です