Putting multiple statements within `for` argument [duplicate] - javascript

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.

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

JSHint: "Unexpected 'var'" in For Loop [duplicate]

This question already has answers here:
Why does not JSLint allow "var" in a for loop?
(3 answers)
Closed 3 years ago.
I am running JSHint on my Javascript code to try and clean it up and it is giving me this warning:
#3 Unexpected 'var'.
for (var i = 0; i < self.myArray.length; i++) { // Line 88, Pos 14
Expanding this out, it is this piece of code:
self.myFunction = function() {
for (var i = 0; i < self.myArray.length; i++) {
// Do some stuff
}
};
I have searched the internet and seen many ways to write a for loop. Some use var, some don't, others use let etc.
I can't seem to find any info on how JSHint expects me to construct my for loop. Can anyone enlighten me on some best practice, or what JSHint is looking for?
Thanks! :)
If you use var then it will create the variable as the enclosed function scoped or global scope (if not inside a function).
So always use let in for loop, the scope will be only within for loop.
self.myFunction = function() {
for (let i = 0; i < self.myArray.length; i++) {
// Do some stuff
}
};

How can I make new variables out of elements in a list? [duplicate]

This question already has answers here:
Use dynamic variable names in JavaScript
(19 answers)
Closed 3 years ago.
I have a list of 3 lines. I want to efficiently separate each line out as it’s own individual item.
myList = [MultiLine.attributes.renderers[0], MultiLine.attributes.renderers[1],
MultiLine.attributes.renderers[2]]
What I want:
line1 = MultiLine.attributes.renderers[0];
line2 = MultiLine.attributes.renderers[1];
line3 = MultiLine.attributes.renderers[2];
I know in Python there is the casting function which I would use like so:
line + str(i) = MultiLine.attributes.renderers[i];
However I'm getting ReferenceError: invalid assignment left-hand side with the equivalent JS:
for(var j = 0; j < myList.length; j++){
"line" + String(j) = MultiLine.attributes.renderers[j];
}
Any ideas?
I don't know how to properly go about changing the value of my variable within the for-loop. Would Break statements help?
You could use a destructuring assignment with the array.
var [line1, line2, line3] = MultiLine.attributes.renderers;

i is not incremented within JavaScript for loop [duplicate]

This question already has answers here:
What is the purpose of the var keyword and when should I use it (or omit it)?
(19 answers)
Javascript: Why do I need to declare var i = 0 in the for loop?
(4 answers)
Closed 4 years ago.
for (i = 1; i < this.people.length; i++) {
peoplePicks[i] = this.people[i].chooseAction(peopleChoices[i]);
}
I have this for loop within my JavaScript program. It runs for ever, even though the length of the array that I am passing to it is 2. when I print the value of i after the statement of the for loop, I get 0. So it seems like i is being decremented by executing the for loop's statement. How can I fix this?
Add var before your i variable in the initialising of your for loop.
Like this for (var i = 1; i < this.people.length; i++) {

Why do functions defined in a loop all return the same value? [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 7 years ago.
I'm confused by the following JavaScript code. I wrote a loop and defined a function inside the loop, but when I call a function defined in the loop, I only get 10 rather than the index.
Obviously, in the following code I abstracted out stuff that isn't relevant:
objectArray = [];
for (i = 0; i< 10; i++){
objectArray[i] = {};
}
for (i = 0; i< 10; i++){
objectArray[i].get_number = function(){
return i;
}
}
console.log(objectArray[5].get_number()); // returns 10 rather than 5
I always get 10 rather than i as expected.
It's because of JavaScript closure. The method objectArray[i].get_number has direct access to i (not a copy of i). The value of i lives on in memory because each method objectArray[i].get_number still has access to it. There's only one i, and when the loop iterates it, it increases by one. When a method objectArray[i].get_number accesses it, the loop has already run to completion, so it accesses the final value of i.

Categories