Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

syntax - What does "options = options || {}" mean in Javascript?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is useful to setting default values to function arguments, e.g.:

function test (options) {
  options = options || {};
}

If you call test without arguments, options will be initialized with an empty object.

The Logical OR || operator will return its second operand if the first one is falsy.

Falsy values are: 0, null, undefined, the empty string (""), NaN, and of course false.

ES6 UPDATE: Now, we have real default parameter values in the language since ES6.

function test (options = {}) {
  //...
}

If you call the function with no arguments, or if it's called explicitly with the value undefined, the options argument will take the default value. Unlike the || operator example, other falsy values will not cause the use of the default value.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...