Example Code

Embedding JavaScript in an HTML page

You can embed JavaScript code in an HTML page via a <script> element.

There are two basic ways to do this. In the first method we can embed some JavaScript code directly into a page by placing the code directly in a <script>...</script> element, like this:

<script>
console.log("Hello from JavaScript!)
</script>

In the second method you can link a JavaScript source code file into your page by using the src attribute of a <script> element.

<script src="example.js"></script>

If you do a View Source on this page you will see that this page uses both of these methods to put some JavaScript in the page. You can see the code in the example.js file by clicking the Example Code button above.

When you place JavaScript code in a page via a <script> element that code will get evaluated as soon as the page encounters that element.

Accessing the JavaScript console

All of the JavaScript examples I am going to show today print their output to the JavaScript console. All browsers have a JavaScript console that you can access via the browser's developer tools. For example, to access the console in Chrome, just right-click in any page and select the Inspect command. This brings up the developer tools. One of the tabs in the developer tools is the Console tab where you can view the console.

The JavaScript code embedded in this page contains a number of calls to the console.log() command. You can see the messages printed by those calls in the console.

Basics of JavaScript: Strings

Strings in JavaScript are similar to Java strings. You can concatenate strings with +, and all strings are objects. Here is a link to a page that documents some string methods available in JavaScript.

The JavaScript examples I linked into this page show some basic examples of string manipulations.