Console returns undefined

so ive hijacked the console function

var log = Function.prototype.bind.call(console.log, console); console.log = function (a) { log.call(console, a); submitmsg("Log", a); }; 

this has the desired effect, however it also returns "undefined" as an unexpected bonus

I cannot understand why this makes me think that something is wrong here.

enter image description here

Hello world is generated by log.call(console, a) as expected

submitmsg() is my custom function

this works exactly the way I want, as I said, although I'm a little worried that it also returns “undefined” for reasons I don’t understand.


Note. The following code was published by OP as an answer to a question. Comments on the answer have been moved to comments on this issue.


So the correct code should be as follows:

 var log = Function.prototype.bind.call(console.log, console); console.log = function (a) { return log.call(console, a); submitmsg("Log", a) }; 
+6
source share
1 answer

If I understand your question correctly, this is because you are not explicitly returning anything from the function. When you do not return a value from a function, it implicitly returns undefined .

For instance:

 function example() {} console.log(example()); //undefined 

This is defined in the internal specification [[Call]] (the corresponding points are shown in bold):

  • Let funcCtx be the result of creating a new execution context for the function code using the value of the F [[FormalParameters]] internal property, the arguments passed to List args, and this value as described in 10.4.3.
  • Let the result be the result of evaluating FunctionBody, which is the value of the internal property F [[Code]]. If F does not have the Internal [[Code]] property, or if its value is empty FunctionBody, then the result will be (normal, undefined, empty).
  • Close the funcCtx runtime context by restoring the previous runtime context.
  • If result.type is throw, then throw result.value.
  • If result.type is return, then return result.value.
  • Otherwise, result.type should be normal. Return undefined.
+10
source

Source: https://habr.com/ru/post/919839/


All Articles