0

Newbie here. I'm working with some JavaScript (JQuery in this case) that is meant to reveal elements on the page when a button is clicked.

It looks like some variables (eg. "$lis", "min", "max") are not declared with "let" or "var". My understanding is that this sets them as global variables, but I don't see any reason to set them as such in this case.

Can someone help me understand why "$lis", "min", and "max" do not include "var", but "visible" does? Thank you!

$( document ).ready(function() {
    jQuery(function($) {
        $lis = $('.blog-page-post'); 
        min = 2;
        max = $lis.length;
        var visible = min;

        function showUpToIndex(index) {
            $lis.hide();
            $lis.slice(0, index).show();
        }

        function disableButtons(){
            if (visible >= max){
                visible = max;
                $('.button').hide();
            }
            else
            {
                $('.button').show();
            }
        }

        showUpToIndex(visible);
        disableButtons();

        $('.button').click(function(e) {
            e.preventDefault();
            visible = visible + 2;
            disableButtons();  
            showUpToIndex(visible);
        });
    });
    });
FlightPlan
  • 43
  • 1
  • 8

1 Answers1

1

You have to use use strict (Strict Mode - MDN) to handle these edge cases.

In your case, when you assign to undeclared variable like this:

abc = true

then it transforms to this:

window.abc = true

bekliev
  • 2,331
  • 2
  • 12
  • 11