eslint-plugin-unicorn icon indicating copy to clipboard operation
eslint-plugin-unicorn copied to clipboard

Rule proposal: prefer-direct-value-assignment

Open BridgeAR opened this issue 6 months ago • 1 comments

Description

I have stumbled upon code a couple of times that first assigns an array and then pushes values unconditionally. That is not ideal, since it requires the array to potentially resize right away and change its internal shape, while also making it less readable and more verbose. Instead, just assign the values directly. The same applies to objects with properties.

Examples

// ❌
const foo = {}
foo.array = []
const random = Math.random()
foo.array.push(42)

// ✅
const foo = {
  array: [42]
}
const random = Math.random()

Proposed rule name

prefer-direct-value-assignment prefer-concise-values

Additional Info

No response

BridgeAR avatar Jun 10 '25 11:06 BridgeAR

An immediate update makes sense to apply.

// ❌
const foo = {}
foo.array = []

// ✅
const foo = {
  array: []
}

But after another call doesn't, it's hard to know what's done there.

fisker avatar Jun 10 '25 11:06 fisker

This got superseded by https://github.com/sindresorhus/eslint-plugin-unicorn/issues/2775

BridgeAR avatar Nov 03 '25 09:11 BridgeAR

Sorry that I forgot about this one when I open #2775

fisker avatar Nov 03 '25 10:11 fisker