Skip to content

Bug: no-new-object has incorrect advice when Object constructor is called with an argument #17517

@fasttime

Description

@fasttime

Environment

Node version: v20.4.0
npm version: v9.7.2
Local ESLint version: v8.48.0 (Currently used)
Global ESLint version: Not found
Operating System: win32 10.0.19045

What parser are you using?

Default (Espree)

What did you do?

/* eslint no-new-object: "error" */
 
var obj = new Object(2);
assert.equal(typeof obj, "object");
assert.equal(obj * obj, 4);

What did you expect to happen?

No error, or a different error message.

What actually happened?

3:11 The object literal notation {} is preferable. (no-new-object)

The advice to use a literal like {} is not applicable when the Object constructor is called with an argument, as in the above example. According to the relevant specification, calling new Object(value) will convert the provided argument into an object, as specified in the ToObject conversions table. To my knowledge, this result cannot be achieved using object literal notation.

Link to Minimal Reproducible Example

https://eslint.org/play/#eyJ0ZXh0IjoiLyogZXNsaW50IG5vLW5ldy1vYmplY3Q6IFwiZXJyb3JcIiAqL1xuIFxudmFyIG9iaiA9IG5ldyBPYmplY3QoMik7XG5hc3NlcnQuZXF1YWwodHlwZW9mIG9iaiwgXCJvYmplY3RcIik7XG5hc3NlcnQuZXF1YWwob2JqICogb2JqLCA0KTtcbiIsIm9wdGlvbnMiOnsiZW52Ijp7fSwicnVsZXMiOnt9LCJwYXJzZXJPcHRpb25zIjp7ImVjbWFGZWF0dXJlcyI6e30sImVjbWFWZXJzaW9uIjoibGF0ZXN0Iiwic291cmNlVHlwZSI6Im1vZHVsZSJ9fX0=

Participation

  • I am willing to submit a pull request for this issue.

Additional comments

I am not sure about the fix in this case. One option is to change the message of the problem, and simply recommend to avoid using the object constructor, but at that point I think that the rule would be no longer considered stylistic.

Alternatively, Object(value) is semantically equivalent to new Object(value), and not forbidden by any rule, so that could be also an option.

Another solution is to change the current behavior and stop reporting a problem when new Object() is called with an argument. This was suggested in a previous issue, but the discussion was not conclusive: #11810.

Ideas?

Metadata

Metadata

Assignees

Labels

acceptedThere is consensus among the team that this change meets the criteria for inclusionarchived due to ageThis issue has been archived; please open a new issue for any further discussionbugESLint is working incorrectlyrepro:yesIssues with a reproducible exampleruleRelates to ESLint's core rules

Type

No type

Projects

Status

Complete

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions