0

I got the following snippet from this link: https://www.gkogan.co/blog/save-url-parameters/

<script>
  var queryForm = function(settings){
    var reset = settings && settings.reset ? settings.reset : false;
    var self = window.location.toString();
    var querystring = self.split("?");
    if (querystring.length > 1) {
      var pairs = querystring[1].split("&");
      for (i in pairs) {
        var keyval = pairs[i].split("=");
        if (reset || sessionStorage.getItem(keyval[0]) === null) {
          sessionStorage.setItem(keyval[0], decodeURIComponent(keyval[1]));
        }
      }
    }
    var hiddenFields = document.querySelectorAll("input[type=hidden], input[type=text]");
    for (var i=0; i<hiddenFields.length; i++) {
      var param = sessionStorage.getItem(hiddenFields[i].name);
      if (param) document.getElementsByName(hiddenFields[i].name)[0].value = param;
    }
  }

  setTimeout(function(){queryForm();}, 3000);
</script>

In short, this code is intended to get link parameters like utm_source and save it to the sessionStorage. What I don't understand is the following line that the tutorial doesn't explain:

var reset = settings && settings.reset ? settings.reset : false;

What does this syntax mean?

WoolfDall
  • 29
  • 7
  • 1
    It's a [ternary condition](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator). – Mitya May 13 '20 at 20:21

2 Answers2

0
?:

This is javascript ternary operator. Your code is equivalent to the code below

var reset;
if (setting && settings.reset) {
    reset = settings.reset;
} else {
    reset = false;
}
TSR
  • 9,145
  • 14
  • 51
  • 114
0

It’s doing a null-coalesce using a ternary operator. Basically it assigns whatever reset is if it exists or the Boolean value false.

More ternary operator here: What does the colon ":" and the question mark "?" operators do?

Martin
  • 350
  • 1
  • 9