By grecdev

2020-01-14 13:12:29 8 Comments

i want to know if i can set the same value for multiple keys in the following:

  1. React functional component state:
const [state, setState] = useState(
key1: 'same-value',
key2: 'same-value',
key3: 'same-value'
  1. React class component state:
state = {
 key1: 'same-value',
 key2: 'same-value',
 key3: 'same-value'
  1. Javascript object:
const state = {
 key1: 'same-value',
 key2: 'same-value',
 key3: 'same-value'

I want to know if something like this is possible:

const state = {
 state1, state2, state3: 'same-value';


@T.J. Crowder 2020-01-14 13:16:28

I want to know if something like this is possible

Not in an object literal, no. You can do it after creating the object:

const state = {};
state.key1 = state.key2 = state.key3 = 'same-value';

Or you could make key2 and key3 accessor properties for key1, meaning they'd track its value (change key1, and you see the change in key2 and key3), because although using them looks like a simple property access, in fact it's a function call.

const state = {
    key1: 'some-value',
    get key2() { return this.key1; },
    get key3() { return this.key1; }
console.log(state.key1); // 'some-value'
console.log(state.key2); // 'some-value'
console.log(state.key3); // 'some-value'

I'm not suggesting that, just noting it's possible.

@grecdev 2020-01-15 05:41:25

Ok thank you, another great lesson learned from stack community :)

Related Questions

Sponsored Content

96 Answered Questions

[SOLVED] How can I remove a specific item from an array?

  • 2011-04-23 22:17:18
  • Walker
  • 6821943 View
  • 8405 Score
  • 96 Answer
  • Tags:   javascript arrays

61 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

27 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

42 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

22 Answered Questions

[SOLVED] Checking if a key exists in a JavaScript object?

3 Answered Questions

45 Answered Questions

[SOLVED] Detecting an undefined object property

67 Answered Questions

[SOLVED] What is the most efficient way to deep clone an object in JavaScript?

54 Answered Questions

Sponsored Content