Global and Local variables JavaScript - javascript

How to get information that is inside a function, from outside a function
var x = 0;
function myFunction() {
x += 1 //When a button is clicked Javascript will add 1 to x, now x will have a value of 1
}
alert(x) //This returns 0, how to make it return 1
P.S Only pure JavaScript
P.P.S Try to make your answer simple, without a lot of code. Thanks :)

You have to call myFunction() first, e.g.:
myFunction();
alert(x);

It should be called myFunction, myFunction(), first before the alert. This is why you get 0. When this script is loaded the value of x is 0. Hence the alert will alert 0. Then each time a user clicks on the button you have referred to, the value of x would be incremented by 1. That being said, I think that you need something like this:
function myFunction() {
// when the button will be clicked the value of x
// would be incremented by one.
x += 1
// the new value would be alerted.
alert(x);
}
Another way it would be this:
myFunction();
alert(x);
However, this doesn't make sense, since you need to increment the value of x each time the button is clicked and you don't need to force the execution of myFunction.

Well, your function has to be executed for that. The function body only executes if invoked/called. So either create an IIFE function or call it later
myFunction();
alert(x); // now the value has been updated
By IIFE (Immediately Invoked Function Expresson), I mean
(function(){
x += 1;
})(); // invoke

start by colling your myFunction(); and then you can get the value by alert(x);

The other answers are correct in this situation - just call myFunction(); before alert(x), but just for completeness, the other option to "get information inside a function from outside it" is to return a value from the function:
var x = 0;
function myFunction() {
return x + 1; // returns 0 + 1 = 1. Note x is still 0
}
var y = myFunction(); // y stores the return value of the function, i.e. 1
alert(y);

Check out:
http://jsfiddle.net/4taojgy7/
(function(){
var x=10;
function run(){
alert(x);
}
run();
})();
Function 'run' can access only those variables which is in its scope. Even though variable 'x' defined in outside, but still it is accessible. You need to look into scope of a variable concept more. Hope that clarifies.

Related

How does self contained function work in javascript?

var count = 0;
(function curse() {
console.log(++count);
curse();
})();
can anybody explain how does this function work? as you can see i have called the function inside of its declaration, then why it does not show any error while i called it before it finishes its declaration? and while i tried it in google console, it loops through to infinity. i don't know what really going on and how does this code execute itself, even though i know the self-executing function in javascript. I will be glad if somebody explains this code. thanks in advance
var count = 0;
(function curse() {
console.log(++count);
curse();
})();
This can be explained using a divide and conquer approach.
1.- Explanation for:
(function someFnc(){})()
When you declare a function, this will actually return a Function object which can be assigned to a variable:
var someFnc = function(){};
Afterwards, you can do something with this variable like to actually call the function like so:
someFnc();
In your case, instead of assigning the return value of the declaration to some variable, You're actually calling the function right away by doing this:
(function foo())();
Long story short, the latter will assure that the function gets called immediately after being declared.
2.- Explanation for function curse(){ console.log(++count); curse(); }
The ++count is simply summing 1 to the variable count and after that it gets printed in console.
Recursion
The second part of this code is the interesting part, is a function that calls itself, this notion is perfectly valid and is called 'Recursion'.
I'll explain recursion with an example using pseudocode:
Chain of events:
The function curse is called
The variable count is increased by 1
The variable is printed to console
The function curse is called
The variable count is increased by 1
The variable is printed to console
The function curse is called
The variable count is increased by 1
The variable is printed to console
and so on...
Hope it helps.
If you write:
()();
You create an IIFE: https://developer.mozilla.org/en-US/docs/Glossary/IIFE
In this case, JavaScript try to run the function, inside first brackets,
and compute result of this function,
and return this result, from function-expression.
If you write some expression in the first brackets, you'll got an error:
(1+2)(); //Uncaught TypeError: 3 is not a function
If you write:
(function(){ return 1+2; })(); //3
You'll get 3, as an int.
If you write:
var x = (function(){ return 1+2; })(); //3 returns and write in x;
console.log('x', x); //3
Next, thing, your function is named.
If you write:
(function curse() {})();
JavaScript try to return result of function curse();
The name of this function is available in scope of IIFE (inside first brackets).
If you write:
(function curse() { return 1+2; })();
curse(); //curse is not defined
So, curse() is available only in first brackets.
This function is recursive, and this not return the result:
function curse() {
console.log(++count);
curse();
}
So JavaScript can not return result, and continue to compute this infinity times;
If you write this, without console.log (this operation took some time):
var count = 0;
(function curse() {
curse();
})();
You'll got an error Uncaught RangeError: Maximum call stack size exceeded.
Inside your function, at line console.log(++count);,
JavaScript call console.log,
then get value of count variable
(it's available in scope of function curse,
because expression writted in the place, where count is available for this place),
then increment this value ++,
show result,
and save this in variable count.
With each call of the command console.log(++count);
count value is increasing,
but because there is no any end, this increasing infinity.
You can also, write the following code,
var count = 0;
(function curse() {
setTimeout(
function(){
console.log(++count);
curse();
},1000
)
})();
to reduce the computing power, and see how this working.
You have extra parentheses, which are not needed.
var count = 0;
function curse() {
console.log(++count);
if (curse < 100) {
curse();
}
}

