Understanding the for Loop - JavaScript

Hey everybody,

I think i am still confused about the loop stuff. And I really dont know how to proceed. Below, Im not looking for the solution, I just need to understand how should I do and hopefully someone could explain me very clearly :wink: Thanks !

For example in the challenge called “Title Case a Sentence” I made this :

First of all, my strategy is :

  1. From String Sentence => Array of words of that sentence : [“i’m”, “a”, “little”, “tea”, “pot”]
    NO PROBLEM FOR THIS its “Line 2” in the code below.

  2. From [“i’m”, “a”, “little”, “tea”, “pot”] => [ [“i”," ’ ",“m”], [“a”], [“l”,“i”,“t”,“t”,“l”,“e”], [“t”,“e”,“a”], [“p”,“o”,“t”] ]
    HERE THE PROBLEM START, to MAKE THIS I WANT TO MAKE A LOOP, AND ITS RETURNING ME ONLY THE FIRST ARRAY

  3. From [ [“i”," ’ ",“m”], [“a”], [“l”,“i”,“t”,“t”,“l”,“e”], [“t”,“e”,“a”], [“p”,“o”,“t”] ] => replace first index of the array to Uppercase.
    FIRST I NEED TO FIGURE OUT THE LOOP :smiley:


function titleCase(str) { //input: (“I’m a little tea pot”);
arrayWord = str.toLowerCase().split(" "); //output: [“i’m”, “a”, “little”, “tea”, “pot”]

for (var i = 0; i < arrayWord.length; i++){
return arrayWord[i].split(""); //output : problem only returning the first [0]

}

}

titleCase(“I’m a little tea pot”);

Your for-loop’s header is correct. But keep in mind that the return keyword immediately stops the function it is in and return a value (and if it’s in any loop, the loop stops too). What your code does is it returns an array of characters from the first word. That’s because on your loop’s first pass, it hits a return right away.

For now, step away from the loop and think of how you’d title-case a word. Say you have

var word = 'hello';

How will you make that variable contain the word 'Hello'?.

There you go:
var word = “hello”;
word.charAt(0).toUpperCase()+word.slice(1);

You’re close! Remember that strings are immutable, and functions that manipulate strings only return new strings based on the original. If you tried console.log(word) afterwards, you’ll get back the same 'hello' string. You’ll have to reassign the word variable.

var word = 'hello';
word = word.charAt(0)....

Now try to combine this with a for-loop to do the same for each word.

1 Like

I want for the loop to go through the arrayWord and for each word give me the first letter uppercase, so I first declare var word as an array and then in the loop say that this variable is equal to : same example as “hello” above but for each word in the array…

function titleCase(str) { //input: (“I’m a little tea pot”);
arrayWord = str.toLowerCase().split(" "); //output: [“i’m”, “a”, “little”, “tea”, “pot”]
var word = [];

for (var i = 0; i < arrayWord.length; i++){
word = arrayWord[i].charAt(0).toUpperCase()+word.slice(1);

}

}

titleCase(“I’m a little tea pot”);

We’re almost there! Take a look at word.slice(1). Are you sure that you’re calling slice with the right variable? Also, note where we are going to store this new title-cased word. Recall from the example above that we’re storing the title-cased word into the same variable as the original word.

var word = 'hello';
word = word.charAt(0).toUpperCase() + word.slice(1);

Yes true i’ve made a mistake. So it’s :
var word = [];

for (var i = 0; i < arrayWord.length; i++){
word = arrayWord[i].charAt(0).toUpperCase()+arrayWord[i].slice(1);

}

but still don’t work :confused:

What happens in your code is that you’re storing the new strings into the same variable, overwriting whatever’s previously stored there.

If you get this right there’s one final line that you’ll have to add, and you’re done!

Thats why I said that I didnt understand the loop properly :

var word = “”; or var word = []; // actually here i dont understand the difference, but i know that i need to declare a variable if I use a new variable in the loop…

for (var i = 0; i < arrayWord.length; i++){
word = arrayWord[i].charAt(0).toUpperCase()+arrayWord[i].slice(1); // here I transform each word in array into hello => Hello like the example you explain me.
return word; // Here is return only the first cuz the loop is breaking when a return called. So i really dont know what to return… I though the line above should already return me the good thing.

}

Remember that a variable can only hold one value at a time. The code for title-casing is definitely correct, but you’re storing the new words into the same container.

Hmmm… okay, let’s try this one. Keep the var word = []; line and let’s push the new words there (maybe even rename the array to newWords since it’s now an array for containing the new words).

