Troubleshoot my code

Attached, when I was practicing my Back-end course I faced this problem and I do not know if my code is wrong or there is something missing in my code. Please could someone explain why was my code wrong? Thank you in advance.

Is a console.log statement the same as a return statement?

Furthermore, what is the return value of a console.log statement? What does the documentation say?

2 Likes

The only thing I could think of is

console.log(order(3,'chocolate'));

and just have the function return the string, and print it when calling. I redid your code in the directory and got the same result so my best guess is its an error on codeacadamy’s side

Killjoy alert:

A function’s primary role is to return something. That’s my conviction, at least. Yes, there are occasions when we need to abstract some repetitive log outs, but they won’t be in the normal flow. JS puts log calls on the back burner in the call stack. Going to leave the reader to really explore this avenue. Sorry to be vague. The importance of this will be apparent on further reading.

It is the caller’s responsibility to handle arguments and returns, not the function(s) being called (short of the repetitive log calls, which in this picture are last in the function call sequence).

This function returns this value, that function returns that value, even if it is two calls to the same function. We are free afterward to log out both results immediately, using a no-return (undefined) function, without delay.

Bottom line, if the primary role of a function is not exclusively centered upon logging, then it should not log at all, especially not in loops. JS is not going to render the way we anticipate. All the log calls will be pushed to the call stack and not execute until the script engine releases the execution space. Don’t log inside functions, except to debug, and then only sensibly, and removed immediately afterward.

const foo = function (x) {
    return x
}

Easy enough to be deceived by the simplicity of the above function definition. It takes an object (primitive or compound), and returns that object.

More succinctly, it returns that object reference in the case of plain objects and arrays, so not a new copy of the object.

 > a = {bar: 42}
<- {bar: 42}
 > b = foo(a)
<- {bar: 42}
 > b['baz'] = b.bar / 6
<- 7
 > a.baz
<- 7
 > 

Drilling deeper in class constructors…

class Foo {
    constructor (bar) {
        this.bar = bar
    }
    print (x) {
        console.log(this[x])
    }
}
 > a = new Foo('baz')
<- Foo {bar: 'baz'}
 > b = foo(a)
<- Foo {bar: 'baz'}
 > b['baz'] = 'faz'
<- 'faz'
 > a.print('baz')
   faz
<- undefined
 > 
1 Like