improved javascript logic