Skip to content
Advertisement

JS return an array and an object from function

In my react app I have a hook that handles resizing of the screen. The function returns an array of width and height.

JavaScript

And i call the hook in my react app like const [width] = useDimensions(). I also want to call the hook like const {isSmScreen} = useDimensions(). Is this possible and how can export it from the useDimensions hook

Advertisement

Answer

Sure, as an array is an object, you can define additional properties.

For instance:

JavaScript

Or:

JavaScript

Whether this is a good idea, is debatable though. If I use a function to get an array, I would not expect that array to have other custom properties.

It would be more natural to return the array data as a single property of the returned object, like:

JavaScript

Then the caller must of course be aware of that. To only get the width, it could do:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement