在 JavaScript 中设置默认值的 3 种方法

2025-06-10

在 JavaScript 中设置默认值的 3 种方法

SamanthaMing.com 的代码小贴士

我一直以来都习惯用三元运算符来有条件地给变量赋值。但自从我发现“||”可以用作选择器运算符后,我就更多地使用它了。我发现我的代码更容易阅读了👍

是的,理解它需要一些时间。但一旦你掌握了这个概念,它就超级好用。现在我不认为代码越少,代码就越好。但在这种情况下,我更喜欢||运算符 🤩



let isHappyHour = '🍺';

// Logical Operator
isHappyHour = isHappyHour || '🍵'; // '🍺'

// Ternary
isHappyHour = isHappyHour ? isHappyHour : '🍵'; // '🍺'

// If/Else
if (isHappyHour) { 
  isHappyHour = isHappyHour 
} else { 
  isHappyHour = '🍵' 
}

console.log(isHappyHour); // '🍺'


Enter fullscreen mode Exit fullscreen mode

理解||操作符

我确信大多数人认为它||仅用于布尔检查,如下所示:



if(a || b) {
  // do something
}


Enter fullscreen mode Exit fullscreen mode

但是!您也可以用它来计算所选表达式并生成一个值。正因如此,将逻辑运算符视为选择运算符会很有帮助。当它与非布尔值一起使用时,该||运算符将返回指定表达式或操作数之一的非布尔值。

是不是脑子爆炸了?别担心,让我用 Kyle Simpson 的解释来解释。他是《你不懂 JavaScript》的作者,这是一本免费的 JavaScript 电子书。

&& 或 || 运算符生成的值不一定是布尔类型。生成的值始终是两个操作数表达式之一的值。

好,我们来看一个例子。



const truthy = true;
const falsy = false;
const poop = '💩';

truthy || poop; // true
falsy || poop; // '💩';


Enter fullscreen mode Exit fullscreen mode

只要第一个表达式(左侧)为真,它就始终会被选中。但是,如果第一个表达式(左侧)为假,则默认输出第二个表达式(右侧)。这就是为什么它||被称为设置默认值的运算符。

使用默认值作为函数参数

您经常会看到||这样的用法:



function(name) {
  name = name || 'no name';
}


Enter fullscreen mode Exit fullscreen mode

注意:这不再是推荐的方式。它比 ES6 的默认参数好得多。因为很多时候,你可能不希望所有假值都启用默认值——我将在下一节解释假值。更常见的情况是,我们只希望在没有值或undefined没有作为参数传递时才设置默认值。

ES6 默认参数的更好解决方案



function(name = 'no name') {
}


Enter fullscreen mode Exit fullscreen mode

虚假值

在该||运算符中,仅当第一个表达式(左侧)满足条件时,才会求值第二个表达式(右侧)。因此,让我们检查一下什么构成了假值。



// JS Essentials: Falsy Values

false
undefined
null
NaN
0
"" or '' or `` (empty string)
```

<br>

_(I wrote another blog post on Falsy Values, which you can read it [here](https://www.samanthaming.com/tidbits/25-js-essentials-falsy-values))_


## Compared to the `&&` operator

In my previous post, I wrote about the `&&` operator. (Read it [here](https://medium.com/@samanthaming/prevent-object-retrieval-typeerror-with-74ea0a58437f)). The `&&` is also known as the **Guard Operator**. So here's a quick summary of the difference:

- `||`: 1st expression is always outputted. The 2nd expression only gets outputted if the 1st expression is falsy.

- `&&`: 1st expression is outputted if it's FALSY. The 2nd expression only get outputted if the 1st expression is truthy.

## What is the Elvis Operator

This is an interesting one. In JavaScript we have `||` to set default values. In other languages such as **C++**, this behavior is similar to the **Elvis Operator** which is denoted as `?:`.

```javascript
// JavaScript
someVariable || 'default value'

// Elvis Operator (not JavaScript)
someVariable ?: 'default value'
```

As to why it's called the Elvis Operator:

![Credit to GlobalNerdy.com](https://thepracticaldev.s3.amazonaws.com/i/7itmzmaoim6awjmqop4k.jpg)

_Image Credit to GlobalNerdy.com_


## When to use which?

Now that you understand **Falsy Values**, let's figure out which way of the 3 ways is better to use.

**🏆Logical Operator `||`**

This is great if you want to capture all falsy values. It's less code and it's way easier to read. Assuming that everyone understands all 3 behaviors, of course. 

_NOTE: I'm not saying less code is always better, one can easily try to be too clever and shorten the code which renders it unreadable. We write code for others, it's a form of communication. It's always better to go with the option that conveys understanding over being clever._

```javascript
let a;

// ✅ Short and simple
a = a || b;

// ☹️ Meh, could be better
a = a ? a : b;

// 😱 Ouch
if (a) {
  a = a;
} else {
  a = b;
}
```

**🏆Ternary Operator**

Let's say we don't want to capture ALL falsy values. And we only want the default value to kick in when it's `undefined`

```javascript
// ❌ Logical doesn't work
a = (a === undefined) || b;
// (a === undefined) > will output a boolean 'true' not the actual value

// ✅ Ternary works
a = (a === undefined) ? a : b;

// ☹️ Of course if/else will also work...but Ouch
if (a === undefined) {
  a = a;
} else {
  a = b;
}
```

**🏆If/Else**

This is the option with the MOST control. And it's something I would absolutely go for if say, I need to perform an additional action.

```javascript
// ✅ If/Else is much better
if (a) {
  a = a;
  // do something else
} else {
  a = b;
}
```

---

## Resources

- [MDN Web Docs - Logical Operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/)
- [YDKJS: Types & Grammer](https://github.com/getify/You-Dont-Know-JS/blob/f0d591b6502c080b92e18fc470432af8144db610/types%20%26%20grammar/ch4.md)
- [Wikipedia - Elvis Operator](https://en.wikipedia.org/wiki/Elvis_operator)
- [Stack Overflow - Comparison of Ternary operator, Elvis operator, safe Navigation Operator and logical OR operators](https://stackoverflow.com/questions/44046927/comparison-of-ternary-operator-elvis-operator-safe-navigation-operator-and-log)
- [Stack Overflow - Logical or vs. Ternary operator](https://stackoverflow.com/questions/42026158/precedence-logical-or-vs-ternary-operator)
- [Default Operator in JavaSctipt and Real Life Examples](https://zzz.buzz/2016/01/10/default-operator-in-javascript-and-real-life-examples/)
- [SamanthaMing.com - Guard Operator](https://www.samanthaming.com/tidbits/51-prevent-object-retrieval-type-error-with-guard-operator)


---

**Thanks for reading ❤**
Say Hello! [Instagram](https://www.instagram.com/samanthaming/) | [Twitter](https://twitter.com/samantha_ming) | [Facebook](https://www.facebook.com/hisamanthaming) | [Medium](https://medium.com/@samanthaming) | [Blog](https://www.samanthaming.com/blog)
Enter fullscreen mode Exit fullscreen mode
鏂囩珷鏉ユ簮锛�https://dev.to/samanthaming/3-ways-to-set-default-value-in-javascript-2253
PREV
JavaScript 中将值转换为字符串的 5 种方法
NEXT
在 JavaScript 中将值转换为布尔值的 2 种方法