3 Replies Latest reply on May 14, 2018 5:58 PM by sidpalas

    inside/outside function array.length

    Polycontrast Level 1

      I have a function with an array which alerts the array.length inside the function block. However, I am unable to alert the array.length outside the function.

      Is there away to alert the array.length outdide the function?

        • 1. Re: inside/outside function array.length
          Loic.Aigon Adobe Community Professional

          See Javascript's scopes :

          JavaScript Scope

          • 2. Re: inside/outside function array.length
            Polycontrast Level 1

            I have run into a limitation with the local variable scope.

            In the example below is it possible to pass the value of the local variable to another variable outside the function?


            var global = 10;

            var fromLocal = local // possible?


            function scope() {

               var local = 5;


            alert(local);  // produces undefined

            • 3. Re: inside/outside function array.length
              sidpalas Level 2

              As Loic.Aigon implied, this is less of a Photoshop Scripting question and more of a general Javascript question.


              There are multiple ways to accomplish something similar to what you describe and without knowing your specific use case it is difficult to recommend the best approach. In general, you want to keep variables to the minimum scope possible while still accomplishing the task at hand. This helps prevent cases where global variables are edited in multiple places throughout a program which can lead to nasty bugs that are hard to track down.


              With that warning in place, if you still want to use a global variable, this is how you would do it:


              var globalVar  = 10; //Defined outside the function so it becomes global
              $.writeln(globalVar); //You could use alert() here if you aren't using ExtendScript ToolKit
              testFunction(); //Call the function
              function testFunction() {
                  globalVar = 5; //Do not use the "var" keyword or it will declare a local variable with the same name


              A better option may be to have the function return the variable you want to use elsewhere. For example:


              var outsideVar = testFunctionWithReturn();
              function testFunctionWithReturn() {
                  var localVar = 15;
                  return localVar;