Introduction
Introduced at the dawn of the web, JavaScript is a powerful and expressive language that runs inside the browser in conjunction with HTML and CSS. Based on an open standard called ECMAScript, JavaScript has quickly become the "programming language of the web." All the power of jQuery is accessed via JavaScript, so needless to say, it's an important language to learn. Having a basic knowledge of JavaScript will go a long way in understanding, structuring, and debugging your code.
This guide covers the foundational concepts of JavaScript, as well as frequent pitfalls developers fall into during their first foray into the language. When possible, we'll relate the JavaScript you learn here to how it's applied in jQuery.
If you have experience with other programming languages, good for you! If not, don't worry. We'll take it slow and teach you everything you need to know to unlock the power of jQuery with JavaScript.
Running Code
External
The first and recommended option is to write code in an external file (with a .js
extension), which can then be included on our web page using an HTML <script>
tag and pointing the src
attribute to the file's location. Having JavaScript in a separate file will reduce code duplication if you want to reuse it on other pages. It will also allow the browser to cache the file on the remote client's computer, decreasing page load time.
<!-- Code is written in a .js file, included via the script tag src attribute. -->
<script src="/path/to/example.js"></script>
Inline
The second option is to inline the code directly on the web page. This is also achieved using HTML <script>
tags, but instead of pointing the src
attribute to a file, the code is placed between the tags. While there are use cases for this option, the majority of the time it is best to keep our code in an external file as described above.
<!-- Embed code directly on a web page using script tags. -->
<script>
alert( "Hello World!" );
</script>
Syntax Basics
Comments
JavaScript has support for single- and multi-line comments. Comments are ignored by the JavaScript engine and therefore have no side-effects on the outcome of the program. Use comments to document the code for other developers. Libraries like JSDoc are available to help generate project documentation pages based on commenting conventions.
// Single- and multi-line comments.
// This is an example of a single-line comment.
/*
* this is an example
* of a
* multi-line
* comment.
*/
Variable Definition
Variables can be defined using multiple var
statements, or in a single combined var
statement.
// This works:
var test = 1;
var test2 = function() { ... };
var test3 = test2( test );
// And so does this:
var test4 = 1,
test5 = function() { ... },
test6 = test2( test );