jgozal jgozal - 5 months ago 8
Node.js Question

Why can't I properly execute code in http://javascriptissexy.com/?

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

Invalid or unexpected token
error, usually on the last lines of whatever block of code I execute. I have tried using Chrome's and Firefox's consoles, node.js and the integrated node.js environment in Visual Studio's Code editor. I have tried taking out comments, trimming spaces, removing indentation and no matter what I do I still get the same error. A friend of mine was able to execute the code without doing anything to it. This is an example:

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