Skip to content
Advertisement

why doesn’t this work? it’s a simple console log inside a loop [closed]

JavaScript

the output gives nothing. why is it this way? I want it to console.log the value position. I have used both node and the chrome developer tools console. Doesn’t work on either one.

Advertisement

Answer

As much as your question is not clear enough, I hope I can shed light to the use of for…loop.

for…loop is used for iteration. To traverse(pass-through) a sequence(such as string) or collections(such as arrays), which are subscriptable(i.e use index numbers). To be able to use for…loop syntax, you need to provide 3-parts in the for…loop declaration part. initialization, test_expression and step. Although, their use IS NOT RESTRICTED to within the pair of parenthesis. That is why your piece of code can be used just needs a little restructuring. In fact, they can be omitted entirely to form an infinite loop. See syntax below:

JavaScript

Before the body of the loop (denoted by above) can be executed, your test_expression MUST evaluate to true. Your initialization and step are ensuring that at a point, that test_expression is evaluated to false, so that your for…loop does not enter into an infinite loop.

Let’s look closer at our Code[Follow my comment]:

JavaScript

NOTE: In Javascript, it’s not possible to provide a negative index like you did in your for…loop declaration. This is 100% possible with Python but not JS. That’s why your test_expression IS NOT evaluating to true.

JavaScript

…and undefined IS NOT EQUALS TO ” “.

SOLUTION 1: Consider restructuring your code as follows if you want to log position in the iteration up to the first occurrence of white-space:

JavaScript

…if this is your intention, you can simply achieve this by quickly locating your first white-space.

JavaScript

SOLUTION 2: If your intention is to count the number of words in your variable line, use the following:

JavaScript

…here, I have chained several methods to each other to feed the output of one method to the input of another. line.trim() removes the leading and trailing white-spaces(i.e spaces before and after the real sentence) .replace(” “, ” “) replace all occurrence of double white-spaces with single white-space. .split(” “) breaks the sentence into an array of words using the single white-space as delimiter. since white-spaces are used as separator of words. .length counts the total words in the array.

Feel free to ask me any question.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement