Using JavaScript in Your C++ Applications

JavaScript V8 is much faster than JavaScript in other browsers

Hackers working hackathon at laptops in dark office
Hero Images / Getty Images

When Google released its Chrome browser, the company included a fast implementation of JavaScript called V8, the client-side scripting language included in all browsers. Early adopters of JavaScript back in the era of Netscape 4.1 didn't like the language because there were no tools for debugging and each browser had different implementations, and different versions of Netscape browsers differed as well.

It wasn't pleasant writing cross-browser code and testing it on lots of different browsers.

Since then, Google Maps and Gmail came along using the whole Ajax (Asynchronous JavaScript and XML) technologies, and JavaScript had enjoyed a major comeback. There are now decent tools for it. Google's V8, which is written in C++, compiles and executes JavaScript source code, handles memory allocation for objects, and garbage collects objects it no longer needs. These design details explain why V8 is so much faster than the JavaScript in other browsers—it compiles to native machine code, not bytecode that has been interpreted.

Using JavaScript V8 in Your C++ Application

V8 isn't only for use with Chrome. If your C++ application requires scripting for users to be able to write code that executes at run-time, then you can embed V8 in your application. V8 is an open source high-performance JavaScript engine licensed under the liberal BSD license.

Google has even provided an embedder's guide.

Here's a simple example that Google provides—the classic Hello World in JavaScript. It is intended for C++ programmers who want to embed V8 in a C++ application

int main(int argc, char* argv[]) {

  // Create a string holding the JavaScript source code.
  String source = String::New("'Hello' + ', World'") ;

  // Compile it.
  Script script = Script::Compile(source) ;
  
  // Run it.
  Value result = script->Run() ;

  // Convert the result to an ASCII string and display it.
  String::AsciiValue ascii(result) ;
  printf("%s\n", *ascii) ;
  return 0;
}

V8 runs as a standalone program, or it can be embedded in any application written in C++. 

Format
mla apa chicago
Your Citation
Bolton, David. "Using JavaScript in Your C++ Applications." ThoughtCo, Sep. 19, 2017, thoughtco.com/using-javascript-in-your-candand-applications-3971807. Bolton, David. (2017, September 19). Using JavaScript in Your C++ Applications. Retrieved from https://www.thoughtco.com/using-javascript-in-your-candand-applications-3971807 Bolton, David. "Using JavaScript in Your C++ Applications." ThoughtCo. https://www.thoughtco.com/using-javascript-in-your-candand-applications-3971807 (accessed December 11, 2017).