Alistair
Alistair

Reputation: 109

How to wrap this in a javascript function?

I have a piece of code that I am trying to wrap in a function that returns the value of a cookie.

document.cookie.split(';').filter(function(s) {
  return s.search('constituency=') == 1
})[0].split(/(=)/).slice(2).join('');

In my browser console, this returns the cookie value perfectly. I want to be able to use this value in another function but when I try wrap it in a function it says 'undefined'.

Can anybody help me understand why?

function splitValues() {
  document.cookie.split(';').filter(function(s) {
    return s.search('constituency=') == 1
  })[0].split(/(=)/).slice(2).join('');
}

Upvotes: 1

Views: 71

Answers (3)

Angel Politis
Angel Politis

Reputation: 11313

In order for a function to work you need to return the result. In your case, you only return the result of the .search() method inside the function of the .filter() method.

You have to return the result of the .filter() method as a whole as well for it to work: ↓

return document.cookie.split(';').filter(function(s) {...}...

The entire function:

function splitValues() {
    return document.cookie.split(';').filter(function(s) {
        return s.search('constituency=') == 1
    })[0].split(/(=)/).slice(2).join('');
}

Upvotes: 2

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

You forgot the return statement:

function splitValues() {
  return document.cookie.split(';').filter(function(s) {
  //^^\\
    return s.search('constituency=') == 1
  })[0].split(/(=)/).slice(2).join('');
}

The return statement is the first statement inside the function.

Upvotes: 2

gurvinder372
gurvinder372

Reputation: 68393

you need to return the value

function splitValues() { 
   return document.cookie.split( ';' ).filter( 
    function( s ) { 
      return s.search( 'constituency=' ) == 1 
    })[ 0 ].split( /(=)/ ).slice( 2 ).join( '' );
}

Notice the return before document

Upvotes: 5

Related Questions