DEV Community

loading...

Setting Dynamic Variables/Properties in Javascript

James 'Tucker' Wray
|Postgres Express React Node|. Codesandbox is my jam. Pairprogramming is sweet. Smooth view transitions get me all worked up. Latest Endeavours include AWS docker Typescript GraphQL.
・2 min read

I became overwhelmed while trying to learn redux, because not only was I learning Redux-- I was also learning higher level concepts of JavaScript intertwined with the Redux module.

Topics included:

how to verbalize a definition for what state really even meant without using the word 'state'
how state differed from props, the concept of immutability
why you would want to maintain immutability when working with state
how to maintain immutability when working with state
how to use switch-cases or to use the spread operator of ESNext
why you would want to 'rewind state'
Lets not forget the topic of today's blog: how to select object properties dynamically such as when setting action payloads to the values of a state slice in Redux Reducers.

This technique saved me a lot of time when creating reusable forms with functions for storing and updating state including handler functions such as a change-handlers or submit-handlers. I found the dynamic bracket notation useful many times when I was using a spread operator to duplicate or make a copy of an object or array
This is a shorthand and I didn't understand how simple it was for the longest time.

I found the following snippet on a Google Search. It cleared things up for me in the flash of another light-bulb moment.
You can also set dynamic properties with the bracket syntax:

var property="test";
var obj={
[property]=1;
};

console.log(obj.test);//1
It does the same as:

var property="test";
var obj={};
obj[property]=1;
Naming conventions and variable name choices are essential for developers to understand and efficiently work with your codebase. I am torn between assessing the var name choices here as muddy and obscure or expertly declarative.

First we have a string assigned to the var 'property' followed by a JavaScript object {} assigned to the var 'obj'. Our JS object 'obj' contains a single key:value pair or object \n named 'property'.

where the objects sole property is actually assigned to be called by the variable " property ".

What we are creating here is actually the ability to create numerous key value pairs on the object "obj".

by reassigning the value of our var "property", we are able to create a new key:value pair on "obj".

var property="propertyNumber2"
print(obj)
yields {"test":1,"propertyNumber2":1}

example retrieved and reshared from https://riptutorial.com/javascript/example/2321/dynamic---variable-property-names#

Discussion (0)