Corey
Corey

Reputation: 133

Arguments before a colon

I'm trying to pass an argument to a function in Javascript. However, the argument column is being interpreted as a literal string as opposed to an argument to the function. This is due to the colon directly following the argument column:

    update(column, selected) {
          var cols = {...this.props.columns, column: selected}
          this.props.dispatch(updateColumns({type: "UPDATE_COLUMNS", cols}))
    }

I've tried using arguments[0] instead of column but then I am told arguments is a reserved word in strict mode. Any idea how I can get read this value as an argument as opposed to a string?

Upvotes: 0

Views: 280

Answers (1)

Pointy
Pointy

Reputation: 413717

In modern JavaScript environments, object initializer syntax allows for expressions to be evaluated on the left side of the property initialization:

update(column, selected) {
      var cols = {...this.props.columns, [column]: selected}
      this.props.dispatch(updateColumns({type: "UPDATE_COLUMNS", cols}))
}

The square brackets mean that the expression inside should be evaluated, and the result should be used as the property name.

In older environments, you'd have to do it in a separate statement, but since you're already using spread syntax I'd guess you're not concerned with that.

Upvotes: 1

Related Questions