How can I update the variable value in jQuery? How can I update the variable value as it updates in functions? I checked the scope of variable in jQuery but I did not understand.
<script>
$(document).ready(function(){
var s = 9;
function data()
{
var s = 11;
}
data();
alert(s);
});
</script>
I want 11 in alert for data but I am getting 9. how can I update the value if its updated in functions. please help me out for this.
I think you meant 11 not 80, or maybe you're not explaining it correctly.
Here s is global var, you can modify its value in data function. When you use var s in data function it creates a new variable names s whose scope is limited to that function only. That's why you get 9 outside its scope.
$(function(){
var s = 9;
function data()
{
s = 11; //removed var from here, if you use var here it will...
//create new variable whose scope will end outside this function.
}
data();
alert(s);
});
Recommend reading:
Values, variables, and literals
var in JavaScript and its scope
First of all, this isn't a question about jQuery. The "$(document).ready"... wrapper in your code isn't relevant to the question.
Secondly, like I said in my comment, I'm assuming that the "70" and "80" in your question are mistakes and you meant to say "9" and "11".
To answer your question, you need to remove the var before s = 11. This code should do what you want:
var s = 9;
function data()
{
s = 11;
}
data();
alert(s);
When you add "var", you're telling the code that s should only exist within the scope of the current function (data), and overrides any other variables called "s" in outer scopes. Without "var", the two ss refer to the same variable.
I'd recommend researching "scope in Javascript" and learning more about how "var" and variable scope work.
Hi i don't think that u can get 70 in alert from this script.
and we can't get 80 in alert with these values, from this script u will get 9 in alert box, because u defined var s as two times, one is global and other one is private, when u are going to alert then script take the global. u can get 11 in alert box by using the following script:
<script>
$(document).ready(function(){
var s = 9;
function data()
{
s = 11;
}
data();
alert(s);
});
</script>
Related
having a strange issue with JS/jQuery. When I push data from a while loop into an array, the data becomes local to the loop.
ignoring the fact my code barely works, if I move console.log(bxStore); into my document ready {} or anywhere below the while loop, it reads undefined.
var bxRegEx = new RegExp(/[b][x]\d*[y]\d*[w]\d*[h]\d*/) //identifier
expression
function bxCycle(){ //cycle html for indbx identifiers
var cycle = 0
var bxIdGet = document.getElementsByTagName('div')[cycle].outerHTML
var bxStore = new Array()
while (bxRegEx.test(bxIdGet)){
bxStore.push(bxRegEx.exec(bxIdGet))
cycle++
bxIdGet = document.getElementsByTagName('div')[cycle].outerHTML
console.log(bxStore)
}
}
$(document).ready(function(){
bxCycle()
})
https://codepen.io/anon/pen/wrRVKw?editors=1112
edit: doesn't appear to be a variable scope issue guys, my example does show it within the function, but when declaring it outside I get the same issue.
I've looked at your codepen. The correct code goes like this:
function bxCycle(){ //cycle html for indbx identifiers
var bxRegEx = /bx\d*y\d*w\d*h\d*/i //identifier expression
var bxStore = new Array();
for (i in document.getElementsByTagName('div')) {
if (bxRegEx.test(i)){
bxStore.push(bxRegEx.exec(i))
}
}
return bxStore
}
$(document).ready(function(){
console.log(bxCycle())
})
I don't have enough reputation to comment yet, so I have to write this in a full blown answer even though it might not fully solve your problem!
Because you define bxStore in the function, it's only usable within that function (it's "scope" is inside the function). So, if you move console.log(bxStore) into the document.ready function it can't see bxStore.
One way to solve your immediate problem is to define bxStore as a global variable (up with bgRegEx) as stravanato says, so that the document.ready function can see it. An even better way would be to have your bxcycle function
return bxStore
... then you could console log your result on document ready like
$(document).ready(function(){
console.log(bxCycle())
})
bxStore scope is inside the function so outside it is not visible.
If console.log is inside function it should echo something, if it's outside it should not.
You should put var bxStore = new Array(); outside the function.
You have to create a closure to expose the local variable of a function, because you declare bxStore inside a function, it will be dumped after function get executed. Yes just do a simple return
return bxStore
Or you can create a global variable.
This may be very simple but i lost my way in finding the answer,
I have a named function inside a Backbone view. I'm trying to write unit test for this named function and i could see a variable is being declared in function scope. The state of this variable changes based on certain scenarios.
I have instantiated the view object inside my test suite and when i do a console.log(viewObject.namedFunction) i see the entire function being logged properly. Now how do i access the variable inside the namedFunction, i was expecting something like viewObject.namedFunction.variableName but it will not work and when i did that, it was not working as expected.
If the variable is tied to viewObject scope then it would have been easy to access it. But in this scenario it is not so can some one please help me in getting a hold on the variable inside named function in view object from test suite.
I think I understand your confusion, because when you define a variable using var in the window scope, it becomes a property on the window object... It would seem to follow that when you define a variable in a child scope, it should become a member of the local context, right? Nope. Globals are special ;-)
In fact, if that were the case, there would be no privacy!
If you want sign to be public, be explicit.
obj = {
namedFunction : function myself() {
console.log(myself);
myself.sign = 23;
}
};
obj.namedFunction.sign;
The only problem with this approach is that you can now assign a new value to sign from anywhere. The classic and preferred approach to this problem is to create a getter function for your private variable.
var obj = {
namedFunction : function myself() {
var sign = 3;
myself.getSign = function(){return sign;};
}
};
obj.namedFunction.getSign();
This isn't by any means the only approach, but I hope it was helpful.
One way to do this is like such:
namedFunction = (function(){
var theActualFunction = function(){
//Do something
//Access variable like: theActualFunction.MyVariable
};
theActualFunction.MyVariable = "value";
return theActualFunction;
}());
As total JavaScript beginner I am unable to use global variable while trying to use multiple functions. The code is as follows -
<script type="text/javascript">
/* Global Variable example! Not working as one function called onClick. */
function make_name_variable () { var y_name = document.getElementById('y_name').value; }
function make_date_variable () { var y_date = document.getElementById('y_date').value; }
function make_month_variable () { var y_month = document.getElementById('y_month').value; }
function make_year_variable () { var y_year = document.getElementById('y_year').value; }
function test(){
/*var y_name = document.getElementById('y_name').value;
var y_date = document.getElementById('y_date').value;
var y_month = document.getElementById('y_month').value;
var y_year = document.getElementById('y_year').value;*/
document.getElementById('Result').innerHTML = y_date + y_month + y_year;
return true;
}
function compute () {
make_name_variable ();
make_date_variable ();
make_month_variable ();
make_year_variable ();
test();
}
</script>
Using as:-
<input type="submit" value="Submit" onclick="compute ()">
Unable to get the result as expected. I want to use the data through out the page so wanted to keep it global for all functions to use. I was not able to set it global in the conventional way as well. Declaring the variable within function gives desired result.
As you must have a realized I am a complete noob so if there are other ways to get the things done please enlighten me. Somehow I feel there must be a better and easier way to solve this.
Thanks in advance. :)
P.S: First question here. Excuse my mistakes.
The var keyword declares a variable in the current scope. If you declare a var inside a function, it will only exist there. The MDN docs are generally very nice.
A GOOD way to declare a global variable in Javascript would be window.globalVariableName rather than var globalVariableName; Or if you are not running your application in browser replace window with global object specific to that invironment.
The first declaration will work no matter where you are in global scope or in a function.
A BAD way to declare a global variable is
globalVariableName = 'Foo';
Because it isn't an obvious declaration and looks a lot like just forgetting the var.
And finally globalVariables is not a good thing to use. So use them thoughtfully. Try to check if they are not used already by another script say like that
if(window.globalVariableName === undefined) window.globalVariableName = 'Bar';
Try reading first chapter of
JavaScript Patterns
Stoyan Stefanov
for more explanation.
UPDATE: awsering Andreas Rossberg
For example David Flanigan in Definitive Javascript Guide states in 4.6.1 what are global variables, they are properties of the global object. You can confirm this on MDN also.
About bad style, i can agree but only partially, because if you don't use the Single var Pattern for variable declarations like this
(function(){
var someVar1 = '',
someVar2 = null,
someVar3 = undefined;
})();
your code will look just as bad.
As to next version of EcmaScript again you are a little too brief on reference. I've read only that this will be handled differently in strict Javascript. If I understood you correctly this example is what you are referring to
function someFunction()
{
//'use strict';
console.log(this); //Window or undefined
console.log(window);// Window or Window
}
someFunction();
Uncommenting 'use strict'; will give undefined for this in first log, but still Window for the second log.
I encountered a strange problem today.
The good: I successfully changed a global var value from within a function(in other words the below example works fine when "passedVarName" is substituted with "a").
The bad: When trying to pass the global var name "a" (rather than putting it directly in the function) it fails to work.
Below is what I can't seem to get working:
(on click document should write "2" but instead writes "NaN" ?)
Javascript:
var a = 1;
function click(passedVarName){
passedVarName ++;
document.write(passedVarName)
};
HTML:
Click this Button to alter global var "a".
This is a pretty bad Code Smell, but if you know it's global, then this'll work:
var a = 1;
function click(passedVarName){
window[passedVarName]++;
document.write(passedVarName)
};
Click this Button to alter global var "a".
This passes string 'a' to your function, not the variable a.
You need to pass it as click(a);
Corrected example :
http://html-bin.appspot.com/aghodG1sLWJpbnIMCxIEUGFnZRjhjxoM
[ Did not use jsfiddle.net to avoid confusion by seperating javascript and HTML ]
Passing a global variable as a param to a function creates a copy of that var inside the function. The global doesn't change.
This example will generate the same output everytime you click on the first div:
//html
<div onclick="foo(a)">Click here</div>
<div id="txt"></div>
//js
window.a = 152;
window.foo = function(varr) {varr++; $("#txt").html(varr)}
However, it seems like if you pass your variable as a property of an object, pass that object to the function, and inside your function modify the variable, it has global effect :
//html
<div onclick="foo(a)">Click here</div>
<div id="txt"></div>
//js
window.a = { val:152};
window.foo = function(varr) {varr.val++; $("#txt").html(varr.val)}
Here is a jsFiddle that works: http://jsfiddle.net/2Ahdb/3/
Forgive me if I misinterpret your knowledge of programming, but a global variable is something that can be accessed and modified by any part of your programming, you do not need to pass it through a function to modify it.
IF you are trying to modify global variables through a function, javascript has some limitations. Only objects are passed by reference.
var a = 5;
var b = { value: 5 };
function changeMe(x) {
x = 10;
}
changeMe(a); //... still 5
function changeMeAlso(x) {
x.value = 10;
}
changeMeAlso(b); //.. changed to { value: 10 }
I am new to JavaScript.
<html>
<body>
<script type="text/javascript">
var x=5;
document.write(x);
document.write("<br />");
var x;
document.write(x);
</script>
</body>
</html>
Result is:
5
5
When x is declared the second time it should be undefined, but it keeps the previous value. Please explain whether this redeclaration has any special purpose.
You aren't really re-declaring the variable.
The variable statement in JavaScript, is subject to hoisting, that means that they are evaluated at parse-time and later in runtime the assignments are made.
Your code at the end of the parse phase, before the execution looks something like this:
var x;
x = 5;
document.write(x);
document.write("<br />");
document.write(x);
var alone does not perform an assignment. It only flags that when you use the variable name throughout the scope in which the var occurs, you are talking about a local variable and not global (the controversial default). The var is spotted when the function is parsed and holds throughout that scope, so where you put it is irrelevant:
var a= 0;
function foo() {
a= 1;
return a;
var a;
}
var b= foo();
alert('global a='+a+', local a='+b);
Results in global a= 0, local a= 1: even though the var statement is never reached in the course of execution of foo(), it is still effective in making a a local variable.
So declaring var x a second time in the same scope is completely redundant. However you might sometimes still do it, typically when you re-use a local variable name for a second independent use within the same function. Most commonly:
for (var i= 0; i<onething.length; i++) {
...do some trivial loop...
}
for (var i= 0; i<anotherthing.length; i++) {
...do another trivial loop...
}
Whilst you could certainly omit the second var, and tools like jslint would demand you do so, it might not actually be a good idea.
Imagine you later change or remove the first loop so that it no longer declares i to be var. Now the remaining second loop suddenly changes meaning from a local to a global variable. If you fail to notice when updating the first loop that the second loop has a hidden dependency on it (and you might very well fail to notice that given how the eyes elide the pattern for(...=0 ; ...<...; ...++) into “oh, that's just a standard iterator”), you've got a subtle and annoying-to-debug problem.
so when the second time when its declared x should be undefined
What part of the specification says this?
"Undefined behaviour" does not mean "the variable will be undefined".
As far as my understanding of javascript goes, the use of the var keyword is completely optional in the global scope. It's a different story for functions.
When inside a function, use the var keyword to indicate that the variable is local to the function (as opposed to being global by default).
I personally use var in the global scope to show that a variable is being declared and/or utilized for the first time.
You can reference http://www.w3schools.com/js/js_variables.asp for more info.
That second var x is totally superfluous.
Within the same scope, it is totally unnecessary to "redeclare" a variable.
Also, a programmer might want to use var to localize a variable:
<script>
var x= 'this is global x';
function my_x() {
var x= 'localized x';
alert(x);
}
my_x();
alert(x);
</script>
You should never redeclare a variable within the same scope, if you really want to change this then assign to it. Redeclaration is not required to create a different object in this dynamic language, if you want x to be a string just assign:
x = "hello";
It is not required that you set it back to undefined or redeclare first.
Please note that changing the variable type is not very good practice in most situations, simply stating that it is a possibility if that's what you require.
I recently wrote code like:
var obj1 = get_an_object();
var v = obj1.get_velocity();
v += changes_in_velocity();
obj1.set_velocity(v);
var obj2 = get_an_object();
var v = obj2.get_velocity();
v += changes_in_velocity();
obj2.set_velocity(v);
(The actual code was more complicated and less repetitive)
So far as the browser is concerned, the second var v statement was redundant and pointless. To me, it served two purposes. It said to forget everything I knew about the old v, because this was a new usage. And it meant I could re-order the code, or comment out the first half, without breaking things.