Ok I understand even if I have my loop I need to push the new words in my new Array, so I have this…but still something missing :stuck_out_tongue: :

function titleCase(str) { //input: (“I’m a little tea pot”);
arrayWord = str.toLowerCase().split(" "); //output: [“i’m”, “a”, “little”, “tea”, “pot”]
word = [];

for (var i = 0; i < arrayWord.length; i++){
newWord = arrayWord[i].charAt(0).toUpperCase()+arrayWord[i].slice(1);
word.push(newWord); // also i dont understand why in this line i Cannot write “word = word.push(newWord);” it say word.push is not a function…

}

}

titleCase(“I’m a little tea pot”);

You’re on the right track. You just have to connect ( join ) array elements so that the separator is a space.

What .push returns is the new length of the array after pushing a new item. In effect, when you do word = word.push(...);, you’re overwriting the array in that variable with a number. You get that error message because in your loop’s next pass, you’re now attempting to call .push with a number instead of an array, and numbers don’t have a .push method defined.

And yes, now that you have this array of new words you can now .join them, then return the .joined words.

yes thank you kevcomedia for your explanation and your time its more clear now :slight_smile: i finally find the answer

1 Like

Hey again, im on Chunky Monkey exercice and there is a similar problem, and try to understand one solution that I found:

This is How I read the code bellow, check my comment. And the fact is that when we enter the loop for the first time could you explain me what we have… because for me : arr.splice(0,size) should return [2,3,4,5] and then newArray.push(subArray); should give a number of 4, for the first loop… how to read the 2nd and the 3rd ?


function chunkArrayInGroups(arr, size) {

var arraySize = arr.length/size; // output : 6/2 = 3

var newArray = []; //creation of new Array

for (var i = 0; i < arraySize ; i++){ _//loop from [0] to [2]_

    var subArray = arr.splice(0,size); _// remove x (size) elements from index 0_
    
    newArray.push(subArray); _// output : a number for each loop.._

}

return newArray;
}

chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2);

Starting from the first element in arr, .splice(0, size) removes the first size elements.

If arr starts as [0, 1, 2, 3, 4, 5] and size is 2, then at the loop’s first pass .splice will remove 0 and 1 from arr, then return an array of the removed elements (which is then pushed to newArray). arr is now [2, 3, 4, 5] after splicing. You make a second pass and do the same, this time you get 2 and 3 (because now arr starts with 2). You repeat this until i hits arraySize.

If you have more questions, ask again, but I won’t be replying for the next few hours (time to sleep :sleepy:) and hopefully someone else comes along and answer them :slight_smile:

1 Like

Try to use console.log to better understand each step of the loop.
Here is your modified function:

function chunkArrayInGroups(arr, size) {

    var arraySize = arr.length/size; // output : 6/2 = 3
    console.log("arraySize is: ", arraySize);
    var newArray = []; //creation of new Array
    console.log("newArray is: ", newArray);

    for (var i = 0; i < arraySize ; i++){ //loop from [0] to [2]_
    console.log("--------------------")
        console.log("This is a loop: i = ", i);
        var subArray = arr.splice(0,size); // remove x (size) elements from index 0_
        console.log("Inside this loop subArray is :", subArray);
        
        newArray.push(subArray); // output : a number for each loop.._
        console.log("Inside same loop newArray looks like: ", newArray);
        console.log("####################");

    }
    console.log("And at the end of our loop, newArray looks like:")
    console.log(newArray);
    console.log("$$$$$$$$$$ END OF FUNCTION ##########");
    return newArray;
    }

    chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2);
2 Likes

Right now its pretty clear :slight_smile: thanks again and have a good night :slight_smile: me i will still code im in Europe :smiley:


function chunkArrayInGroups(arr, size) {

var arraySize = arr.length/size; // output : 6/2 = 3

var newArray = []; //creation of new Array

for (var i = 0; i < arraySize ; i++){ //loop from [0] to [2] 

    var subArray = arr.splice(0,size); // remove x (size) elements from index 0
    //1st loop : subArray = [0,1] and arr = [2,3,4,5]
    //2nd loop : subArray = [2,3] and arr = [4,5]
    //3rd loop : subArray = [4,5] and arr = []
    newArray.push(subArray);  
    //1st loop : push 1 element : [0,1] to newArray, newArray=[[0,1]]
    //2nd loop : push 1 element : [2,3] to newArray, newArray=[[0,1],[2,3]]
    //3rd loop : push 1 element : [4,5] to newArray, newArray=[[0,1],[2,3],[4,5]]
}

return newArray; //returning the newArray of the last Loop !

}

chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2);

1 Like