I am new to programming and sorry if a question is dumb.
I am using several functions with variables i, j for looping like - for( j = 0; j < pol.length; j++) ...
Now my lack of knowledge is - I think that declaring "var i = 0..." in every function will creates a memory problem because these functions are used many times and it will declare "i" or "j" each time. So what I do now is I declare var i,j = 0; once outside the functions as a global and then just use them in functions without "var". But I have a feeling - this is terribly wrong.
Another variables that I declare as global "var" are the ones I use later in some functions. For example - var pol_owner = ""; So the code will play with these variables later and change their values. And now I have something like this at the start of my document:
var thePol = 0;
var nondrag = 0;
var intGl = 0;
var intMn = 0;
var oldGl = 0;
var oldMn = 0;
var money = 0;
var gifts = 0;
var g_spent = 0;
var the_mess = "";
var j = 0;
var x = 0;
var y = 0;
var i = 0;
And later my functions just use these variables without "var".
I know though the code runs well still I am doing it wrong. Can you give me any advice of how to properly do it. I was looking for some information about it but still I am not sure what is the proper way of doing it.
From the start I was doing my code as: for( var j = 0; j < pol.length; j++) not declaring "j" outside the function, but later I thought that every-time this function run it will declare this var again and again and will not it be more effective to declare it once from the start and later use it without "var". The only problem I see is - creating a global variable that I can accidentally use wrong in some part of the code. But I am kind of controlling this.
So the question basically is - is declaring "var i=0" in every loop part of the function creates any memory problem and should I declare this var once outside the function and use it later without declaration to avoid this problem?
Thank you in advance.
Related
What is the difference between:
for (var i=0; i<5; i++) {}
for (i=0; i<5; i++) {}
And is it necessary to include the var keyword?
I understand that the var keyword affects variable scope, but I'm having trouble understanding if it's necessary to include the keyword in for loops.
In the second example, your variable is defined globally, so if you're in the browser environment, you can access it from the window object.
The first one is an equivalent of:
var i;
for (i=0; i<5; i++) {}
as all the variables in javascript are hoisted to the beginning of the scope.
1
for (var i = 0; i < 5; ++i) {
// do stuff
}
2
var i;
for (i = 0; i < 5; ++i) {
// do stuff
}
3
for (i = 0; i < 5; ++i) {
// do stuff
}
1 and 2 are the same.
3 you probably never mean to do — it puts i in the global scope.
I am assuming your are using C#, Java or JavaScript. The short answer is you need the var if "i" has not already been declared. You do not need if it has already been declared.
For example:
var i;
for(i=1;i<=5;i++) {}
Now there may be some implicit variable typing depending on language and IDE, but relying on implicit typing can be difficult to maintain.
Hope this helps, good luck!
I am having a jstree and in javascript function i am checking which node has been selected thats working fine. But when i assign that node value to a variable then do comparasion with a normal string variable thats not working.
$(document).ready(function() {
$('#bdeViewNew').on('changed.jstree', function(e, data) {
var i, j, r = [];
for (i = 0, j = data.selected.length; i < j; i++) {
var x = data.instance.get_node(data.selected[i]).text;
r.push(data.instance.get_node(data.selected[i]).text);
if(x=="Hadoop")
{alert("hi");}
else{
alert("hello");
}
}
});
});
any one know how we can do such comparasion?
thanks in advance
It is possible that your variable has some unexpected whitespace at the start or the end, that's a common problem. You should be able to get rid of it with
var x = data.instance.get_node(data.selected[i]).text.trim();
Should work on all modern browsers.
Also keep in mind that JavaScript has function scope, not block scope like you might be used to from C/C++ or Java. The x you declare there is visible throughout the function, not just in the for loop. You should probably declare it at the same time as i, j and r.
I have a piece of JavaScript code that I want to create a list of functions. All the functions will be put in a dictionary d. d["a"] will give me the function function() {console.log("a")} and d["b"] will give me the function function() {console.log("b")} etc. This is my code:
var a = "abcdefghijklmnopqrstuvwxyz1234567890".split("");
var d = {};
for(var l = a.length, i = 0; i < l; i++)
{
d[a[i]] = function(){console.log(a[i])};
}
However, when I run the above code, d["a"] and d["b"] will be the same, they all point to function(){console.log(a[i])}. How to get what I want?
Thanks.
You need to give each instance of the function its own variable:
for(var l = a.length, i = 0; i < l; i++)
{
(function (x) {
d[a[x]] = function(){console.log(a[x])};
})(i)
}
They don't point to the same instance of function(){console.log(a[i])}, instead, you've created a bunch of functions that all use the same reference to i. The value that i points at changes as the for loop executes.
The other answers provided will work, but it involves generating twice as many functions as you need.
function makeLogFunction(whatToLog) {
return function() {
console.log(whatToLog);
}
}
var a = "abcdefghijklmnopqrstuvwxyz1234567890";
var d = {};
for(var l = a.length, i = 0; i < l; i++) {
d[a[i]] = makeLogFunction(a[i]);
}
Here, I have a makeLogFunction that will return a new function that always prints whatToLog. The other answers will generate a new "version" of the makeLogFunction every time the loop executes. For very large sets of data, this is a waste of time and memory.
This approach has added advantages of clarity and reusability. If there's a significant amount of logic happening in your loop, encapsulating it in a named function allows future reviewers to get a sense of what's going on by the name you give to the function. You can also reuse the function in other parts of your application.
I am trying to make a cell in a table tell me its number when I click it.
for(var j = 0; j < 8; j++){
var cell = row.insertCell(j);
cell.name = j;
cell.onclick=function(){alert(cell.name)};
}
This however, prints the number 8 for every cell. How do I save the value of j in cell.name, instead of just having it point to the variable j?
Thanks.
IMPORTANT: All JavaScript developers should know this. It will cause all kinds of weird bugs that is very hard to find.
It is a common mistake of people who are new to JavaScript. I've made the same mistake before.
A function inside a loop is NOT created for every iteration. It is the same one function object with the same closure scope. Thus, your cells will have the exact same onclick callback.
My advice here is NEVER EVER create a function inside of loop. Instead, create and call a function that returns a callback function and assign it to onclick.
for (var j = 0; j < 8; j++) {
var cell = row.insertCell(j);
cell.name = j;
cell.onclick = createOnClick(cell);
}
function createOnClick(cell) {
return function () {
// do whatever you want to do with cell
};
}
Is there a name for this? Here's an example of what I'm trying to say:
var i = 0;
var j = 0;
i = j = 1;
So obviously both i and j are set to 1. But is there a name for this practice? Also, in terms of good coding standards, is this type of thing generally avoided? Can I also get an example or explanation of why it is/isn't good practice?
As Daniel said, it's called chained assignment. It's generally avoided, because for some values (such as objects), the line i = j = _something_ creates a reference from i to j. If you later change j, then i also changes.
var i = {};
var j = {};
i = j = {a:2};
j.a = 3; //Now, j.a === 3 AND i.a === 3
See this jsFiddle demo for an example: http://jsfiddle.net/jackwanders/a2XJw/1/
If you don't know what i and j are going to be, you could run into problems
I believe that it is called "assignment chaining".
We say that assignment is "right associative". That means that
i = j = 1;
is equivalent to
i = (j = 1);
j = 1 will assign the number 1 to j and then return the value of j (which is now 1).
Sometimes it's referred to as "chained assignment" and sometimes as "multiple variable assignment". Also, you might want to look at the answers to this question.