I am trying to increment a variable using Javascript, but I am not quite understanding what I am doing wrong. What do I need to change?
function init(){
var a = 0;
}
function repeat(){
a = a+1;
}
Do you want this ?
var a;
function init(){
a = 0;
}
function repeat(){
a = a+1;
}
If a is declared in a function, it's not available outside this function.
See the MDN on var :
The scope of a variable declared with var is the enclosing function
or, for variables declared outside a function, the global scope (which
is bound to the global object).
function init(){
var a=0;
a = repeat(a);
}
function repeat(a){
return a+1;
}
As mentioned above, access to variables declared inside a function is possible only inside this function. This rule also applies to curly braces.
Also to increment your value you may use postfix or prefix.
Postfix: x++ the increment operator increments and returns the value before incrementing.
Prefix ++x the increment operator increments and returns the value after incrementing.
{
let x = 0
x = myFunc(x)
}
function myFunc(a){
return a++
}
// next line will throw error because x was declared inside braces
// Uncaught ReferenceError: x is not defined
console.log(x)
Related
When I define the variable outside of a func, it returns undefined. I couldn't find out the reason why.
document.write(myFunc());
var x = 1;
function myFunc() {
return x;
}
output: undefined
However if I define variable inside the func, it works.
document.write(myFunc());
function myFunc() {
var x = 1;
return x;
}
output: 1
You have fallen foul of a common misconception. Variable and function declarations are processed before any code is executed, however assignments occur in sequence in the code. So your code is effectively:
// Function declarations are processed first
function myFunc() {
return x;
}
// Variable declarations are processed next and initialised to undefined
// if not previously declared
var x;
// Code is executed in sequence
document.write(myFunc());
// Assignment happens here (after calling myFunc)
x = 1;
I have a for loop where I get the start number for my countdown. I want to use that number outside the for loop and here comes the closure problem.
for (var i = 0; i < response.length; i++) {
var number = response[i].number; //the number is 10
getNumber(number);
};
So I thought I should call a function that returns that number so I can use it somewhere else:
function getNumber(number) {
return number;
}
But when I try to do this, I get an undefined instead of 10:
var globalVariableForNumber = getNumber();
What I know I am doing wrong is calling getNumber() without the parameter when assigning the value to my variable, but how else should I do it?
The number comes from an ajax call that has more numbers in it (response[i].number). I then want to use those numbers to be the start timers of my countdown. So if the number is 10, then my countdown will start from 10.
Thank you.
var response = [
{number:5},
{number:6},
{number:7},
{number:8},
{number:9},
{number:10}
]
var number;
for (var i = 0; i < response.length; i++) {
number = response[i].number; //the number is 10
console.log(getNumber());
};
function getNumber() {
return number;
}
// try it again later...
console.log(getNumber());
Again, you should just be calling number directly. But for the purpose of this question you have to declare number in a higher scope.
Scope
The current context of execution. The context in which values and
expressions are "visible," or can be referenced. If a variable or
other expression is not "in the current scope," then it is unavailable
for use. Scopes can also be layered in a hierarchy, so that child
scopes have access to parent scopes, but not vice versa.
A function serves as a closure in JavaScript, and thus creates a
scope, so that (for example) a variable defined exclusively within the
function cannot be accessed from outside the function or within other
functions.
Consider this example of scopes that your code could be declared and called:
function ImInGlobalScope(){ //Function declared in global scope
//Lets call this block 1
for (var i = 0; i < response.length; i++) {
var number = response[i].number; //Inside function scope
getNumber(number)
};
//Lets call this block 2
function getNumber(number){ //In same scope than for statement
return number; //block 3
}
}
var globalVariableForNumber = getNumber();
With this example getNumber is undefined because it belongs to ImInGlobalScope() scope. Consider another scenario of scopes for your code.
function ImInGlobalScope(){ //Function declared in global scope
//Lets call this block 1
for (var i = 0; i < response.length; i++) {
var number = response[i].number; //Inside function scope
getNumber(number)
};
}
//Lets call this block 2
function getNumber(number){ //In same scope than for statement
return number; //block 3
}
var globalVariableForNumber = getNumber();
I believe the above is what your scenario is: getNumber is on global scope but number is ImInGlobalScope().
So when you're calling var globalVariableForNumber = getNumber(); We have the following:
function getNumber(number){ //Number is not being passed so is undefined
return number; //no variable named number exists in this scope so it will return undefined.
}
What you are doing is creating a function that takes exactly one parameter and returns that parameter when it is called. Return is a fancy way of saying that if you say foo=bar() then foo is whatever bar() returned.
In your code, calling getNumber() with no parameter returns undefined because it just returns the parameter. What you should do instead is not return the parameter, but instead set the global variable to it like so:
function getNumber(number) {
globalVariableForNumber = number;
}
Now, just get the number by running:
globalVariableForNumber
When running the following code, I expected the alert at the end of the function to use the globally defined variable value for "a" (1), but it instead returns undefined. If the code within the if block is never run, why does the the variable "a" return as undefined?
var a = 1;
four();
function four() {
if (false) {
var a = 4;
}
alert(a); //alerts undefined
}
Does the javascript parser "see" the variable declaration within the scope of a conditional expression in the same way that it would "see" it outside of that?
Since variable declarations are 'hoisted' to the top of their scope, the second var a is being set inside of the function scope. so essentially it's turning into something like:
function four() {
var a;
if (false) {
a = 4;
}
alert(a); //alerts undefined
}
if you were to remove the second assignment within the four function you would alert the window.a variable rather than the four.a one.
ie:
var a = 1;
function four() {
if (false) {
a = 4;
}
alert(a); //alerts 1
}
Yes.
All Javascript variable (and function) declarations are "hoisted" to their containing function.
The a local variable exists throughout your function (even before the if), but will only have a value after it's assigned.
var x = 3;
(function (){
console.log('before', x);
var x = 7;
console.log('after', x);
return ;
})();
In the above code var X is initialized globally. So inside the function the first console.log should print "before 3" but i don't get it. The reason is that i am trying to re-declare the global variable.
Can somebody explain why this is happening?
In the above code var X is initialized globally. so inside the function the first console.log should print "before 3".
No, it should print before undefined, because var takes effect from the beginning of the function regardless of where you write it.
Your code is exactly the same as this:
var x = 3;
(function (){
var x;
console.log('before', x);
x = 7;
console.log('after', x);
return ;
})();
And of course, variables start with the value undefined.
Details: Poor misunderstood var
The JavaScript parser does Variable Hoisting when parsing your code. This means that any variable declaration will be moved to the top of the current scope, thus in your case, this code will get executed:
var x = 3;
(function (){
var x;
console.log('before', x);
x = 7;
console.log('after', x);
return ;
})();
So your local variable x gets declared at first with an initial value of undefined.
This should explain, why you get an "beforeundefined" for the first console.log().
The scope of a variable is much simpler than in other languages. It doesn't start at declaration but is either :
the function in which you have the declaration
the global scope if the declaration isn't in a function
MDN :
The scope of a variable declared with var is the enclosing function
or, for variables declared outside a function, the global scope (which
is bound to the global object).
You can imagine that all variable declarations are moved to the start of the scope (the function). So this is exactly like
var x = 3;
(function (){
var x;
console.log('before', x); // now undefined
x = 7;
console.log('after', x); // now 7
return ;
})();
Be careful to understand what is the exact scope (the function, not the block) :
var x = 3;
(function (){
console.log('before', x); // this is undefined !
if (true) {
var x = 7;
}
return ;
})();
For this snippet, I'm not surprised global variable 'a' evaluates to be 5.
http://jsfiddle.net/MeiJsVa23/gZSxY/ :
var a = 10;
function func(){
a = 5;
}
func(); // expect global variable 'a' to be modified to 5;
alert(a); // and this prints out 5 as expected. No surprise here.
But how come for this code snippet, global variable 'a' evaluates to be 10 and not 5? It's as if the a = 5 never happened.
http://jsfiddle.net/MeiJsVa23/2WZ7w/ :
var a = 10;
function func(){
a = 5;
var a = 23;
}
func(); // expect global variable 'a' to be modified to 5;
alert(a); // but this prints out 10!! why?
This is due to variable hoisting: anything defined with the var keyword gets 'hoisted' to the top of the current scope, creating a local variable a. See: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting
So, there are two things are going here: hoisting and shadowing.
Because the first one, variable declarations are "hoisted" to the top, so your code is equivalent to:
var a = 10;
function func(){
var a;
a = 5;
a = 23;
}
And because the second one, you're "shadowed" the global variable a with a local ones, so the changes are not reflected to the global a.
This is called "variable hoisting". var declarations (and function() declarations) are moved to the top of their scope.
This has to do with hoisting.
In the function, a local variable with the same name is declared. Even though it happens after your modification, it is deemed to have been declared before it - this is called hoisting.
Local variables hoist for declaration but not value. So:
function someFunc() {
alert(localVar); //undefined
var localVar = 5;
}
Functions, if declared with function name() {... syntax, hoist for both declaration and value.
function someFunc() {
alert(someInnerFunc()); //5
function someInnerFunc() { return 5; }
}
var a = 10; //a is 10
function func(){
a = 5; //a is 5
var a = 23; // a is now in local scope (via hoisting) and is 23
}
func();
alert(a); // prints global a = 10
Presumably, the statement var a = 23 creates a local variable for the whole scope. So the global a is shadowed for the entirety of func(), not just for the lines below the statement. So in your second snippet, a = 5 is assigning to the local variable declared below.