What are the differences of that iterations? - javascript

What are the differences of that iterations:
var recordId;
for(recordId in deleteIds){
...
}
and
for(var recordId in deleteIds){
...
}
It says implicit definition(what is it), is there a performance difference between them?

the two samples are equivalent, however the first may come from following a recommended pattern in JavaScript which is declaring all variables at the top of every function.
Sample:
var recordId,
i = 0;
for(recordId in deleteIds){
...
i++;
}
More explanation on this can be found here JSLint error: Move all 'var' declarations to the top of the function

An "implicit declaration" is a variable that is assigned a value before it is declared using a var. The scenario leaves the variable declared in the largest possible scope (the "global" scope).
However, in both your code examples, recordId is declared before it is assigned (var recordId), so there's no problem.
As to your other question, no, there is no noticeable performance difference.

Related

Where to use `var` and where `let` in javascript? (NOT asking difference)

I have read my blog about the var and let. What I see is this.
var is a function or global scope variable depend on where it is defined.
where
let is block scope variable
So in lots of articles, I see they recommend to use let instead of var. I understand that because it eliminated the conflict of the scope of a variable.
So I want to ask where to use let and where to use var? If possible please provide any relevant link for that. If I go with recommendation than I have to use let everywhere.
What I understand is this.
let should be used in for loop as it creates its own lexical scope.
for(let i =0;i<5;i++){
setTimeout(function(){
console.log(i);
},100);
}
So in this case because of let, we will able to print 0,1,2,3,4, but if we have used var it would have print 5 time 5.
Also, I want to know your suggestion on what should be used in function scope and global scope?
let say, I have file index.js
var first = 1; // what should be used here and why
function function1(){
var first = 1; // what should be use here and why `let or var`
var first1 = 2; // what should be use here and why `let or var`
for(let i=0;i<2;i++){
console.log(i);
}
Also, I fill let is more than a variable, I create its own lexical scope, there would be more manipulation under the hood like creating IIFE sort of thing.
What I understand is that we should use function and global scope as var and let as only block scope? Please provide any recommended link which describes what is better where and why?
Thanks.
It's mostly right to only use let these days.
In almost all situations, let is a better or at least equivalent to var considering that leaky declarations make you write error prone code. Avoid using var.
Look at this code:
for(var i = 0; i < 6; i++) {
document.getElementById('my-element' + i)
.addEventListener('click', function() { alert(i) })
}
contrary to this code:
for(let i = 0; i < 6; i++) {
document.getElementById('my-element' + i)
.addEventListener('click', function() { alert(i) })
}
The first one makes a closure which catches i, defined by var, while the other one makes i different values. The first example makes every callback alert 6, since they are all pointing to the same object. However, the let in the second example makes a new block scope every time it iterates. This solves a very common pitfall in javascript.
In most situations, if you need to use var's scope to achieve something not available using let, it's almost always a sign that's something is wrong.
Also, don't rely on var's variable hoisting. If you are using a variable you didn't declare before, it becomes error prone.
Mostly, try to follow on the style guide you follow. If you don't have a special style guide you follow, try the AirBnB's: https://github.com/airbnb/javascript
The "never use var and use let" thing is mentioned here: https://github.com/airbnb/javascript#variables
let and var
You should use var, when you wan to define a variable globally, or locally to an entire function regardless of block scope. Variables assigned with the var keyword have functional scope. The variable isn’t accessible outside of the function.
And, you should use let to declare variables that are limited in scope to the block, statement, or expression on which it is used. When used inside a block, let limits the variable's scope to that block.
Variables assigned with let are very similar to those defined with var. The major difference is scope. This has been referenced above. Variables assigned with let have block scope. This means the variable can be seen within that block and any sub-blocks. Variables assigned with var have functional scope and ignore block scoping rules. Variables assigned with let can not be redeclared, they can only be reassigned.
According to this article, Only use the let keyword when you know that a variable will have a dynamic value. You probably don’t need to use var anymore
Clearly, you know the difference between let and var, and your question is WHERE TO USE WHICH?
First of all, if you are seeking for a better performance, use let wherever you are able to. However, you have to be aware that some old browsers may not be able to handle the let.
Second, I think the best and shortest answer to your question is " use let as long as you can, and if you couldn't then use var".
If you study the differences between let and var deeply, you can figure out where you should use var instead of let, I recommend you to read this article.

Are there downsides to using var more than once on the same variable in JavaScript

Before asking my question, let me give a disclaimer. I know what var does, I know about block scope, and I know about variable hoisting. I'm not looking for answers on those topics.
I'm simply wondering if there is a functional, memory, or performance cost to using a variable declaration on the same variable more than once within a function.
Here is an example:
function foo() {
var i = 0;
while (i++ < 10) {
var j = i * i;
}
}
The previous could just have easily been written with the j variabled declared at the top:
function foo() {
var i = 0, j;
while (i++ < 10) {
j = i * i;
}
}
I'm wondering if there is any actual difference between these two methods. In other words, does the var keyword do anything other than establish scope?
Reasons I've heard to prefer the second method:
The first method gives the appearance of block scope when it's
actually function scoped.
Variable declarations are hoisted to
the top of the scope, so that's where they should be defined.
I consider these reasons to be good but primarily stylistic. Are there other reasons that have more to do with functionality, memory allocation, performance, etc.?
In JavaScript - The Good Parts Douglas Crockford suggests that by using the second method and declaring your variables at the top of their scope you will more easily avoid scope bugs.
These are often caused by for loops, and can be extremely difficult to track down, as no errors will be raised. For example;
function() {
for ( var i = 0; i < 10; i++ ) {
// do something 10 times
for ( var i = 0; i < 5; i++ ) {
// do something 5 times
}
}
}
When the variables are hoisted we end up with only one i. And thus the second loop overwrites the value, giving us an endless loop.
You can also get some bizarre results when dealing with function hoisting. Take this example:
(function() {
var condition = true;
if(condition) {
function f() { console.log('A'); };
} else {
function f() { console.log('B'); };
}
f(); // will print 'B'
})();
This is because function bodies are hoisted and the second function overwrites the first.
Because searching for bugs like this is hard and regardless of any performance issues (I rarely care about a couple of microseconds), I always declare my variables at the top of the scope.
There will not be any differences during execution time. There might be a imperceptibly small difference in interpretation/compilation time, but that of course will be implementation dependent. There also might be a few bytes different in the size of the file, which could also affect download time. I don't think either of these are worth being bothered about.
As you already know, any variable declaration will be hoisted to the top of the function. The important thing to note is that this occurs during the interpretation/compilation process, not during execution.
Before a function is executed, the function must be parsed. After each function is parsed, they will both have all of the variable declarations moved to the top, which means that they will be identical and there will be no execution time cost incurred.
For the same reason, there are no memory cost differences. After parsing, there will be no differences at all.
Since you are not asking about style I am not telling you which I think is better. But I will say that the only reason you should prefer one over the other is style.
Style
Subjective. I prefer the approach that keeps the var close to the usage site, but I always keep the scoping rules in mind. I also avoid combining multiple declarations into a single var and prefer multiple var statements.
Memory allocations
Variables are not objects: not applicable. Due to the hoisting rules, the variable "slot" has the same lifetime in all cases.
Performance
No. There should be no difference in terms of performance. While an implementation could technically really mess this up - they don't.
The only way to answer this (besides looking at every implementation in minutia) is to use a benchmark.
Result: noise differences on modern browsers
The 2nd way saves the 4 characters in the the javascript file - but in terms of the actual code generation or execution speed I don't believe there is any difference at all.
Your example will function exactly the same. It could be even more unclear than your example to use 'var' in a block, though. Say, for example you want to update a variable that is outside of the scope (by not using 'var') conditionally, or use a local 'var' instead. Even if that condition is false, 'j' becomes local. It turns out not to be as trivial as it appears to do that.
var j = 1;
function foo () {
j = 2;
if (false) {
var j = 3; // makes `j = 2` local simply for being in the same function
}
console.log(j);
}
foo(); // outputs 2
console.log(j); // outputs 1
That's one tricky case that may not work as you expect just by looking at the code.
There are no downsides to declaring every 'var' on top, only up-sides.

Is it wrong to declare a variable inside an if statement in Javascript?

I have a Sublimelinter installed in Sublime Text 2 and it's great. However it doesn't like the following code:
if(condition){
var result = 1;
}else{
var result = 2;
}
process(result);
It says for var result = 2; that result is already defined and for process(result); that it's used out of scope. Is it just mistaking the {} of the if statement for a more closed scope or should I really be doing it like this:
var result;
if(condition){
result = 1;
}else{
result = 2;
}
process(result);
No it is not "wrong"; it will get hoisted to the top of the nearest function definition, as per the ECMAScript specification.
Yes, your program "Sublimelinter" is incorrect to claim the variable is out of scope.
It is not wrong. If you get that error, you defined result earlier in your code.
You can also simplify your condition to this so you don't have to use result:
process( condition ? 1 : 2 );
Javascript doesn't have 'block-scoping' like many other languages. If it did, the variable result would not exist when you tried to call process(result) because it would not be possible to reference it outside of the {} block where it was defined.
However, javascript only has function scoping, where variables in one function cannot be accessed by another function. Where variables are declared in the function has no significance whatsoever, because it will still be accessible from anywhere inside that function (no block scope). Hence, both code snippets you posted are equivalence to whatever interpreter is running the code.
The second is preferable because it is clearer as it shows where the variable will be used (throughout the function). It also prevents the variable from being declared twice inside the scope of the function, which may not necessarily cause anything bad to happen, but it will definitely not cause anything beneficial. You should almost always declare a variable once at a higher level instead of twice at different lower levels, even though it doesn't really matter since the scope of the variable will be the entire function no matter where it is declared.
JavaScript does not have block scope. Variables are scoped to the function they are defined in, meaning that when you declare a variable inside of an if block, it is "hoisted" to the top of the function.
Since the variable is technically defined at the top of the function anyway, it is considered a best practice to move variable declarations to the top of the function so that the intent of the code is clear.
I'd say your code isn't "wrong" but it is misleading to people reading the code who aren't familiar with how scope works in JavaScript. I would definitely opt for the second version, because it actually reflects how the code is executed.
Here's a good article explaining variable hoisting.
Declare your var pointer once with-in the function you have your if statement at. Like ninjagecko mentioned all vars get sent to the top of their containing functions.
However; do be careful because if you declare the same var twice like you have it , it will reset the var.
I recommend doing this:
var result = MORE_LIKELY_OUTCOME;
if (LESS_LIKELY_CONDITION) {
result = LESS_LIKELY_OUTCOME;
}
process(result);
This way, you are setting result initially to what you are expecting it to be most of the times.
Then, the if statement will change result if the condition occurs.
It turns out that SublimeLinter is using JSHint which has the option to surpress this warning and explains why it exists.
funcscope This option suppresses warnings about declaring variables
inside of control structures while accessing them later from the
outside. Even though JavaScript has only two real scopes—global and
function—such practice leads to confusion among people new to the
language and hard-to-debug bugs. This is way, by default, JSHint warns
about variables that are used outside of their intended scope.

Clarification of a JavaScript variable issue

Having coded JavaScript since 1996, I have a very simple issue which I could not clearly prove/disprove using jsfiddle
In some JS attached to a CV I spotted some issues that I would like to verify - one of which is
multiple declaration of variable in the same function
Testing it seems it is allowed in newer browsers (OSX Chrome16 Fx 10beta) - as far as I remember it used to give errors (Netscape/Mozilla/Fx1/IE5 or so) :
function something() {
var var1 = "";
.
/* reams of code which scrolls the first declaration off the screen
so the author likely forgot the var was already declared earlier
in the same function */
.
var var1 = ""; // could this result in an error in some browsers?
}
My fiddle is here
Not as far as I'm aware, I've seen javascript functions with multiple for loops each declaring their own var i for at least 6 years all without issue.
Having looked at the spec, there seems to be nothing concrete in this area, however since (particularly global) variable name overwrites (read: clashes) has been a feature since inception I would be very surprised if a restraint upon multiple declarations was imposed.
As it stands, I would suggest that it doesn't show particularly good knowledge of scoping (and hoisting) in javascript, but is valid code nonetheless.
I've been playing with javascript for about as long as you, and I don't remember this ever being forbidden by an interpreter. Looking at the ECMAScript 1 spec, I can see no mention of ensuring that variable declarations are unique within a given scope; and it would be a strange feature to remove.
The absence of such a check, alongside the fact that variables are function~ and not block-scoped, is one of the things that seems to cause misunderstanding, where a variable "declared" in one block unexpectedly has the last value it had in a previous block.
I'm quite certain that the parser ignores the second "var"-declaration, since it is redundant - all it does is signify that the variable is limited to the local scope. There's no reason to use it twice in the same scope, as in the same function, but if you, as #rich.okelly pointed out, have loops or functions, you can indeed use "var" to create a local variable of the same name as a variable in a higher scope. It's not pretty, and certainly doesn't do any wonders for readability, but it's possible. I have never encountered a browser that hangs up on prepending a variable with "var" twice.
Example:
x = "Hello";
function test() {
alert(x); // Outputs "Hello"
}
function test2() {
var x = "local variable";
alert(x); // ouputs "local variable"
var x = "changed the variable"; // this does exactly the same thing as if you'd omitted "var"
}
alert(x); // Outputs "Hello"

Does using var in a tight JavaScript loop increase memory-related overhead?

For example, would this:
while (true) {
var random = Math.random();
}
... be less efficient than the following, in most implementations?
var random;
while (true) {
random = Math.random();
}
Thanks for your input.
Edit: In case it wasn't obvious, I'm mostly worried about lots of repeated (de)allocations occurring in this example.
JavaScript does not have block scoping.
In the first example, the var text declaration is hoisted out of the while block. In both cases, the variable is declared only once. In both cases, the variable is assigned a value once per iteration of the while loop.
var
function-scoped
hoist to the top of its function
redeclarations of the same name in the same scope are no-ops
No, variables are initiated upon entry into the scope, so random exists before the var statement is even reached.
JavaScript doesn't have block scope, and random's declaration would be hoisted to the top of its scope anyway (variable object).
This depends on the implementation of the interpreter. Strictly speaking, yes, it may have a slightly higher overhead; but depending on the GC mechanism this should be cleared reasonably quickly too.
Douglas Crockford recommends putting all the var assignments at the top of a function, i.e. outwith any loops.

Categories