Java Script Variable Problems [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Is there a way to null out all variables or delete any data inside them. Beside writing
Variable1=null;Variable2=null;
...so on and so forth. Please no software.
It's not that it's taking much memory, I just want it to load fast. Why I want to null the variable is because I want no mistakes even possible. The code looks like this:
var First_variable;
for (var I_am_a_loop=0;I_am_a_loop<10;--I_am_a_loop){
First_variable=prompt("What is your name.");
}
Now this is the just but it will have arrays and be more advanced. Why I want to null the variable is because I want no mistakes. I don't have the script complete so I cant give you a whole example.

If you are reassigning the variables in the loop setting them to null for a few milliseconds isn't really going to solve any problems for you.
Even if you do declare them within the loop*, modern JavaScript garbage collectors shouldn't have any trouble getting rid of unreferenced variables. The only time you would expect there to be a problem here is with circular references (so the variables always have a reference) or very fast creation of lots of large objects, which causes a lot of garbage handling.
if you use var they are hoisted to the top of the function, if you use let they will have block scope (ECMAScript 6 only).
Regarding your comment:
its not that its taking much memory it is that i want it to make sure it will not mess up it anyway
May I be the first to quote the Donald Knuth...
Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.
I recommend you measure and take no action until you have a measurement that demands it. Write your code to be readable, not efficient, by default.
Code
Based on the code you added, I'd make some observations... you seem to be decrementing the loop variable, so it is going to prompt forever. You can do that if you want, but it is easier to just use a while(true) {} loop to make it clear you want to do it.
Otherwise, if you really intend to do the loop 10 times, increment the loop variable instead.
var First_variable;
for (var I_am_a_loop = 0; I_am_a_loop < 10; I_am_a_loop++) {
First_variable=prompt("What is your name.");
}
Even if the user enters nothing, the value of First_variable will be overwritten. You can always supply a default for when they don't enter a value:
var First_variable;
for (var I_am_a_loop = 0; I_am_a_loop < 10; I_am_a_loop++) {
First_variable = prompt("What is your name.") || 'Default Name';
alert(First_variable);
}

Seems like an odd question, but to answer. You could wrap the relevant code in a function and rely on javascript's function-level scoping to give you fresh instances with each call of the function.
You might be able to refactor your code such that you are using an object or an array in lieu of direct variables.
You could somewhat shorten your example code by one chained assignment statement, such as:
variable1 = variable2 = null; // saves you a bunch of '=null;' if nothing else
My general thoughts are that if you have fewer than 10 variables you need to reset, it's a minor complaint. If it is many more than 10 variables you need to reset, you probably want to look at your code.

Related

why can't I declare the same variable twice in Java?

There are similar questions here but they didn't really answer my questions.
So I am curious why we can't declare the same variable twice in Java?
for example:
int a = 4;
int a = 6;
this won't really work in Java.
However in javascript, this actually works:
var a = 1;
var a = 2;
In javascript, people said that the declaration immediately got moved to the start so that it became like this:
var a;
a = 1;
a = 2;
The simple, obvious answer is because the compiler doesn't let you. But now let's go a step further - why would this be desired?
The reason here is that declaring a variable twice is a sign of a mistake. It usually means one of three things:
Your variable names are not specific enough. Perhaps you used int length twice and it barks at you. You probably should make your name more specific to what it holds the length of, for example int originalLength and int extendedLength when copying an array or something.
Your method is too long. Why is your method so long that you need two of the same variable? Chances are you're duplicating code, so consolidate that into a method.
You haven't really thought out your method. This is sort of an extension of number 2, but the truth is you should decide what a method does before you write it. If you're adding a variable that already exists, it probably means that you haven't decided exactly what this method is doing.
Each of those is a major code smell, and is probably the source of bugs down the road. (And not far down the road!) In each of the cases, allowing you to declare a variable twice is going to cause ambiguity that would have been prevented if it stopped you from compiling.
Now, does this mean there aren't cases where it might be nice? Sure. There might be. Maybe you've covered all your bases and you're absolutely sure it's okay to reuse that variable. In that case, just reassign it instead of redeclaring it. Personally, I'd advise against that, but it's your foot to shoot if you want to. :)
You can use the same variable name if the scopes don't overlap, for instance i could have a variable in a private method called "var1" and then in another method have the same thing, these two would not conflict
However since everytime i use "int var1" in the same scope, java is re-declaring the variable, it wont allow it, as it's a conflicting variable name, whereas in java script the declaration happens once, as it's weakly typed
now it has been rectified or improvised in javascript too with the new let keyword
if you try to intialize the same variable name more than once it will throw an error
let a = 4;
let a = 5;
will throw an error in ES6

