javascriptjquerynative-code

What does " [native code] " mean?


I tried to investigate the jQuery code, so I used this:

document.write($.constructor);

jsfiddle

I got this result:

function Function() { [native code] }

What does [native code] mean? Why can't I see the real code?

Tested with Google-Chrome


Solution

  • When you define functions in an interpreted language (as opposed to a compiled language). You have access to the file / string / text that defines the function.

    In JavaScript for example you can read the definition body text of a function you have defined:

    function custom( param ){
      console.log( param );
    }
    
    console.log( custom.toString() ); // <- Will display the full code (in text) of the function. 
    

    If you try to do the same for a function that is included by construction* in JavaScript it is not implemented as text but as binary.

    console.log( setInterval.toString() );
    
    // Will display: function setInterval() { [native code] }
    

    There is no reason to show the binary code that implements that function because it is not readable and it might not even be available.

    jQuery extends default JavaScript behaviour. It's one of the reasons it was so highly appreciated and praised as opposed to Prototype.js for example. Prototype was altering the natural behaviour of JavaScript creating possible inconsistencies when using Prototype alongside some other piece of code that relied on normal functionality.

    tl;dr:

    jQuery extends JavaScript, there is functionality implemented using native code (which performance wise is a good thing).


    *included by construction: Elaborating a bit on this part. JavaScript itself can be written/implemented in any language (C++, Java, etc.). In Chrome, the JavaScript engine (V8) is written in C++. Firefox's JavaScript engine (SpiderMonkey) is also written in C++.

    The functions that are defined by the language specification (ECMAScript) and should be included in the actual implementation, are written in another language (e.g. C++ in these 2 cases) and become available in JavaScript as built-in/native functions.

    These functions are actually compiled (binary) C++ code and thus cannot be displayed within JavaScript itself, e.g. using the [].map.toString() syntax.