'jquery - use a variable outside the function

How I Can use a variable outside the function where it was declared?

$(function() {
    function init() {
        var bwr_w = $(window).width();
    }
    init();
    $('#button').click(function() {
        alert('The Browser Height is' + bwr_w);
    });
});

If I click on the button I get this error:

bwr_w is not defined



Solution 1:[1]

Just declare that variable in constructor's scope:

$(function() {
    var bwr_w = null;

    function init() {
        bwr_w = $(window).width();
    }

    init();

    $('#button').click(function() {
        alert('The Browser Height is' + bwr_w);
    });
});

Solution 2:[2]

try this

$(function() {
  var bwr_w = 0;
  function init() {
    bwr_w = $(window).width();
  }
  init();
  $('#button').click(function() {
    alert('The Browser Height is' + bwr_w);
  });
});

Solution 3:[3]

If you declare the variable outside the function, then assign a value to it inside the function, it should be accessible elsewhere. So long as you're sure that a value will be assigned. If you're not sure, you might want to assign a default value:

$(function() {

        var bwr_w; // or 'var bwr_w = default_value;'

    function init() {
        bwr_w = $(window).width();
    }
    init();
    $('#button').click(function() {
        alert('The Browser Height is' + bwr_w);
    });
});

Solution 4:[4]

Try this

  $(function() {
    var bwr_w_var = function() {
        let bwr_w = 'stack overflow';
        return bwr_w;
    };
    function() {
        let bwr_w = bwr_w_var();
        console.log(bwr_w);
    };
  });

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
Solution 2 Andrei Andrushkevich
Solution 3 David Thomas
Solution 4 Joukhar