Copy link to clipboard
Copied
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?
Copy link to clipboard
Copied
See Javascript's scopes :
Copy link to clipboard
Copied
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
Copy link to clipboard
Copied
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
$.writeln(globalVar);
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();
$.writeln(outsideVar);
function testFunctionWithReturn() {
var localVar = 15;
return localVar;
}