Using the for command in Javascript

Asked

Viewed 110 times

-2

People, can you help me ? I am trying to get a function to be executed and to return the word "Blue" 4 times, through a Cycle. I tried to write this here, but it gave the following error

Referenceerror: imprimirAzul4 is not defined.

That’s the code I wrote:

for (var i = 0; i < 5; i++) {
  function imprimirAzul4 () {
    return "Azul";
  }
}

Can anyone tell me where it’s wrong?

  • Your code and your error have nothing to do with each other... which is to say I believe that this error comes from another version of code and not the one in question... you can put the complete code that gave that error?

  • Strange, that’s the code. follow: for (var i = 0; i < 5; i++) { Function imprimirAzul4() { Return "Blue"; } } Error: Solution.js:29 var muki_query_result = printAzul4(); Referenceerror: printAzul4 is not defined

  • 1

    this error is from mumuki island, it has a lot of equal questions of this mumuki in a short period of time and of this function including

  • Are you sure about this? Because if it is, it’s very serious. This platform has a partnership with a Programming school, and we are doing online exercises that count points, in a kind of vestibular. Who has the best placements is awarded a full course of programming. If the plafatorma is in trouble, may require recount....

2 answers

0


You have to declare the function before the go and call it as code below:

function imprimirAzul4() {
    return "Azul";
}

for (var i = 0; i < 4; i++) {
    imprimirAzul4();
}

Or puts the for inside the function:

function imprimirAzul4() {
    for (var i = 0; i < 4; i++) {
        console.log("Azul");
    }
}

imprimirAzul4(); // chamada da função

0

You can either do @Benilson answered declare the function outside of the looping, or call the function right after declaring, this technique is called self-executing Function which is basically a function that is executed soon after being declared.

for (var i = 0; i < 5; i++) {
  (function imprimirAzul4() {
    console.log("Azul");
  })();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.