Rather than just present a few JavaScript examples for people to look at, lets get in to actually running JavaScript code.
The first method, is to just use the browser. The browser already has a built in JavaScript engine, so no need to download any additional tools. You can access Developer Tools in most browsers by pressing F12. Feel free to do so from this page, it won't interrupt your browsing. The Developer Tools pane should appear at the bottom or side of the window. Pressing F12 again will close it. The "Console" tab of the developer tools allows you to enter JavaScript directly, which will run the code immediately and display the results.
For demo purposes, here's some sample JavaScript code. It's just a quick run through of a few basic JavaScript data types.
script.js:
console.log("Hello World!");
var x = 2;
var y = 3;
console.log("x + y =", x + y); /* 5 */
function f(a, b) {
return a * b;
}
console.log("f(x, y) = ", f(x, y)); /* 6 */
var arr1 = [10, 11, 12];
var arr2 = [13, 14, 15];
var arr3 = arr1.concat(arr2);
console.log("arr3 = ", arr3); /* [10, 11, 12, 13, 14, 15] */
console.log("arr3[0] =", arr3[0]); /* 10 */
console.log("arr3[1] =", arr3[1]); /* 11 */
console.log("arr3[2] =", arr3[2]); /* 12 */
var obj = {
prop1: "some string",
prop2: 10,
prop3: [3, 5, 7],
prop4: f,
prop5: {
a: 1,
b: 4,
x, /* shorthand for 'x: x' */
y /* shorthand for 'y: y' */
}
};
console.log("obj = ", obj);
console.log("obj.prop5.y = ", obj.prop5.y);
console.log("typeof x =", typeof x); /* number */
console.log("typeof 'Hello World!' =", typeof 'Hello World!'); /* string */
console.log("typeof f =", typeof f); /* function */
console.log("typeof obj =", typeof obj); /* object */
console.log("typeof [] =", typeof []); /* object (Array is an 'object') */
You could type, or copy/paste that into the Developer Tools Console. It would work. Though it's not much of a way to develop longer code. Instead, you could download, paste, or write code into a JavaScript file. The browser can't run just a raw JavaScript file though. It needs to be embedded into or linked from a page to run. Here's a minimal structure for an HTML page:
minimal.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Minimal HTML Host for JS</title>
<script src="script.js"></script>
</head>
<body>
</body>
</html>
It's a blank page, with nothing to display, but serves as an adequate host for running some JavaScript. It contains a script tag, which links to the JavaScript file. These two files can be opened locally in a web browser (Linux screenshot):
If you have the Developer Tools Console open, you'll see the result of running the script when you load the page:
For more info on Developer Tools:
Chrome Developer ToolsFirefox Developer ToolsExplorer Developer Tools
Script files attached below.