Search code examples
javascriptexpressdestructuring

Why am I getting 'undefined is not a function' for this destructuring assignment code?


Say I have this request coming into an API route:

/api/things?p=2&t=25&some_id=67&another_id=89

Can I use a destructuring assignment to get the parameters into local variables? I've tried this:

const [p, t, ...otherParams] = request.query;

...but I get "undefined is not a function" at runtime, which is an odd error that I can't debug. What I'd really love is to use destructuring with defaults. In my flawed syntax, that would be something like:

const [p = 1, t = 25, ...otherParams] = request.query;

Is this possible? If so, what am I doing wrong?


Solution

  • The value you are destructuring is an object, not an array. Therefore you need to use the object destructuring syntax. If you use the wrong flavor you get the not very helpful "undefined is not a function" error.

    const {p = 1, t = 25, ...otherParams} = request.query
    

    I struggled with this very same error last Friday.