Iteration in JavaScript [duplicate] - javascript

This question already has answers here:
Do modern JavaScript JITers need array-length caching in loops?
(3 answers)
Closed 6 years ago.
This MDN page claims:
...you can iterate over an array using the following:
for (var i = 0; i < a.length; i++) {
// Do something with a[i]
}
This is slightly inefficient as you are looking up the length property
once every loop. An improvement is this:
for (var i = 0, len = a.length; i < len; i++) {
// Do something with a[i]
}
A nicer-looking but limited idiom is:
for (var i = 0, item; item = a[i++];) {
// Do something with item
}
Are these really commonly accepted ways of iteration? Wouldn't modern JavaScript engines simply optimize the first one?

The MDN page is incorrect. Modern engines will optimize the handling of length. In fact, some engines will actually run the first fragment faster.

Related

Why this Insertion Sort method won't work if I change one VAR for LET in nested loops? [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
What is the difference between "let" and "var"?
(39 answers)
Closed 4 months ago.
I'm currently doing a Javascript bootcamp. Today we were studying Sorting methods. The teacher provided us with "template" not-built-in functions. Another teacher also said that nowadays there's no reason to use VAR anymore to define a variable, that we should always use LET (and const, etc.).
So I copypasted his code in VSCode tu run it and study it. Then I decided to change all the VARs for LETs, and the code stopped working. I tried one by one and discovered it is one in particular (inside a loop that is nested in another loop) that if changed, then the code throws an error. So i would like to understand why is this happening? We've used lots of nested loops and this is the first time it happens.
Here is the code:
// INSERTION SORT
function insertionSort(arr){
let currentVal;
for(let i = 1; i < arr.length; i++){
currentVal = arr[i];
for(**var** j = i - 1; j >= 0 && arr[j] > currentVal; j--) {
arr[j+1] = arr[j]
}
arr[j+1] = currentVal;
}
return arr;
}
let hola = insertionSort([26,54,2,1,9,20,99,76,4]);
console.log(hola);
I wonder if this is related to the scope... If I delete this VAR, the code runs with no issue.... what's going on

Does it run faster having assigned the vairable before the loop with Javascript and block scope? [duplicate]

This question already has answers here:
Is reading the `length` property of an array really that expensive an operation in JavaScript?
(6 answers)
Closed 1 year ago.
Is this true:
Statements or assignments that can be placed outside the loop will
make the loop run faster.
Bad:
var i;
for (i = 0; i < arr.length; i++) {
Better Code:
var i;
var l = arr.length;
for (i = 0; i < l; i++) {
https://www.w3schools.com/js/js_performance.asp
Update:
What is the purpose of declaring i before the loop?
It could make the code a tiny bit faster. In the first snippet, every time there's an iteration, the engine has to evaluate
arr.length
looking up the size of the array which might take a bit more processing time than looking up what integer a plain variable refers to.
In the second snippet, you only have to look up the size of the array once, instead of on every iteration.
That said, given how fast computers are nowadays, this consideration is almost certainly irrelevant in 99.9% of situations. Better to write clean and readable code first, and then optimize performance only if it becomes a problem.

Putting multiple statements within `for` argument [duplicate]

This question already has answers here:
Multiple counters in Javascript for loop
(3 answers)
Closed 7 years ago.
I wanted to put multiple statements in the initialization statement of a for loop, and I did as follows:
for({var i = 0; var j = 1;}; someCondition; i++){
...
}
But this seems to cause a syntax error. Isn't a single statement replacable with {}? Why didn't it work? Is there a way to put multiple statements in for argument?
You can use { } to create a new block in place of a statement. But a for loop requires a declaration or assignment.
Instead, you can use ,.
for (i = 0, j = 1; someCondition: i++) { ... }
But this seems to cause a syntax error.
Yes, it does.
Isn't a single statement replacable with {}?
No.
Is there a way to put multiple statements in for argument?
Not really.
For this specific case you can set the value of two variables in a single expression with a comma operator.
for(i = 0, j = 1; someCondition; i++){
But it's decidedly non-idiomatic.
Just use a comma to separate them. See here:
for(i = 0, j = 1; i < 5; i++){
console.log(i, j);
}
There's no reason to expect an expression to be replacable by an object.

Javascript - why isn't my array loop working? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I have a list of objects (data), I am doing this:
for (var i = 0; data.length < i; i++) {...}
But it doesn't work. When I use this:
for (var i in data) {
It works, but is looping three times, when there is only one object, in this case i is: 0 (correct), indexOfObject (wtf), removeItem (wtf).
Why my first expression is not working? What are those two werid i values? Am I doing something wrong?
Edit: Since this thing is a bit complicated, the best I can do is provide a screenshot of my data object: screenshot
Check your for loop statement, the condition of the loop (data.length < i) is the other way round and probably never fulfilled.
It should be:
for (var i = 0; i < data.length; i++)
{
// Now write your code
}
If you really have an array —
var a = ["hello", "world"];
or
var a = new Array();
a[0] = "hello";
a[1] = "world";
Then your first loop (with the index variable) is correct. You should use the in style for loop for iterating over properties of objects, but the indexed style for the numerically indexed properties of an array.
edit — oops good call #Sachin - your for loop test is backwards.
If you have a plain object and you want to iterate through its properties, but skip properties found on the object's prototype chain, you can do something like this:
for (var name in obj) {
if (obj.hasOwnProperty(name)) {
var value = obj[name];
// do stuff
}
}
I could see from the above given code, you have given wrong condition inside the for loop. First, you are initializing the variable i to 0, and then checking data.length<0. Can any length value be less than zero??
you can use it like:-
for (var i = 0; i<data.length; i++) {...}
Try it will work.

Difference between a basic for-loop and a for-in-loop in JavaScript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript “For …in” with Arrays
In which situations using
for (var i = 0; i < array.length; i++)
is different from using
for (var i in array)
in JavaScript?
for (var i = 0; i < array.length; i++)
is best for traversing an array, visiting all of the array elements in order.
On modern javascript engines, array.forEach is often cleaner.
for (var i in object) // with object.hasOwnProperty
is used to go through the enumerable properties of an OBJECT, including inherited enumerable properties. Order is not assured. Though an array is an object and this method "works" for arrays, it isn't ideal as returned properties may not be in any particular order. In addition, if any monkey patches or shims are put into place on the array object, they can show up here.

Categories