0

What is meaning of typedef $ in following source code. I have read from this link.

typeof allows the identifier to never have been declared before. So it's safer in that regard:

But here they are using if (typeof $ !== 'undefined'), what is meaning of $ here.

I copied following code from this link

<script type="text/javascript">
  if (typeof horizon.d3_line_chart !== 'undefined') {
    //alert("test1");
    //When first time It give alert means it is defiend 
    horizon.d3_line_chart.init("div[data-chart-type='line_chart']",
      {'auto_resize': true});
  }

  if (typeof $ !== 'undefined') {
    //alert("alert2");
    /*
      We first time we run resource usage, then It will show alert, and date options are not showing. So means first time It hides the date options. Means '$' varaible is defined.
    */
   show_hide_datepickers();
  } else {
    addHorizonLoadEvent(function() {
      show_hide_datepickers();
    });
  }

  function show_hide_datepickers() {
    $("#date_options").change(function(evt) {
        // Enhancing behaviour of selectbox, on 'other' value selected, I don't
        // want to refresh, but show hide the date fields
        if ($(this).find("option:selected").val() == "other"){
          evt.stopPropagation();
          $("#date_from input, #date_to input").val('');
          $("#date_from, #date_to").show();
        } else {
          $("#date_from, #date_to").hide();
        }
    });
    if ($("#date_options").find("option:selected").val() == "other"){
      $("#date_from, #date_to").show();
    } else {
      $("#date_from, #date_to").hide();
    }
  }
</script>
Community
  • 1
  • 1
Neelabh Singh
  • 2,600
  • 12
  • 51
  • 88

2 Answers2

3

In Javascript, $ is just a variable name so:

if (typeof $ !== 'undefined')

is just checking to see if the $ variable is already defined or not. In code that uses jQuery, the $ sign is usually an alias for the jQuery object so this code would be checking to see if jQuery was present or if jQuery was using the $ symbol or not.

You don't show us the addHorizonLoadEvent() code, but logic would suggest that maybe it is responsible for loading jQuery or for knowing when a set of stuff that includes jQuery has finished loading and it is used if the code finds that whatever loads $ has not yet finished loading.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

In your case, the author is just checking if some libraries are present and loaded :

  • (typeof $ !== 'undefined') --> A library using $ (JQuery in your case)
  • (typeof horizon.d3_line_chart != 'undefined') --> A chart library?

This allow to do some code if a library was loaded and don't crash if it wasn't. Could also be used to be able to use different library, if one isn't present try another.

Michael Laffargue
  • 10,116
  • 6
  • 42
  • 76