Get variable value of a function without setting it globally - javascript

Is it possible to get a variable value inside a function without having to set it globally?
I know this is possible:
var testvalue;
function setTestValue(){
testvalue = 30;
}
if you console.log this outside the setTestValue function you will get: 30. Which is clear.
But is there also a possibility to have the same effect but without a global variable?
function setTestValue(){
var testvalue = 30;
}
console.log(testvalue); // will print undefined
The reason why I want this is because I can not change the Javascript file where this function is created. I can only read it and not write it so I need it a workaround.
PS. It might be that this question is already been aksed on stackoverflow but I could not really find it. So if there is, please provide the links to that question.Thanks!

This works (if you don't have var keyword before the variable in the function )
function foo() {
bar = 10; // variable without var comes under window scope so you can access them outside fuction
}
foo();// you have to call the function to set its value
alert(bar) // window.bar also gives 10

why not returning the var in the function:
function setTestValue(){
var testvalue;
do whatever to assign value
return testvalue;
}
console.log(setTestValue());

Related

If a variable is created within the scope of a function that returns a function that uses that variable. Is it possible to acces that variable outside

function creatPrintNumFunction()
{
var num= 12;
return function printNum()
{
console.log(num);
}
}
var printer = creatPrintNumFunction();
printer.num =13; //this part doesn't work but is there a way to access this Num variable Outside the creatPrintNumFunction, The printer function must be finding the num variable from somewhere.
printer();
So how can I get this code to print 13 instead of 12 most importantly with out changing any of the code of the createPrintNumFunction().
For more context on what I really need to use this theory for. I'm using an external module express-sessions in node.js that I don't want to change. There is this 'store' variable where all the sessions are stored that I need to access only problem is that it's created within a function.There is another way i could access it but it's not really convenient
Looking for something like this?
function creatPrintNumFunction() {
const f = function printNum() {
console.log(f.num);
};
f.num = 12; // set .num property to initial value
return f; // return function "printNum"
}
var printer = creatPrintNumFunction();
printer.num = 13;
printer();
printer.num = 42;
printer();
There is this 'store' variable where all the sessions are stored that I need to access only problem is that it's created within a function. There is another way i could access it but it's not really convenient
No there is no way to access store without modifying the code. And you shouldn't modify the code of an external module, because store is likely made inaccessible for a reason. Changing the code might result in a code base that would prevent you from updating the express-sessions.
Having the need to do that sounds like an XY-Problem.
If it is your code and you want to allow the variable to be accessed there are different ways to do that. You for sure could move var num outside of creatPrintNumFunction (as described in the answer of alonealgorithm but that breaks the encapsulation you had before. Whether that is a good idea or not depends on the actual use case. But you need to be aware that if you do that that every "print" function returned from creatPrintNumFunction then uses the same variable.
Let's say you don't want to move num out of the scope of creatPrintNumFunction because every "print" function returned from creatPrintNumFunction should have its own num variable.
What then you could do is to create another function (e.g. set) within creatPrintNumFunction that can change num and assign this function as a property to the function you return from creatPrintNumFunction.
function creatPrintNumFunction() {
var num = 12;
// both "set" and "printNum" create here
// have a closure over the same "num" variable
function set(val) {
num = val;
}
function printNum() {
console.log(num);
}
// the "set" function is assigned as a parameter to your
// printNum function
printNum.set = set;
return printNum;
}
var printerA = creatPrintNumFunction();
var printerB = creatPrintNumFunction();
printerA.set(13)
printerB.set(23)
printerA();
printerB();
The advantage of this approach is that you don't expose num and you can control in your set function how/if num can be changed.
So, the comment you wrote about printNum() function being able to access the num variable somehow is due to JavaScript closures. Closures are an important JavaScript topic which I would recommend looking at some online resources or this stackoverflow post JavaScript closures to learn about. Essentially when you return the printNum function from createPrintNumFunction, the printNum function will remember the num variable that was declared in createPrintNumFunction. But to answer your question of whether you can access the variable outside of the scope it was declared in, then the answer is no. An outer scope cannot access variables from an inner scope. Inner scopes can access variables from outer scopes. So, unless you are keeping track of the num variable from outside of the scope that it was declared in, you won't be able to access the value num holds outside of the scope it was declared in.
So, here you can change the value of num inside of the printNum function itself like this:
function creatPrintNumFunction() {
var num = 12;
return function printNum() {
num = 13;
console.log(num);
};
}
var printer = creatPrintNumFunction();
printer.num = 13; //this part doesn't work but is there a way to access this Num variable Outside the creatPrintNumFunction, The printer function must be finding the num variable from somewhere.
printer();
You could define a global variable that keeps track of the num variable. Then through the scope chain the value used inside of the printNum function for the num variable will resolve to the value your global variable currently contains like so:
var num = 12;
function creatPrintNumFunction() {
return function printNum() {
console.log(num);
};
}
var printer = creatPrintNumFunction();
num = 13; //this part doesn't work but is there a way to access this Num variable Outside the creatPrintNumFunction, The printer function must be finding the num variable from somewhere.
printer();
I'm sure there are other methods to go about this as well but I hope that one of the above methods fits your need.

Can you add a property to a JavaScript function inside the function body?

I know that you can do this:
var someFunc = function(){
//do something
}
someFunc.newProperty = "blah";
However, this doesn't seem to do the same thing.
var someFunc = function(){
var newProperty = "blah";
//do something
}
In the second case, if I try to call someFunc.newProperty, that doesn't seem to return "blah". What is the difference?
What is the difference?
In the first case you are assigning a property to the function object. In the second case you are defining a local variable inside the function, which only exists when the function is executed. Local variables do not magically become properties of the function object.
If you give the function a name, you can easily assign a property to it:
var someFunc = function name() {
name.newProperty = "blah";
//do something
}
But the property still won't exists until the function is executed. So,
someFunc.newProperty;
doesn't work, but
someFunc();
someFunc.newProperty;
does.
In the first case, newProperty is an attribute of the someFunc object. In the second case newProperty is a local variable, which means it gets placed on the stack during function execution and disappears afterwards.

Variable undefined when set inside a function

function setx(){
var x = 'foobary bazer'
showit();
}
function showit(){
console.log(x);
}
setx();
In the above example, the showit function fails because x is undefined. However, x is set and is available in memory (or so I thought) before showit is called. Why is this not the case?
Also, what's the best way to make this code work, so the console.log does indeed print foobary bazer to the console? I could get rid of the var and make it a global, but I don't think this is the best way as it can cause strange bugs.
You could pass the x variable to the showit function:
function setx(){
var x = 'foobary bazer'
showit(x);
}
function showit(x){
console.log(x);
}
setx();

this versus function property in javascript

I want to create a static variable in my js. From what I know with my little js knowledge is, I can do it using this two ways.
function foo (){
if (this.counter==undefined){this.counter=1}
else {this.counter++ } ;
}
function foo (){
if (foo.counter==undefined){foo.counter=1}
else {foo.counter++ } ;
}
Are these two things essentially the same or I need to to careful in selecting one versus other.
Another question I have is: why var is not needed when doing these?
No, they are not equivalent. In your first example, you are using this. this can actually change depending on how the function is being called.
function showThis(){
console.log(this);
}
var obj = { };
obj.showThis = showThis;
showThis(); // gives 'window', or the top-most scope of your page
obj.showThis(); // gives obj as 'this'
If you are always calling the function the same way, then this would just mean the value counter is tracked as a property on window.counter. This is bad, because you may accidentally have an actual variable named counter in that scope, that you are now using in a different way somewhere else. If you are not calling it the same way everytime, then this will be different and probably not giving you your desired behavior.
If you are trying to keep a count on the number of times foo is being called, independent of how/who is calling it, then your second approach is more appropriate. For the sake of code clarify/convention, I would write it this way:
function foo (){
// If counter does not exist, create it and initialize it to 0.
foo.counter = foo.counter || 0;
foo.counter++;
}
foo.counter; // undefined, since foo has never been called yet
foo();
foo.counter; // is now 1
var is used to create a variable in the current scope.
Both the approaches you are taking are setting a property on an object that exists in a wider scope.

Javascript assign variable to alert

I am wondering Can you assign a variable to alert ? what does it really mean and do ? For example,
var a = alert('test');
I tried it out, and the alert pops up as soon as the page loads where variable a remains 'undefined' when I call it. Aren't we suppose to make it an anonymous function with the alert inside like
var a = function(){ alert('test'); }
If we want to trigger an alert on something? Why does javascript allow you to do that?
var a = alert('test');
Think of this statement like any other variable assignment. In order to perform the assignment, first the right-hand side is evaluated. In this case it's a function call, so the function is called and its return value is obtained. In alert's case, the return value is undefined. It doesn't return anything.
Then the return value is assigned to a, so a ends up with the value undefined.
As a side effect of the statement, an alert message is displayed. That happens as a consequence of calling alert() and getting its return value.
function foo(x) {
return x * 2;
}
var a = foo(3);
This code is structurally similar to the alert call, and would result in a being 6. But then alert() doesn't return a value. It's more like this:
function bar(x) {
return;
}
var a = bar(3);
Now a is undefined.
var a = alert('test');
This says to execute alert('test') and assign the return value from that function to a variable named a.
This would be no different than:
var max = Math.max(1,2,3,4);
where max would end up with the value 4 in it as the return value from executing Math.max(1,2,3,4).
var a = function(){ alert('test'); }
This says to declare an anonymous function and assign that function object to the variable a. Since the function is just declared, it is not executed at this time. You can execute it in the future with a().
You commented:
I am just wondering why javascript allows we to do that if it doesn't really means anything
Well, JavaScript (and any other language, including English) allows you to do a lot of stuff that does not mean anything, as long as the syntax is valid. For example, the snippets bellow also mean nothing:
var a;
a = a; // so what?
function something() { /* nothing */ }
var b = something(); // very similar to your example!
Wouldn't it be less consistent if you could assign from some functions, but not from others? If the language were typed, that would produce an error, but since it's not, what's the problem with it? If they don't return a value, their return is undefined, and nothing breaks if you try to assign that to a variable. So you can make functions that sometimes return something, sometimes not. That can be an advantage if used wisely. It's a feature, not a problem with the language.
If you do:
var a = function(){ alert('test'); }
You can then do:
a();
since you've defined an anonymous function..
alert is a function so you can't assign anything to it, per se.
If you want something to pop up if a variable has a value, you could do something like -
$(document).ready(function() {
if (someVar != undefined) {
alert(someVar);
}
});

Categories

Resources