0

Is there a way to access a variable outside of the function that it's declared in?

var checkWidth = function () {
  var $width = $(window).width();
}

$(window).on('resize', checkWidth);

// access $width here with the value from the resize

Solution:

var $width = $(window).width();

$(window).resize(function () {
  var $resizeWidth = $(window).width();

  updateWidth($resizeWidth);

});

function updateWidth(a) {
  width = a;

  // use the new width here
}

3 Answers3

1

You actually can in this way:

var width;

var checkWidth = function () {
    width = 150;
}

checkWidth();
console.log(width);

width will be 150 in the logs

alexr
  • 299
  • 1
  • 9
1

There are two ways, actually.

You could declare it outside of the function to set its scope there, like this:

var $width;
var checkWidth = function () {
  $width = $(window).width();
}

$(window).on('resize', checkWidth);

Or, you could just omit the declaration to give it global scope:

var checkWidth = function () {
  $width = $(window).width();
}

$(window).on('resize', checkWidth);

Either way, you'll now be able to access it outside of the function, and its value will be undefined until you call the function.

(With that second one, you might get a ReferenceError due to ES5: see this question.)

Community
  • 1
  • 1
AstroCB
  • 12,337
  • 20
  • 57
  • 73
0

The $width variable only exists within the scope of your checkWidth function. You must declare this variable in the global scope before invoking checkWidth() if you would like to access it outside of that checkWidth scope.

Liam Schauerman
  • 851
  • 5
  • 10