Properly scope variables in javascript