JavaScript函数参数解构报错:如何访问函数内的first/second布尔值?
first and second Booleans in someFunction & Fix the Destructuring Error The Problem
You’ve got a function set up like this, and you’re hitting a TypeError: Cannot read property 'first' of undefined when trying to access the first and second boolean values:
function someFunction(actions, { first = true, second= false }) { if(first == true) { console.log("something"); } }
You’re wondering:
- How to properly access
firstandsecondinsomeFunction - Whether the second parameter uses object destructuring syntax (it does!)
- How to resolve that destructuring error
The Root Cause
That second parameter is object destructuring syntax—you’re trying to extract first and second from an object passed as the second argument. The error pops up because when you call someFunction without providing a second argument (or passing undefined), JavaScript tries to read properties from undefined, which isn’t allowed.
The Fixes
There are two straightforward ways to fix this:
1. Set a Default Empty Object for the Second Parameter
Add = {} to the second parameter to give it a fallback empty object when no argument is provided. This lets the destructuring safely fall back to your first = true and second = false defaults:
function someFunction(actions, { first = true, second = false } = {}) { if (first === true) { // Pro tip: Use === for strict equality checks! console.log("something"); } }
Now you can call the function in multiple valid ways:
someFunction(yourDefinedActions): Uses the defaultfirst=true,second=falsesomeFunction(yourDefinedActions, { first: false }): Overridesfirst, keeps defaultsecond=falsesomeFunction(yourDefinedActions, { second: true }): Overridessecond, keeps defaultfirst=true
2. Always Pass an Object as the Second Argument
If you control all calls to someFunction, make sure you always pass an object (even an empty one) as the second parameter. This avoids the undefined scenario entirely:
// Full custom values someFunction(yourDefinedActions, { first: false, second: true }); // Use all defaults by passing empty object someFunction(yourDefinedActions, {});
Quick Recap
- Your second parameter is indeed using object destructuring—you’re on the right track!
- The error comes from trying to destructure
undefined. Fix it either by setting a default empty object for the second parameter, or by always passing an object when calling the function.
内容的提问来源于stack exchange,提问作者Almuntasir Abir

