JavaScript solution to ex2