JavaScript By Example

Using Functions: 3. Returning An Object

When you first consider how functions work, one of the limiting factors on what you can do with them is that while you can feed as many parameters to them as they need, they can only return one. Now if what they could return was just a variable that could hold but one value then this would be the limiting factor that it appears to be. It isn't a limiting factor at all though once you realise that you c an return an object and so return as many values as you need all at once simply by making them all properties of that object.

To return an object from a function is no different than returning a variable from the function except that you need to create the object within the function instead of just setting a variable.

In this example our function creates the object within the return statement itself and creates an object with two properties that will pass back the current amount that the page has been scrolled both in the x (horizontal) and y (vertical) directions. As each value can be determined using multiple ternary operators to set each value in a single statement we can use the shorter version of an object declaration in this instance and not need anything else within the function except for the return statement.

var pos, txt;
scrollpos = function() {
return {
'x': window.pageXOffset ? window.pageXOffset : document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft, 'y': window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop

pos = scrollpos();
if (pos.x > 0) txt = 'scrolled to the right';