Home > Enterprise >  number not getting added and printed in for loop
number not getting added and printed in for loop

Time:12-09

i testing some codes, and i need a logic for my program, but i tested in a separated arquive and i got the following problem:

let numero = 0;
const string = `aaa: ${numero}`

for(let i=0; i<3;i  ) {
  console.log(string)
  numero  = 1
}

console.log(numero)

but the result is this:

aaa: 1
aaa: 1
aaa: 1
4
  • why the loop are adding , but in string continue with the value of 1?

someone can explain what is my error? javascript is really weird some times xD

CodePudding user response:

write string = aaa: ${numero} after for(let i=0; i<3;i )

The reason its doing that is because numero changes in the for loop but the string is declared outside of the for loop and is therefore constant.

CodePudding user response:

The reason of this behaviour - scope. When you use console.log into loop you get numero from global scope that = 0.

Just use follow code:

let numero = 0;
const string = 'aaa: ';

for(let i=0; i<3;i  ) {
  console.log(string   numero);
  numero  = 1
}

console.log(numero)

CodePudding user response:

For two reasons:

In your case specifically: You are assigning the value outside your loop that means that string is assigned only once, so it will never change.

Moreover string is a constant and technically shouldn't change (there are exceptions, for example when your constant is an object or an array). If you try to change it (inside the loop) you will get an error. Instead of const use let, because you want to change it.

let numero = 0;
let string = `aaa: ${numero}`

for(let i=0; i<3;i  ) {
  console.log(string)
  numero  = 1
  string  = 1
}

console.log(numero)

CodePudding user response:

The issue is that when you set the string variable it is using a string literal which only uses the value of numero when you created it - which is 0. It doesn't dynamically update itself. You have set it equal again to a new value;

You have 2 options

  1. Change the string from const to let so you can change its value, and update the value of the string variable within the for loop like this:
let numero = 0;
let string = `aaa: ${numero}`;

for (let i = 0; i < 3; i  ) {
    string = `aaa: ${numero}`;
    console.log(string);
    numero  = 1;
}

console.log(numero)
  1. Create a function that returns the updated string every time it's called inside the for loop, like this:
let numero = 0;

function updateString() {
    return `aaa: ${numero}`;
}

for (let i = 0; i < 3; i  ) {
    console.log(updateString());
    numero  = 1;
}

console.log(numero);
  • Related