Search code examples
javascriptecmascript-6ecmascript-5conditional-operator

Trouble understanding javascript syntax: if (parameter == "someValue") parameter = ""


I'm having trouble understanding this JS syntax:

function myFunction(a) {
  if (a == "someValue") a = ""; 
}

Is this some sort of shorthand? As in: if "a" is equal to "someValue", then set "a" to be empty?


Solution

  • That's just a standard if statement without the curly braces. Your code is basically the same as this:

    if (a == "someValue") {
      a = "";
    }
    

    A shorthand would be using something like a ternary operator like this:

    a = (a == "someValue") ? "" : a;
    
    // if "a" is loosely equal to "someValue", then assign an empty string to "a",
    // else leave "a" unchanged by assigning it to it's current value.