Skip to content

An object key shouldn't need to be declared before an assignment that specifies it. #5339

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
fernandortdias opened this issue Dec 23, 2020 · 2 comments

Comments

@fernandortdias
Copy link

fernandortdias commented Dec 23, 2020

Feature request

Input Code

a.b.c.d = 10 
alert("a.b.c.d = " + a.b.c.d)

Expected Behavior

a.b.c.d = 10

Current Behavior

error;

Possible Solution

var a;

if (typeof a === "undefined" || a === null) {
a = {};
}

if (a['b'] == null) {
a['b'] = {};
}

if (a['b']['c'] == null) {
a['b']['c'] = {};
}

if (a['b']['c']['d'] == null) {
a['b']['c']['d'] = {};
}

a.b.c.d = 10;

alert("a.b.c.d = " + a.b.c.d);

Context

As Coffeescript doesn't require variables do be declared before assigning values to them, I'd expect that a missing key in a object hadn't to be declared either before an assignment to that key. This way it would be much easier to represent a sparse matrices as objects.

I've got the "possible solution" above using this code in CoffeeScript:

a = {} unless a?
a['b'] = {} unless a['b']?
a['b']['c'] = {} unless a['b']['c']?
a['b']['c']['d'] = {} unless a['b']['c']['d']?

a.b.c.d = 10

alert("a.b.c.d = " + a.b.c.d)

Environment

  • CoffeeScript version: 2.5.1
  • Node.js version: N/A
@edemaine
Copy link
Contributor

The canonical solution to this is

a ?= {}
a.b ?= {}
a.b.c ?= {}
a.b.c.d = 10

Are you suggesting that a.b = 5 should automatically prepend a ?= {}? This seems likely dangerous and bad, as it's using JavaScript notation with a very non-JavaScript meaning.

I could imagine a different operator like a!.b = 5 (or some other notation) that automatically does a ?= {} before a.b = 5, though.

@vendethiel
Copy link
Collaborator

Duplicate of #2610, #1870, #1642, #1394, and somewhat #1141 & #881.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants