Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable scope in functions

I have a SCOPE problem. When I declare "var text" outside the function all works. But inside the function it works only in the first part. Here is what I mean:

This is a buffer function. Executing buffer("anything") saves "anything". Executing buffer() - without the properties will return all properties.

  • buffer("Al")
  • buffer("ex")
  • buffer() <= should return Alex

But the SCOPE of "text" is wrong and it does not return the saved properties.

  function makeBuffer() {
    var text = "";
    if (arguments.length != 0) {
      for (let i = 0; i < arguments.length; i++) {
        console.log(`Adding argument - (${arguments[i]})`);
        text += arguments[i];
        console.log(`New text - (${text})`);
      }
    } else {
      console.log(`text - (${text})`);
      return text;
    }
  }
  var buffer = makeBuffer;


  buffer("One", "Two");
  document.write(buffer());
like image 839
Alexey Tseitlin Avatar asked Mar 27 '26 15:03

Alexey Tseitlin


1 Answers

That is normal behaviour.

A variable defined in a given scope goes away when the scope goes away. Each call the to the function creates a new scope.

Declaring the variable outside the function is the standard way to share a value between invocations of it.

like image 84
Quentin Avatar answered Mar 30 '26 05:03

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!