Categories
Modern JavaScript

Best of Modern JavaScript — Loops and Parameters

Spread the love

Since 2015, JavaScript has improved immensely.

It’s much more pleasant to use it now than ever.

In this article, we’ll look at JavaScript variables.

let and const in Loop Heads

We can use let and const in loop heads with the for, for-in, and for-of loops.

With the for loop, we can write:

const arr = [];
for (let i = 0; i < 3; i++) {
  arr.push(i);
}

We can write use let to make i only available in the block.

This is better than var which make the loop available inside the whole function:

const arr = [];
for (var i = 0; i < 3; i++) {
  arr.push(i);
}

const works like var , but we can’t change the value of i .

For example, we can’t write:

for (const i = 0; i < 3; i++) {
  console.log(i);
}

since we change the value of i .

We can also use the for-of loop to get the item from a loop.

For instance, we can write:

const arr = [];
for (let i of [0, 1, 2]) {
  arr.push(i);
}

to get the value.

We can also use const since we don’t change the array entry variable:

const arr = [];
for (const i of [0, 1, 2]) {
  arr.push(i);
}

The var variable will make the variable available outside the loop:

const arr = [];
for (var i of [0, 1, 2]) {
  arr.push(() => i);
}

The for-in loop works like the for-of loop.

Parameters as Variables

We can write parameters we let variables inside blocks if they don’t overlap with parameters.

For example, we can’t write:

function func(arg) {
  let arg;
}

since both args have the same scope.

We’ll get the ‘Uncaught SyntaxError: Identifier ‘arg’ has already been declared’ error.

However, we can write:

function func(arg) {
  {
    let arg;
  }
}

since arg is in the block.

However, with var , both are valid:

function func(arg) {
  var arg;
}

function func(arg) {
  {
    var arg;
  }
}

They both do nothing and they arg in the parameter and the block share the same scope.

If we have default parameters, then they’re treated as parameters.

For instance, we can write:

function foo(x = 1, y = x) {
  return [x, y];
}

since x is defined before y .

But we can’t write:

function bar(x = y, y = 2) {
  return [x, y];
}

since y isn’t defined when we assigned it to x .

Therefore, we treat default parameters as let variables.

They don’t see the scope of the body.

For instance, if we have:

const foo = 'bar';

function bar(func = x => foo) {
  const foo = 'baz';
  console.log(func());
}

bar()

Then we get bar .

The function in the function parameter takes foo from the outside and return it.

The foo inside bar has its own scope.

Conclusion

We can use let and const in loop heads and functions.

Default parameters are also treated as let variables.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *