CodingTrain / CodingTrain/Wave-Function-Collapse

How to use constants as Object keys

Open
#35 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
218
Forks
64
PR merge metrics
No merged PRs in 30d

Description

At [22:24](https://youtu.be/rI_y2GAlQFM?t=1365) in the video Dan tries to use his constants as the keys in the object but it doesn't work for him. This is because he did it wrong.

when he did it you ended up with an object that had the strings "UP", "DOWN", etc as the keys but you wanted it to be the numbers that those constants represented. The way that you do that is to put the variables in square brackets. For example.
```ts
const UP = 0;
const DOWN = 1;
const LEFT = 2;
const RIGHT = 3;

const object1 = {
UP: [],
DOWN: [],
LEFT: [],
RIGHT: []
}

const object2 = {
[UP]: [],
[DOWN]: [],
[LEFT]: [],
[RIGHT]: []
}

console.log(object1) => // {UP: Array(0), DOWN: Array(0), LEFT: Array(0), RIGHT: Array(0)}
console.log(object2) => // {0: Array(0), 1: Array(0), 2: Array(0), 3: Array(0)}
}
```
and here's an interactive example https://editor.p5js.org/D_Snyder/sketches/r7rHl0QuA

The term for this is Computed Property Names and more details can be found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names

Contributor guide

No contributing guide indexed for this repository

Research direction

Review the referenced video segment, the supplied p5.js example, and the MDN computed property names reference. Update the relevant project guidance to explain that square brackets use the constants' numeric values as object keys, then verify the corrected example matches the shown output.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
documentation
Issue type
Documentation
Difficulty
1/5
Estimated time
Under an hour
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.