It's easy to knock the imaginary friend (IF). The knocking takes its lead from the idea of the value of the IF as wish-fulfilling substitutive pseudo-satisfaction. This IF fills a gap but through desire's self-deceiving palliation rather than through desire's genuine satisfaction. It takes us further away from reality; it entrenches a self-deception. This IF doesn't help us accommodate, doesn't help us face the world in an honest way, doesn't help us tackle our loneliness, but encourages a drifting away into the pallid shades of faery.
On this more fundamental understanding, the function of the IF isn't to conjure an imaginary companion for such wanderings in the void. It's rather to keep alive the axis of relatedness in our inner life, an axis which provides warmth to our heart and opens us to meaning and value in our relations. Such an IF, far from being a salve for everyday loneliness, may even function as its condition of possibility. What I mean is that without that axis being energised by the relationality cultivated by the IF, perhaps we might lose relationality altogether, and thereby lose the possibility of enjoying or missing the company of others.
Might God - the God of love, that is - be the supreme IF? And, if so, might He fulfil a function really quite other than any mere wish-fulfilment? Might praying to Him keep us alive to relatedness at times when otherwise we may drift off into depression's drifting void? Perhaps such prayer not only staves melancholy or apathy but also, through keeping us alive to what is met with in relatedness - through disclosing the other to us in her otherness under the aspect of love - keep us on the moral ball. Keep in check our centripetal disposition to self-centredness; keep alive our centrifugal disposition to caring connection.
Theological afterword: I'd be disappointed to be read as implying that God is an imaginary as opposed to a real Being! Whilst I know what it is to distinguish between a real childhood friend and an imaginary childhood friend, I don't think I know what it is to distinguish between (to pick a common understanding of God) a Ground of Being which is Love that is real and one that is imaginary. Do many of our concepts of 'God' really make room for an imaginary/real contrast - any more than, say, those of 'space' or 'time' do? We may ask whether a certain space is real or imagined, but space itself? (It's not as if the concepts of 'space' or 'God' do their work by 'referring to' or by 'picking out' something.) What notions of 'real' and of 'God' are we working with if we ask whether or not God is but an imaginary being or instead has a real existence? (They don't seem to be the ones met with in religious texts. So why use them?)