rma943
rma943

Reputation: 11

Can't figure out why my JavaScript for loop only loops once

I am trying to get my for loop to print each characters of a string argument individually, but when I run code, it only prints the first character. I can't seem to figure out why it doesn't keep looping through.

Here is my code:

function reverse (param) {
    for (var i=0; i<arguments.length; i++) {
        console.log(param.charAt(i));
    }
}

reverse("Test");

Upvotes: 1

Views: 46

Answers (4)

ABGR
ABGR

Reputation: 5235

This code is working as it should. arguments length is 1. To make it work as intented, you must use param's length

function reverse (param) {
  console.log(arguments)
    for (var i=1; i<=param.length; i++) {

        console.log(param.charAt(param.length - i)); //you need to correct here as well
    }

}
 reverse("Test");

On another note, you may make use of .reverse function as well. But it works on arrays. So you can do something like this:

console.log("Test".split('').reverse().join(''))

Upvotes: 1

Farrukh Abdusalamov
Farrukh Abdusalamov

Reputation: 1

function printLetters(string) {
    for (let letter of string) {
        console.log(letter);
    }
}
printLetters("test");

Here's how you print the letters to the console

Upvotes: 0

Sascha A.
Sascha A.

Reputation: 4636

Because you need length of param and not arguments.

function reverse (param) {
    for (var i=0; i<param.length; i++) {
        console.log(param.charAt(i));
    }
}

reverse("Test");

Upvotes: 0

Bruno Sendras
Bruno Sendras

Reputation: 601

Because arguments just contains ["Test"], so arguments.length is 1

Upvotes: 0

Related Questions