'Variable is not defined

I'm working on a jquery where user selects a category and then a range of years. my problem is I'm getting cats is not defined although it is, and I can see it using alert(cats); from $('[id^="multi-"]').click(function () {

but when i'm choosing the range of years, from $("#multi_select_wrapper").keyup(function(){ "cats" variable is not defined

$('[id^="multi-"]').click(function () {
            $(this).toggleClass('selected');
            var cats = [];
            $(".selected").each(function(){
                cats.push($(this).attr('data-id'));
            });
            var cats = cats.join(",");
            alert(cats);
    });

            $("#multi_select_wrapper").keyup(function(){
                    if(f_year!==null && t_year!==null){
                            var years = [];
                            var counter = parseInt(t_year)+1;

                            for (var i = f_year; i < counter; i++) {
                                    years.push(i);
                            }
                            alert(years);
                            alert(cats);
                    }
                    $("#multi_search").attr("href", "index.php?do=m&msc=" + cats + "&msy=" + years);
            });


Solution 1:[1]

cats is only declared inside your click handler function and is not given a value until that click handler runs. It's value is only available inside that function.

If you want cats available outside that function, then you must declare cats at a higher scope (e.g. perhaps as a global variable or some higher scope). Then, it's value could be used anytime AFTER the click handler function runs.

In addition, you shouldn't be declaring the cats variable twice in your click handler. This won't cause an error, but it is incorrect. Declare it with var only once per scope.

Solution 2:[2]

The problem is the variable scope. You need to move var cats = []; outside of the first function

Solution 3:[3]

You actually CAN, if you prefer to, define globally accessible variables from within a function by appending them to the window object.

window.cats = window.cats ?? []; /* scope 1 */

if (window.cats) { ... /* scope 2 */

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jfriend00
Solution 2 Graham Walters
Solution 3