Structs in JavaScript
Tags: javascript, webdev, watercooler, programming
Published: 2022-05-07 23:59:19

Update May 8th 2022:

<blockquote>If you like to use it, I've just published it as <a href="https://www.npmjs.com/package/makestruct" target="_blank">npm package</a>.

<pre>
npm i makestruct
</pre>
</blockquote>

<h1>What is a struct?</h1>

A struct is used for building data structures. These structures are used to group related data together.

There are differences on how they work behind the scenes depending on the programming language but the fun thing is that there are no structs in JavaScript.

When you want to create a custom data structure in JS you usually do a single thing. Creating an Object.
```javascript
const user = {
  id: 0,
  name: '',
  country: '',
  pets: [],
}
```

But is there any other way to do that? 

**Let's try to create a function to dynamically generate "structs" in JavaScript!**


![dope javascript structs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mqusw4eaoodxbdorvor2.gif)


```javascript
/**
 * @constructor Generates a constructor for a given data structure
 * @param {string} keys separated by a comma + whitespace. struct('id, name, age')
 * @returns {constructor} Constructor for the new struct
 */
function makeStruct(keys) {
  if (!keys) return null;
  const k = keys.split(', ');
  const count = k.length;

  /** @constructor */
  function constructor() {
    for (let i = 0; i < count; i++) this[k[i]] = arguments[i];
  }
  return constructor;
}
```

## How it works?
It takes a comma + whitespace separated string and generates a **constructor** for the structure you desired, so you can now instantiate your objects using this dynamically generated constructor.

## Usage:

```javascript
const user = new makeStruct("id, name, country");
const johnny = new user(1, 'John', 'UK');
console.log(johnny.name); // john
```

We can also assign complex structures at our properties!

```javascript
const user = new makeStruct("id, name, country, pets");
const pepe = new user(1, 'Pepe', 'ES', ['Baxter', 'Flurfrils']);

console.log(pepe.pets); // ['Baxter', 'Flurfrils']
```

Or adding a struct inside the other:

```javascript
/**
 * @typedef UserInfo
 * @property {string} phone
 * @property {number} age
 * @property {string} hairColor
 * @constructor
 */

/** @type {ObjectConstructor|any} */
const UserInfo = new makeStruct('phone, age, hairColor');

/** @type {UserInfo} */
const extraInfo = new UserInfo('555-777-888', 31, 'blonde');


/**
 * @typedef User
 * @property {number} id
 * @property {string} name
 * @property {string} country
 * @property {UserInfo} info
 * @constructor
 */

/** @type {ObjectConstructor|any} */
const User = new makeStruct('id, name, country, info');
/** @type {User} */
const John = new User(1, 'John', 'US', extraInfo);
```

Now we can do:

```javascript
John.country // 'US'
John.info.phone // '555-777-888'
```



Okay okay it's creating an object at the end but JavaScript is an object-based language just like Python and others, so in truth everything is an object.

And you can't say that this isn't funny!

<img src="https://y.yarn.co/edd14e42-8bc4-4266-96a1-b13f230b83b7_text.gif" />

<hr />
<p align="center">Do you like my content?</p>
<a href="https://www.buymeacoffee.com/joelbonetr" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>