Javascript tip: Place brackets within braces when declaring an array

Recently, I came across a code snippet that is new to me and I'm having trouble finding an explanation for it online:

function segColor(c) {
    return {
        red: "#FF0000",
        green: "#00ff00",
        blue: "#0000ff"
    }[c];
}

I'm curious about the operation being performed on the function parameter c. Can someone explain what {array}[val] does in JavaScript? My searches for "brackets after braces" haven't turned up much information.

Answer №1

In this code snippet, the variable c is used as a property accessor to the object. The function segColor serves as a static mapper that returns the corresponding color value based on the input color word.

function segColor(c) {
    return {
        red: "#FF0000",
        green: "#00ff00",
        blue: "#0000ff"
    }[c];
}

console.log(segColor('green'));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to remove this specific element from an inherited hyperlink?

My website can be found at whensayfeed.meteor.com. Each post on the site is enclosed within an <a></a> element. The heart symbol on the right side of each post is intended to be a "like button" that users can click on. However, because it is ...

Error message encountered while using NEXJS Stripe v3:1 library: Unhandled promise rejection IntegrationError - Stripe() requires a valid apiKey in string format

v3:1 IntenationalIssue: Stripe() is requesting a missing value - apiKey must be a string. Encountering this issue in my Next JS project while attempting to implement a pre-built checkout with stripe. .env.local (full key has been replaced with ..... for ...

Configuration for secondary dependencies in Tailwind

As per the guidelines outlined in the official documentation, it is recommended to configure Tailwind to scan reusable components for class names when using them across multiple projects: If you’ve created your own set of components styled with Tailwin ...

Retrieve a collection containing all the variables that have been defined

I am attempting to gather all PHP defined variables and store them in an array. Previously, I tried: $myArr = get_defined_vars(); var_dump($myArr); The result was: array(4) { ["_GET"]=> array(0) { } ["_POST"]=> array(0) { } ["_COOKIE"]=> array ...

"Is there a way to ensure that jPlayer plays the same song even after a page refresh

I have been working on integrating jPlayer with Ajax to ensure that when the page of my website is refreshed, jPlayer will continue playing its current song seamlessly. I have successfully stored track information and the current track during refresh, ho ...

Repeating Elements with Angular and Utilizing a Touch Keyboard

Currently, I am developing a table with various fields and the ability to add new rows. The goal is to display all the inputted data at the end. This application is specifically designed for touch screen monitors, so I have created a custom keyboard for in ...

The empty string is not getting recognized as part of an array

Currently, I have a textarea field where pressing enter submits and creates a new item in the array. Pressing shift + enter creates a new line in the textarea input field. But when trying to submit by pressing shift and enter after creating a new line, it ...

The command 'vue' is not a valid internal or external command

After ensuring that everything was installed correctly, I encountered an issue when trying to create a project. An error message would appear stating that "'vue' is not recognized as an internal or external command". I attempted to reinstall the ...

Python: Ultimate Collection of Basic Ordinary Least Squares

My goal is to create a comprehensive dictionary that contains multiple lower level libraries. Idea I have collected interest rates from my retail bank over the past 12 years and want to analyze them by using a variety of bond portfolios. Regression Mode ...

Is there a way to inform TypeScript that the process is defined rather than undefined?

When I execute the code line below: internalWhiteList = process.env.INTERNAL_IP_WHITELIST.split( ',' ) An error pops up indicating, Object is possibly undefined. The env variables are injected into process.env through the utilization of the mod ...

Is it possible to create an index for an associative array based on a string in JavaScript?

Within my JavaScript code, I am working with an associative (two-dimensional) array (myObj[x][y]). Each row in this array contains a different number of elements denoted by 'n', where the first value signifies the amount 'n' as shown be ...

Can JavaScript be used to determine if any code has been executed from the browser's console?

I'm currently developing a JavaScript game and I want to prevent cheating. Is there a way for me to track and record commands entered in the JavaScript console? Here's a basic outline of what I have in mind: consoleCommands = ""; window.console ...

Using npm to install packages with multiple package.json files

My current project includes a submodule with another submodule, each having their own package.json file. This is how I set up my project: |root ----|node_modules ----|package.json ----|someFolder ----|submodule_1 -------- |package.json -------- |someFold ...

Error occurs when applyMatrix is used after scaling in three.js

The issue: I am currently in need of updating the vertex positions on a mesh after scaling it. This update is necessary for me to accurately calculate the volume of the mesh. To maintain scale as an active parameter in the original mesh, I have created a c ...

Modifying various items depending on the variable's value

I'm attempting to adjust various variables depending on which button the user clicks. For instance, there are three buttons: <button id="button1" onclick="isClicked(this.id)">B1</button> <button id="button2" onclick="isClicked(this.id) ...

Create Mesh from Three.js Points

I'm attempting to create an interactive shape in Three.js by using points generated from mouse clicks. Below is the code that I currently have: mouse.x = ( ( event.clientX - renderer.domElement.offsetLeft ) / player.width ) * 2 - 1; mouse.y = - ( ( ...

In Firefox, using $().focus to target a textarea does not yield the intended results

Here is the problem recreated: http://jsfiddle.net/Rc52x/5/ In Chrome, when you click on Click here!, the textarea gains focus and allows typing. However, in Firefox (version 3.6.15), clicking on it does not give focus to the textarea and typing has no e ...

What is the best way to load an ExtJS combobox with a JSON object that includes an array

After retrieving the following JSON from the backend: { "scripts": [ "actions/rss", "actions/db/initDb", "actions/utils/MyFile", "actions/utils/Valid" ], "success": true } The JSON data is stored as follows: t ...

Refresh the flatlist to display new content without uploading items automatically

When I click the save button in my FlatList component within React Native, the data does not reload automatically or render in the FlatList. However, if I manually reload the app, the saved item appears. I've tried various methods to make the data re ...

Exploring Angular: How does Number.isNaN handle non-empty strings?

Within my component, there is a dropdown menu that allows users to choose a value. Upon selecting an item from the dropdown, a function called onDropdownChange is triggered. The parameter passed to this function can either be a string ("Please select an op ...