Is there a better way to write if (argList[foo] === "bar" || argList === "bar")?

Viewed 101

I have an if statement :

if (argList["foo"] === "bar" || argList === "bar"){
    // some code
}

I want to know if there is a shorter or more elegant way to write this condition.

Why i write this statement like this ? I have a function called startTool(argList), and another called startCreate(argList).

mod.zsh_apiStartTool = function(argList, callback) {
  
        // some code
  if (argList["tool"] === "measure" || argList === "measure"){
   //some code to start the tool
  }
  if (argList["tool"] === "scanning"|| argList === "scanning"){
   // some code to start the tool
  }
  ZSH_JS_API_ERROR(callback);
  return;
 }

mod.zsh_apiStartCreate = function(argList, callback) {
  
        // some code
  if (argList["tool"] === "measure"){
   mod.zsh_apiStartTool("measure")
  }
  if (argList["tool"] === "scanning"){
   mod.zsh_apiStartTool("scanning");
  }
  ZSH_JS_API_ERROR(callback);
  return;
 }

So when i run into startTool from startCreate, my var isn't argList["foo"] === "bar" but argList === "bar"

1 Answers

To be sure that a property exists IMHO is better to use an helper as:

  • typescript elvis case
  • Lodash _.get() method

    if (_.get(argList, "foo") === "bar" || argList === "bar"){ // some code }

The problem is critical only if you try to access to a deeper level like argList["foo"]["bar"]

JSON.stringify

Another option can be stringify the object and seek the value here, if you know that "bar" is a deterministic value in your object (so there is no other properties that can hold it in argList):

JSON.stringify(argListObj).includes("bar")

const argListObj = { foo: "bar" };
const argListString = "bar";
console.log(JSON.stringify(argListObj).includes("bar"));
console.log(JSON.stringify(argListString).includes("bar");

// Console logs true, true

Related