Get variable value of a function without setting it globally

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());

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();

scope and availability of a variable inside a function

I am learning javascript and my question might not be used practically anywhere but for interview purpose I want to understand this clearly. below is the code. the first alert alerts 'undefined' and the second one is '4'. the second one is understandable. I want to know why the first alert doesn't alert '5' and undefined? whats the concept behind the same?
Thanks.
var x = 5;
function check(){
alert(x);
var x = 4;
alert(x);
}
check();
var is always hoisted (moved) to the begining of the scope. Your code is equivalent to this:
var x = 5;
function check(){
var x;
alert(x);
x = 4;
alert(x);
}
check();
As you can clearly see, the local x hides the global x, even if the local one doesn't have a value yet (so the first alert shows undefined).
A little extra: conditionals or other blocks don't influence hoisting the var declaration.
var x = 1;
(function() {
x = 3;
if (false) {
var x = 2; // var will be moved to the begining of the function
}
})()
console.log(x) // 1
JavaScript has some concepts that take a little getting used to for sure and sometime the answer for what seems to be a simple question is long winded but i will try to be as quick and concise as possible.
In JavaScript, variables are scoped by functions and you have two places that a variable can be scoped(have context) either 'globally' or 'locally'. The global context in a web browser is the 'window' so in your code example var x = 5; is a global variable. The local context in your code is within your check function so var x = 4; is a local variable to the check function. If you had more functions those would have their own function scope(context) and so on. As a word of caution if you forget the word "var" when declaring a variable inside a function it will become a 'global' variable, be careful. Now that we have the 'global', 'local' scope down what happens before a Javascript programs runs?
A few things happen in the Javascript Engine before your code is executed but we will only look at what happens to variables. Variables are said to be 'hoisted' to the top of their functional context or scope. What that means is that the variable declaration is 'hoisted or moved to the top and assigned the value 'undefined' but not initialized the initialization remains in the same spot they were. This hoisting also makes the variable available anywhere within the function it was defined.
So it looks something like this:
//to be accurate this is hoisted to its functional scope as well
var x;
x = 5;
function check() {
//declaration of 'x' hoisted to the top of functional scope,
//and assigned undefined
var x;
//this will alert undefined
alert(x);
//initialization of variable remains here
x = 4;
//so after the initialization of 'x' this will alert 4
alert(x);
}
check();
Happy Coding!!!
As an aside: They have a new feature named 'let' that you can implement to add block-level scoping in I believe EMCAScript 6 but is not implemented in all the browsers as of yet so that is why i placed it in an aside.

var is firing before triggering through button

Let's say I have the following situation:
CLICK ME
and
var x = alert("test");
$('#trigger').click(function() {
x
});
Why is x firing on loading the page, and not while pressing the button? I know when placing the variable into the function it works, but I don't really get why!
var x = alert("test");
This will execute alert("test"), then assign the value of that expression to x. (alert doesn't return anything, so x will be set to undefined.)
Instead, use this code:
var x = function() {
alert("test");
}
$('#trigger').click(function() {
x(); //remember to actually call it!
});
Here are some better ways:
$('#trigger').click(x); //no need to wrap in function if it does not have
//any arguments
$('#trigger').on('click', x); //using on
In this line
var x = alert("test");
you actually call the function and put its return value into the variable x. As alert() has no return value besides undefined there is nothing really stored in x.
That's why the next time you access x it is still empty and does not contain a pointer to a function or something similar!
var x = alert("test"); will call the function alert("test") immediately, and then assign the return value to x.
To get the behavior you desire, you can wrap the call to alert in a function:
var x = function() {
alert("test");
}
And then to call it later, use parentheses (a parameter list):
$('#trigger').click(function() {
x();
});
Because alert("test") is a function which will show an alert message. Since you call this function not in the $('#trigger') area, it has nothing to do with the click functionality of the trigger but will be executed as soon as the script part is executed by your browser.

Categories

Resources