1

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

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

"Automatic Semicolon Insertion"!? Thanks for the answer. I'll have a good read of the spec you've provided and mark your answer in due course.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.