Search code examples
javascriptuncaught-exception

unexpected identifier in javascript, but I have declared the variable


I've looked at this file for an hour and have tried a ton of permutations.

$(document).ready(function() {

var unreadMessages = document.getElementsByClassName("unreadMessage");

var previousEntries;

chrome.storage.sync.get(null, {
    var previousEntries;
    previousEntries = (data["item"]);
});

console.log(previousEntries);


});


Why does previousEntries throw an "Uncaught SyntaxError: unexpected identifier"?

This seems to be the most straightforward task. Is it a } () or , issue?


Solution

  • $(document).ready(function() {
    
      var unreadMessages = document.getElementsByClassName("unreadMessage");
    
      var previousEntries;
    
      //                            vvvvvvvvvvvvvv
      chrome.storage.sync.get(null, function(data){
        // var previousEntries;              And if you want to access this variable outside,
        previousEntries = data["item"];   // don't redefine it here (no "var" keyword).
        logValue();                       // Now that the variable is set, you can use it
      });
    
      // console.log(previousEntries);    // Undefined, because it is not set yet.
    
      function logValue(){
        console.log(previousEntries);     // Now it should work (called from get's callback).
      }
    
    });
    

    The reason the variable is not set yet is that chrome.storage.sync.get is, just like Ajax or a setTimeout, asynchronous. Imagine doing this:

    var myVar;
    
    setTimeout(function(){
       myVar = 'Hello world!';
       console.log(myVar);     // logs "Hello world!" to the console
    }, 100);
    
    alert(myVar);              // alerts undefined