Why is this function returning undefined?

You need $w.OnReady() for your page and dataset. Also be sure collection is read-enabled.