Bugbeeb
Bugbeeb

Reputation: 2151

Why does my javascript function return null?

I have a function that searches the cookies string for a specific cookie and returns its value but I don't understand why it keeps returning null when the cookie exists.

document.cookie = "userName=nameHere";
function getCookie() {
    document.cookie.split(";").forEach(cookie => {
        if (cookie.substring(0, cookie.indexOf("=")) == "userName") {
            var name = cookie.substring(cookie.indexOf("=") + 1);
            console.log(name);
            return name;
        }
    })
    return null;
}

>> getCookie()
//prints
nameHere
//returns
null

Upvotes: 1

Views: 749

Answers (3)

jperl
jperl

Reputation: 5112

A few things to note here:

  • forEach does not and is not supposed to return anything
  • your function is returning null because you told it to return null
  • don't hard code the name of the cookie you're looking for in the function, pass it as a parameter

That said, here is a working function:

document.cookie = "userName=nameHere";
function getCookie(cName) {
      const decodedCookie = decodeURIComponent(document.cookie) // deal with any special character
      // returns the value of the first element in the provided array that satisfies the provided testing function
      const cookie = decodedCookie.split(";").find(c => c.substring(0, c.indexOf("=")) == cName)
      if (!cookie) return null // cookie not found, return
      const value = cookie.substring(cookie.indexOf("=") + 1)
      return value
    }

console.log(getCookie('userName'))

Upvotes: 1

Ilijanovic
Ilijanovic

Reputation: 14904

If you take a closer look you will see that there are actually 2 functions.

    `.forEach(cookie => {`

You actually returning name in the arrow function

A solution could be to go with a for loop instead of forEach

Upvotes: 3

Cornelis
Cornelis

Reputation: 1107

My guess is that:

var name = cookie.substring(cookie.indexOf("=") + 1);

doesn't actually assign a name. Try putting an Alert, after the name var or log the name to check the contents.

Upvotes: -2

Related Questions