1

I've recently picked up some javascript code - because I'm no js expert, once I get it running, I like to disect it so that I can better my understanding.

Here's the code:

function checkCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(";");

    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];

        while (c.charAt(0) == " ") c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);

    return null;
}

The bit that's confusing is the stacked while and if statement - if I add curly brackets, I get a clearer picture like this:

        while (c.charAt(0) == " ") {
            c = c.substring(1, c.length);
        }
        if (c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length, c.length);
        }

But what I can't understand is why a while statement is being used at all - surely an 'if' would be more appropriate - or have I got the brackets wrong?

Clarification would be great.

ViRuSTriNiTy
  • 5,017
  • 2
  • 32
  • 58
John Ohara
  • 2,821
  • 3
  • 28
  • 54
  • 2
    You are using a while statement to cut all whitespaces at the beginning. An if-statement would cut only once! Moreover culry brackets are optional, if the body is just one line :) – Tobias S Jul 26 '16 at 11:49
  • 3
    You loop to remove every space at the beginning of c. It is a left trim of the String c. – AxelH Jul 26 '16 at 11:50
  • 2
    `.trim()` is what you should use. seems you are trimming the string. – Jai Jul 26 '16 at 11:52
  • 1
    @Jai `.trim()` is probably right, but are we sure he also want to remove spaces at the end of the string? – rypskar Jul 26 '16 at 11:56

2 Answers2

1

If you have a text starting with several spaces, first you will get c.charAt(0) == " " as true, then the first character is removed. Then the character at the beginning of the string will be the 2nd space you originally had so it will still be true and the space will be removed. This will continue until you don't have any space at the beginning.

rypskar
  • 2,012
  • 13
  • 13
1

I hope this answer will give you more clarity.

I am posting an answer as i am not able to add comment :)

If Statement :-

An if statement checks if an expression is true or false, and then runs the code inside the statement only if it is true. The code inside the loop is only run once...

While Statement :-

A while statement is a loop. Basically, it continues to execute the code in the while statement for however long the expression is true.

When to use a while loop:

While loops are best used when you don't know exactly how many times you may have to loop through a condition - if you know exactly how many times you want to test a condition (e.g. 10), then you'd use a for loop instead.

Krutika Patel
  • 312
  • 1
  • 17