-2

I am watching a video about C programming, and the instructor has an example for loop that is written as such:

for(int i=0, n=strlen(c); i<n; i++)

In Javascript can we declare n in the same way as well? I'm trying to not set "i

Edit:

Thank you for the replys. Sounds like I can't do the code from above, but instead I would have to split it up into 2 separate line items like so:

const n = strlen(c); for(int i=0; i<n; i++)

bwkarr77
  • 1
  • 1
  • 1
    Yes, [in a similar way in the same place](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for_statement), but no, of course you cannot use `int`. – Bergi Dec 08 '19 at 18:57

2 Answers2

0

In Javascript can we declare n in the same way as well?

Yes. You can use either var or let there, and it makes a big difference: Inside the loop's block, if you use var, all loop iterations share a single variable. If you use let, each loop iteration gets its own variable. This only matters if you create closures within the loop.

Example of the difference:

for (var varvar = 0; varvar < 3; ++varvar) {
    setTimeout(() => {
        console.log(`varvar = ${varvar}`);
    }, 10);
}

for (let letvar = 0; letvar < 3; ++letvar) {
    setTimeout(() => {
        console.log(`letvar = ${letvar}`);
    }, 20);
}

(And if you use var, the variable exists throughout the function [or global scope, if you're doing this at global scope]. With let, it's confined to the for loop.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Don't forget about [`const` declarations](https://stackoverflow.com/q/31987465/1048572), although of course they're only useful if you don't initialise an immutable value and use that in your condition. – Bergi Dec 08 '19 at 19:09
  • @Bergi - Yeah. Not applicable to `for` loops, but very useful in other kinds of loops (`for-of`, `for-in`, `while`, ...). – T.J. Crowder Dec 08 '19 at 19:10
  • `for (const iterator = …; iterator.hasNext(); iterator.advance()) { … }` – Bergi Dec 08 '19 at 19:14
  • @Bergi - I suppose, if you don't try to modify the control variable in the increment. – T.J. Crowder Dec 08 '19 at 19:19
0
for(let i = 0; i < c.length; i ++) 
Sarath P S
  • 131
  • 5
  • I'm trying to not have javascript calculate c.length everytime the forloop iterates. With this way it has to use memory everytime it iterates. I'm guessing I'd have to declare n before my for loop, and use it as the condition statement. – bwkarr77 Dec 08 '19 at 20:57
  • Then you can do like `const length = c.length for(let i =0; i < length; I ++)` – Sarath P S Dec 09 '19 at 09:56