Using JavaScript in Your C++ Applications

Hackers working a 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. V8 is so much faster than the JavaScript in other browsers because it compiles to native machine code, not bytecode that has been interpreted.

JavaScript V8V8 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

// 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) ;
return 0;

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