Chris Walsh
Chris Walsh

Reputation: 3523

javascript return function returns undefined

Can anyone explain why the first of my three sample functions (ref failFunc()) should return an undefined value rather than a valid string?

I know I can fix the problem by wrapping the expression in brackets (ref worksFunc1()) or placing the result in an intermediate variable (ref worksFunc2()) but the fact the first function failed to return a string goes against anything I've experienced in other programming languages.

Fiddle is here: http://jsfiddle.net/BloodBaz/zGLmy/

JavaScript:

var rs = {};

rs.failFunc = function(n)
{
    var h = "0010";
    var m = "15";
    var s = "12";
    var c = "10";

    return 
        h.substr(h.length - 4) + ":" + 
        m.substr(m.length - 2) + ":" + 
        s.substr(s.length - 2) + "." + 
        c.substr(c.length - 2);
}
rs.worksFunc1 = function(n)
{
    var h = "0010";
    var m = "15";
    var s = "12";
    var c = "10";

    return (
        h.substr(h.length - 4) + ":" + 
        m.substr(m.length - 2) + ":" + 
        s.substr(s.length - 2) + "." + 
        c.substr(c.length - 2));
}
rs.worksFunc2 = function(n)
{
    var h = "0010";
    var m = "15";
    var s = "12";
    var c = "10";

    var res =
        h.substr(h.length - 4) + ":" + 
        m.substr(m.length - 2) + ":" + 
        s.substr(s.length - 2) + "." + 
        c.substr(c.length - 2);
    return res;
}


var res = rs.failFunc();
document.getElementById('output1').innerHTML = res;
var res = rs.worksFunc1();
document.getElementById('output2').innerHTML = res;
var res = rs.worksFunc2();
document.getElementById('output3').innerHTML = res;

HTML:

<div id='output1'>output</div>
<div id='output2'>output</div>
<div id='output3'>output</div>

OUTPUT:

undefined
0010:15:12.10
0010:15:12.10

Upvotes: 1

Views: 127

Answers (1)

Pointy
Pointy

Reputation: 413702

JavaScript syntax is strange. One particularly odd part is that a return statement followed by a newline is taken to be return;. A return without an expression means that to the caller, the return value is undefined.

Thus,

return 
    h.substr(h.length - 4) + ":" + 
    m.substr(m.length - 2) + ":" + 
    s.substr(s.length - 2) + "." + 
    c.substr(c.length - 2);

is effectively the same as

return;
    h.substr(h.length - 4) + ":" + 
    m.substr(m.length - 2) + ":" + 
    s.substr(s.length - 2) + "." + 
    c.substr(c.length - 2);

Read all about it in the language spec.

Upvotes: 4

Related Questions