Life4ants
Life4ants

Reputation: 693

Javascript: shortcut syntax for conditional check?

Say I have a function that needs to check for a match with one of two different values. However, the input is very complicated:

function checker(id, value){
  if (this.state.users[id].items[value].name === 'onething ' ||
    this.state.users[id].items[value].name === 'theotherthing ' ){
    // my action
  }
}

What I end up doing is this:

function checker(id, value){
  var name = this.state.users[id].items[value].name
  if (name === 'onething ' || name === 'theotherthing '){
    // my action
  }
}

Is there any way to do something like this:

function checker(id, value){
  if (this.state.users[id].items[value].name === 'onething ' || 'theotherthing '){
    // my action
  }
}

Obviously the second method takes less typing and is easier to refactor than the first one. How do they compare memory/speed wise?

Upvotes: 0

Views: 125

Answers (3)

Dan Ionescu
Dan Ionescu

Reputation: 3423

In ECMAScript 2016 you can do something like:

if (['onething ','theotherthing'].includes(this.state.users[id].items[value].name)) {
    //do stuff
}

The statement is composed of the following parts:

  1. the if statement (obviously)

  2. an array definition: ['onething ','theotherthing']

  3. calling the method includes() on the previously defined array.

In javascript an array is an object that has methods like any other object. One of those methods is includes() which checks that the argument is contained inside the array. The return type of this method is boolean so it's directly evaluated by the if statement without any casting

More about includes() method here

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386726

You could use Array#indexOf and test against -1

if (['onething ', 'theotherthing '].indexOf(this.state.users[id].items[value].name ) !== -1){

Upvotes: 3

trincot
trincot

Reputation: 350766

You could use object notation:

if (this.state.users[id].items in {"onething ":1, "theotherthing ":1}){

Or, a regular expression could also work -- shorter, but less efficient:

if (/onething |theotherthing /.test(this.state.users[id].items)){

Upvotes: 0

Related Questions