JsHint W083 Don't Make Functions in Loop and jQuery's $.each() function

I'm currently using JsHint and am receiving warning W083: "Don't make functions within a loop". I read this post from JsLint Error Explanations and understand why you should not do this, which essentially boils down to the asychrnonous nature of JavaScript and the potential for variables to be overwritten.
However, I also read in a few other posts here on SO that although this is a faux pas it does not always lead to bugs depending on the situation.
My situation in particular that JsHint is complaining about is a for-loop that uses the jQuery $(selector).each() function within it. This function takes a function as a parameter. Below is a snippet of the code that I'm concerned about. Don't worry about what it actually does+ since I'm really just using this as an example:
for (var i = 0; i < sections.length; i++) {
disableSectionState[sections[i].name] = {};
$('.' + sections[i].name).each(function (index, element) {
var id = $(element).attr('id');
disableSectionState[sections[i].name][id] = $(element).attr('disabled');
});
if (sections[i].isChecked) {
$('.' + sections[i].name).attr('disabled', 'disabled');
}
}
Essentially, this is just a nested for-each loop within a for-loop, so I didn't think this would be too dangerous, but I'm obviously not familiar with all of the quirks in js.
As of right now, everything is working properly with this function in particular, but I wanted to ask the community about the dangers of this using jQuery's each function within a loop.
To prevent this being marked as a dupe I did see this SO question, but the only answer doesn't go into any detail or explain anything, and based on the comments it looks like an XY problem anyway. I'm more interested in the why this is when at it's core is that it's essentially a nested loop.
Is it really that much safer for this function to be extracted and named outside of the loop? If I copied the loop counter to a variable in scope of the anonymous function, would that eliminate the potential danger of this design? Is that function executed completely asynchronously outside of the main for-loop?
+In case you're actually interested: This code is used to determine if certain fields should be disabled at page load if certain options are enabled.
The problem isn't using jQuery's each within the loop, it's repeatedly declaring a function. That can lead to some odd closure issues (the function closes on a reference to the loop counter, which still gets updated and can change) and can be a non-trivial performance problem on less clever VMs.
All JSHint is asking you to change is:
function doStuff(index, element) {
var id = $(element).attr('id');
disableSectionState[sections[i].name][id] = $(element).attr('disabled');
}
for (var i = 0; i < sections.length; i++) {
disableSectionState[sections[i].name] = {};
$('.' + sections[i].name).each(doStuff);
if (sections[i].isChecked) {
$('.' + sections[i].name).attr('disabled', 'disabled');
}
}
Most of the dangers come when you're calling something asynchronously from within a loop and close over the loop counter. Take, for example:
for (var i = 0; i < urls.length; ++i) {
$.ajax(urls[i], {success: function () {
console.log(urls[i]);
});
}
You may think it will log each URL as the requests succeed, but since i probably hit length before any requests have come back from the server, you're more likely to see the last URL repeatedly. It makes sense if you think about it, but can be a subtle bug if you aren't paying close attention to closure or have a more complex callback.
Not declaring functions within the loop forces you to explicitly bind or pass the loop counter, among other variables, and prevents this sort of thing from accidentally cropping up.
In some more naive implementations, the machine may also actually create a closure scope for the function every iteration of the loop, to avoid any potential oddities with variables that change within the loop. That can cause a lot of unnecessary scopes, which will have performance and memory implications.
JSHint is a very opinion-based syntax checker. It's kind of like deciding which type of citations to do on a paper MLA or APA. If you go with one, you just follow their rules because, most of the time, it is "right", but it's rarely ever wrong. JSHint also says to always use === but there may be cases to use == instead.
You can either follow the rules or ignore them with the following
// Code here will be linted with JSHint.
/* jshint ignore:start */
// Code here will be ignored by JSHint.
/* jshint ignore:end */
If you are going to use JSHint, I would just comply. It tends to keep the code a little more consistent, and when you start trying to work around one warning or error, it tends to start creating a bunch more
Is it really that much safer for this function to be extracted and named outside of the loop?
In practice, yes. In general, on case by case, maybe not.
If I copied the loop counter to a variable in scope of the anonymous function, would that eliminate the potential danger of this design?
No.
Is that function executed completely asynchronously outside of the main for-loop?
Pretty sure it is.

Why does not JSLint allow "var" in a for loop?

Something is wrong with my code or with plovr. I went to JSLint to get some help. However, JSLint seems to consider this as a fatal error and refuses to check more of the code:
for (var i = 0; i < data.length; i += 4) {
Why? I like this way of declaring "I".
JSHint does not seem to be an alternative if you are on Windows. I am trying The Online Lint at the moment. I have a feeling that this bug will be a bit difficult to find so I would be glad for suggestions about good code checkers.
I agree with Niet the Dark Absol that the tool is opinion-based. Reflect on all the rules it imposes and whether they actually make sense in your specific project or not. It's also not the only "lint" tool for JavaScript. Maybe ESLint or another such tool is more suited to your needs.
But I also disagree with him: It is not good practice to declare all your variables at the start of your function, especially not if the function is rather long, since this makes comprehension of your program much harder. IMHO this holds regardless of how the scoping of JavaScript works: It's not about program semantics, it's about code readability!
I would argue that a variable should be declared as close to its first use as possible (i.e. in your case: in the for loop). This ensures that someone reading your code (a colleague or yourself three months from now) has too keep as little information in their head as possible. Declaring all your variables at the start forces the reader to keep all those variables in mind throughout the entire function. Questions like "what's the current value of this variable?" or "what is its purpose?" become harder to answer.
Furthermore, you are much more tempted to reuse a variable for more than one purpose. This is not only confusing, but also dangerous! Values might "leak" from the first use to the second. This can lead to subtle, hard-to-debug problems.
My personal opinion is that JSLint is retarded. But opinions may vary on that sensitive topic.
— dystroy, 45 secs ago
Hey, that's actually a valid point. JSLint is entirely constructed on opinion, and it not the word of god.
However, general good practice is to declare all your variables in one place, at the start of the function block they are in:
function doSomething() {
var a, b, c, d;
a = 1;
c = 10;
for( b = a; b < c; b++) {
d = b*2 + a-c;
alert(d);
}
}
Because creating a bar in the for loop creates a global var. it's one of those things that JavaScript does and most people don't realize. And if you don't and you or someone else creates that same var in the scope of that function or global scope then that my friend would be one of the famous JavaScript foot guns.

What is the community's intention of putting a couple of parenthesis around an anonymous function declaration in JavaScript? [duplicate]

This question already has answers here:
Location of parenthesis for auto-executing anonymous JavaScript functions?
(4 answers)
Closed 5 years ago.
What is the semantic difference between these two snippets of code?
Example 1
var x = (function () {} ());
Example 2
var x = (function () {} )();
The difference in writing is where we put our parenthesis pair () which tells the JavaScript interpreter to execute the code block at once. Technically, there is no difference. If I may rephrase the wording of my question and eliminate the word "semantic", then the new question has already been answered and elaborated upon here: https://stackoverflow.com/a/6645915/1268003
But, the semantic part is my dilemma and what I hope this thread could shine some light on. Due to it being "semantic", there can be no objective answer and my question is admittedly on the borderline of not being valid according to the FAQ of Stackoverflow. However, I can argue for the validity of this question which just might happen in the comments. For now, lets move on.
Defining the problem
The absolute vast majority of all JavaScripters out there seems to use example 2. Actually, I haven't yet found one exception to that rule (or where have I been lately?). jQuery plugin developers in particular, write code like so:
Example 3 (see example of an example)
(function ($) {} )(jQuery);
My bible, JavaScript: The Definitive Guide , doesn't use this practice at all - not once. Author David Flanagan sticks to example 1 (page 249 is the place where author comments this practice).
Never mind which construct, added parenthesis all have one and only one intention: To maximize readability. To clarify. Then, may I ask, clarify what?
My reasoning
When writing a closure in JavaScript, we're defining a local variable in a function that is not supposed to be accessible from code outside. For the most part and due to context, our function is an anonymous one that isn't bound to an identifier. Like so:
Example 4
function () { var local = "Local variable!"; }
Again due to context and what is usually the practice, we want to execute that snippet of code at once. So we throw in a couple of parenthesis. This will tell the JavaScript interpreter to run the function:
Example 5
function () {} ()
To clarify this in code, best practice is to add a couple of parenthesis, in a way this also clarifies the closure:
Example 6
(function () {} ())
This is an exact replica of example 1. My reasoning thus gives that example 1is the way we "should" write code. Whenever I choose to use example 2, I only clarify the use of a closure, not the fact that our anonymous function is executed at once. But by the smallest of efforts to place our clarification-parenthesis on the outside of the entire code snippet, we can catch both.
Yes I can critique my reasoning. In example 3, I find it appealing to think "hey, outside reference is copied to an alias on the inside". The alternative:
Example 7
(function ($) {} (jQuery))
..isn't as clear in this particular regard. However, example 2 doesn't use this pass-by-value technique. Personally, for the most part when I write closures, I don't have to pass anything in. And still, if we are allowed to be fundamentalist about it, the jQuery plugin practice never clarifies the immediate execution of our anonymous function.
Example 1 users
If my reasoning holds true, why is it then that the entire community out there use example 1? Is their sole intention to only cast one of two clarifications? Maybe just maybe, they don't even have a purpose but are following the lead of a mere tradition of which purpose we might not be able to explain? I haven't yet written a jQuery plugin, or used example 2 because I began my career reading the bible. But if you are among the many who use example 1 and have a reasoning for it, please share =)
Why? Readability
Many things are done in code because of the mantra of "Readability". It is invaluable in writing code. Your code should be easily inherited by another developer.
You forgot one
Or zero, as it were.
Example 0
var x = function(){ }();
And here is why people don't use that: it is hard to read. Usually these closures become very large, very quick. Someone shouldn't have to get to the very end of the closure to determine that it is just a variable named x with no self execution - such as var x = function(){}; To this end, developers wrapped their self executing closures with parenthesis: var selfExecuting = (function(){})();, or even plainly (function(){})(); so that from line 1 it was obvious that this was self executing. It also means that if you come across a function like this: var notExecuting = function(){}; you can generally assume at line 1 that it is not self executing.
Readability is very important when coding. It is important for maintenance. It is important for consistency. It is important for documentation.
Although, keep in mind, development code should not be production code.

Is that a bad Javascript practice I'm doing here?

for some reason I do that every time because I find it clean. I declare variables on top to use them below. I do that even if I use them only once.
Here is an example (using jQuery framework) :
$("#tbListing").delegate("a.btnEdit", "click", function(e) {
var storeId = $(this).closest("tr").attr("id").replace("store-", ""),
storeName = $(this).closest("tr").find("td:eq(1)").html(),
$currentRow = $(this).closest("tr");
$currentRow.addClass("highlight");
$("#dialogStore")
.data("mode", "edit")
.data("storeId", storeId)
.data("storeName", storeName)
.dialog( "open" );
e.preventDefault();
});
I tend to do that in PHP too. Am I right if I believe it's not very memory efficient to do that ?
Edit: Thank you for all the answers. You have all given good answers. About that code optimisation now. Is that better now ?
$("#tbListing").delegate("a.btnEdit", "click", function(e) {
var $currentRow = $(this).closest("tr"),
storeId = this.rel, /*storing the storeId in the edit button's rel attribute now*/
storeName = $currentRow.find("td:eq(1)").html();
$currentRow.addClass("highlight");
$("#dialogStore")
.data("info", {
"mode" : "edit",
"storeId" : storeId,
"storeName" : storeName
}) /*can anyone confirm that overusing the data isn't very efficient*/
.dialog( "open" );
e.preventDefault();
});
Sorry, are you asking if it's OK to declare variables even if you're using them once?
Absolutely! It makes the code a million times more readable if you name things properly with a variable. Readability should be your primary concern. Memory efficiency should only be a concern if it proves problematic.
As Knuth said,
We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.
If you're asking more about declaring the variables at the beginning of the function, rather than where they are first used, then Emmett has it right - Crockford recommends doing this in JavaScript to avoid scope-related confusion. Whether it's worth it in PHP is a purely subjective question I'd say, but there's nothing wrong with keeping your PHP and JS coding styles similar.
One more CS quote (from Abelson and Sussman's SICP):
programs must be written for people to read, and only incidentally for machines to execute.
It's not bad practice.
The var statements should be the first statements in the function body.
JavaScript does not have block scope,
so defining variables in blocks can
confuse programmers who are
experienced with other C family
languages. Define all variables at the
top of the function.
http://javascript.crockford.com/code.html
Declaring variables at the top is a good thing to do. It makes the code more readable. In your particular example, you could replace $(this).closest('tr') witha variable, as suggested int eh comments, but in general I find code with descriptive variable names all in one place very readable.
nah, I'd say you're doing exactly the right thing.
As #Caspar says, you could simplify your code by setting $currentRow first and using that instead of $(this).closest("tr") in the other two lines. And there may be a few other things you could improve. But setting vars at the begining of a function the way you've done it is absolutely a good thing.
Particuarly good because you've done it inside the function, so they're local variables, which means they get thrown away at the end of the function, so no memory usage issues there.
If you'd set them as global vars, it might have been more of an issue, although to be honest even then, since you're just setting pointers to an existing object, it wouldn't be using a huge amount of memory even then (though it would be polluting the global namespace, which isn't good)

Categories