jgozal - 8 months ago 21

Node.js Question

I'm learning about Closures here. For some reason, I can't execute any of the examples. I get an

`Invalid or unexpected token`

`function celebrityID () {`

var celebrityID = 999;

// We are returning an object with some inner functions

// All the inner functions have access to the outer function's variables

return {

getID: function () {

// This inner function will return the UPDATED celebrityID variable

// It will return the current value of celebrityID, even after the changeTheID function changes it

return celebrityID;

},

setID: function (theNewID) {

// This inner function will change the outer function's variable anytime

celebrityID = theNewID;

}

}

}

var mjID = celebrityID (); // At this juncture, the celebrityID outer function has returned.

mjID.getID(); // 999

mjID.setID(567); // Changes the outer function's variable

mjID.getID(); // 567: It returns the updated celebrityId variable

This is driving me crazy. Please somebody help me solve this mystery.

Answer

There are invisible characters in you code which are throwing this errors, I've removed them here:

```
function celebrityID () {
var celebrityID = 999;
// We are returning an object with some inner functions
// All the inner functions have access to the outer function's variables
return {
getID: function () {
// This inner function will return the UPDATED celebrityID variable
// It will return the current value of celebrityID, even after the changeTheID function changes it
return celebrityID;
},
setID: function (theNewID) {
// This inner function will change the outer function's variable anytime
celebrityID = theNewID;
}
}
}
var mjID = celebrityID (); // At this juncture, the celebrityID outer function has returned.
mjID.getID(); // 999
mjID.setID(567); // Changes the outer function's variable
mjID.getID(); // 567: It returns the updated celebrityId variable
```