Suppose I have a JavaScript function. and it contain a variable x;
function A(){
var x = 12+34;
}
Is it possible to access x from outside function x?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
No, the ability to do so would not make any sense. Suppose we changed your function slightly and called it 3 times:
At this point, the function has run 3 times, so the variable
xhas been created 3 times — whichxwould you expect to be able to access? Then there’s garbage collection; how could references and data be cleared from memory if the browser had to keep variables alive once they’re no longer in scope?If you want to, you can do something like this:
or, if the variable will be static/constant as you have it
or finally, as others have pointed out, by declaring
xunder a different name outside of the function’s scope: