Learn how to build and design websites with our tutorials.

Introduction To Javascript

View Tutorial Contents


What Is JavaScript?

JavaScript is a programming language that runs on a visitor's computer. It is mainly used as part of web browsers to make web pages interactive and to make web applications. It can also be used, and commonly is used, in server-side network programming to create games and desktop and mobile applications.

Javascript is also known as ECMAScript, which is the untrademarked name used for the standard, and is commonly abbreviated to JS.


Are JavaScript and Java the Same?

Are JavaScript and Java the same? The answer is no, they are not. JavaScript and Java are two completely different programming languages.


The JavaScript <script> Tag

JavaScript must be inserted within the opening and closing <script> tags. The opening <script> tag tells the web browser to start treating the text as a script, and the closing </script> tag tells the web browser to stop treating text as a script.

The only time that you can use JavaScript outside of the <script> tags is through the use of event handlers, which will be covered in another tutorial.

You may see some other, usually older, tutorials and examples include the type attribute of type="text/javascript" within the opening <script> tag. This type attribute is not required, the reason is because JavaScript is the default scripting language in HTML.

The example below is an HTML document (web page) that contains a simple line of JavaScript code that outputs some text, which in this example is "Hello World!".


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>
</style>
</head>
<body>

<script>
	document.write("Hello World!");
</script>
</body>
</html>

The example above will output the following text:


Hello World!


JavaScript Statements

JavaScript scripts and applications are made up of instructions that are meant to be executed by the computer. Basically, a statement performs an action. These instructions are called statements.

If JavaScript is placed within an HTML document, then it can be executed by the web browser.

The example below contains two JavaScript statements, each on its own line.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>
</style>
</head>
<body>


<script>
	var name = "John";
	document.write(name);
</script>
</body>
</html>

JavaScript statements are made up of:


JavaScript Values

There are two types of values in JavaScript: fixed values and variable values.

Fixed values are called literal values that you provide.

The values below are examples of fixed values.


10
3.14159
"This is a text"

Variable values are variables.

The values below are examples of variable values.


var x = 10;
var y = "10"
var text = "This is a text";


JavaScript Operators

An expression is any valid combination of valid variables, fixed values, operators and expressions that evaluate to a single value. The characters that are used to combine these values, for example, +, - and *, are called operators.

Below is an example of an expression.


var text = "This is a text";

Some of the most common JavaScript operators are listed below.

Operator Description
= assignment operator assigns values to variables
+ concatenation operator when used on strings, it is used to combine strings
+ addition operator when used on numbers, it is used to add number numbers
- subtraction operator it is used to subtract numbers
* multiplication operator it is used to multiply numbers
/ division operator it is used to divide numbers
% modulo (remainder) it divides the value of one expression by the value of another, and returns the remainder
++ increment operator it is used to increment the value of a variable by one
-- decrement operator it is used to decrement the value of a variable by one

JavaScript Keywords

JavaScript has a number of reserved words that cannot be used as identifiers (variable names). Reserved words in JavaScript are part of the Javascript language and each reserved word has a specific meaning. Using a reserved word will cause an error when the script attempts to run.

See the full list of JavaScript reserved words.

In the code example below, the JavaScript reserved word var tells the web browser to create a new variable.


var x = 10;


JavaScript Expressions

A JavaScript expression produces a value, but it does not have to perform an action.

The code example below contains lines that each contain an expression.



x
5 + 10
myFunction("x", "y")



JavaScript Comments

JavaScript comments is text and/or code within any JavaScript code that will be ignored and not executed.

JavaScript comments can be used to explain some JavaScript code, leave yourself or someone else a note, make code more readable and to prevent execution of some code for testing purposes.

There are Single line comments and also multiple line comments.

Single Line Comments

Single line comments in JavaScript only consist of two forward slashes (//) at the beginning of the comment. Any text or code that appears after the two forward slashes until the end of the line will be ignored and not executed.

The code example below contains two single line comments.


var myCar = "Ford"; // This is the variable for my car

// var carPrice; JavaScript will ignore this whole line

Multiple Line Comments

Multiple line comments in JavaScript start with a forward slash immediately followed by a asterisk (/*) and then with an asterisk immediately followed by a forward slash (*/). Any text or code that appears in between the beginning and the end of the comment tags will be ignored and not executed.

Multiple line comments can also span only one line, but that is what single line comment tags are for.

The code example below contains a multiple line comment.


/*
These are the variables for the script
This script validates form data
This is located in the sub-folder
*/
var firstName;
var lastName;
var telNumber;
var email;


JavaScript Is Case Sensitive

JavaScript identifiers are case sensitive.

In the code example below, the variables myFirstName and myfirstname two different variables.


var myFirstName = "John";
var myfirstname = "John";


JavaScript Variables

In Javascript, variables are containers for storing data values.

In the example below, "x" and "y" are variables.

<script language="javascript">
var x = 1;
var y = 2;
</script>

In the example above:

Learn more about JavaScript Variables.


Javascript Functions and Events

A Javascript function is a block of code that is made so that it performs a particular task when it is invoked, aka called upon. A Javascript is invoked when an event occurs. An event is when the web browser does something or when a user does something.

Some examples of events are:

Javascript functions are defined with the function keyword.

The Javascript function keyword is followed by the function name, which can be whatever name you decide to give it. Function names can contain letters (A-Z, a-z), digits (0-9), underscores (_), and dollar signs ($).

The Javascript function name is followed by parenthesis (()), which can contain parameters. If there is more then one parameter, they are separated by commas, for example, (name1, name2, name3)

Following the parenthesis are curly brackets ({}) which contains the code that is to be executed.

The basic syntax to create a function is shown below. This method is called a Function Declaration.


function functionName(parameter1, parameter2, parameter3, ...) {
    code to be executed
}

The example below is a function. The code within the function "alerts" you by displaying a pop-up box with a message, in this case "Hello World!". In order for this code to be executed, the function needs to be invoked.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>
</style>
</head>
<body>


<script>
	function clickButton(){
		alert("Hello World!");
	}
</script>
</body>
</html>

The example below is the same as the one, but it also includes the event that is used to invoke the function. In this example, the event is the click of a button.

In this example, the event is onclick, which is when the user clicks on a specified HTML element. When the user triggers the event, the specified function is invoked. In this case, the function will be "myFunction".


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>
</style>
</head>
<body>

<button onclick="clickButton()">Click Here</button>

<script>
	function clickButton(){
		alert("Hello World!");
	}
</script>
</body>
</html>

The example above produces the button that when clicked brings up an alert box.

JavaScript Naming Conventions

JavaScript naming conventions are a set of guidelines for naming variables, functions and other such entities.

One of the benefits of naming conventions include making it easier to understand code.

Some of the common naming conventions used to name variables are shown in the example below. Hyphens, underscores and camel case are commonly used to name variables.


var first-name;
var middle_name;
var lastName;


JavaScript And Unicode Character Sets

The Unicode character set is implemented in HTML, XML, JavaScript, Java, e-mail, ASP, PHP and more. The Unicode character set covers almost all of the character, punctuations and symbols in the world.


Where To Place Javascript In HTML Page?

You can any javascript within the <head> and/or <body> tags, however, usually the best place to include your Javascript within an HTML page in at the bottom of the HTML document, right before the closing </body> tag.

The example below shows you how to include Javascript in an HTML document right before the closing </body> tag, which is where it is generally recommended to place Javascript within HTML.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>
</style>
</head>
<body>


<script>
// some Javascript code
</script>
</body>
</html>

The example below shows you how to include Javascript in an HTML document within the <header>.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>
</style>
<script>
// some Javascript code
</script>
</head>
<body>

</body>
</html>


External Javascript

The use of external javascript is similar to external stylesheets. Using external Javascript should be used when the same Javascript code is used on more than one web page.

An external Javascript file is a file with a ".js" extension that contains Javascript code. That external Javascript file is then linked to from any HTML web page that you want using the <script> tag with the following attribute/value pair: src="fileName.js".

Javascript files should not contain the opening <script> or closing </script> tags, only the Javascript code.

The example below shows only the <script> tag with the source and a file name.


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

To make this more clear, I'll first provide with an example of an HTML document with Javascript that is included within the HTML document.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>
</style>
</head>
<body>


<script>
// some Javascript code
</script>
</body>
</html>

The example below is the same as above, except that I've taken out the Javascript and placed it into an external Javascript file and linked to it within the HTML document.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>
</style>
</head>
<body>


<script src="fileName.js"></script>
</body>
</html>

Only Javascript should be within the external Javascript file.


// some Javascript code

Advantages of External Javascript

Placing your Javascript in external files has the following advantages:


Outputting Javascript

You can output Javascript for display and print in the following ways:

Javascript alert() Method

The alert() method displays an alert box with a text that you specify and an OK button. The user has to click the OK button to get rid of the alert box and continue.

The syntax for the alert() method is window.alert() but the method can be written without the "window" prefix.

The alert() method accepts strings as parameter values.

The example below shows you how to use an alert box to display a text.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>
</style>
</head>
<body>

<script>
	alert("This is a text");
</script>
</body>
</html>

Javascript document.write() Method

The Javascript document.write() method writes a string of text to a document.

The Javascript document.write() method should only be used for testing purposes, the reason is that using the method after an HTML document is fully loaded will delete all of the existing HTML.

The example below shows you how to use the document.write() method.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>
</style>
</head>
<body>

<script>
	document.write("This is a text");
</script>
</body>
</html>

Javascript innerHTML Property

JavaScript allows you to access and change the HTML content of HTML elements with the use of the innerHTML property.

The id attribute defines the HTML element. The innerHTML property allows you to define and change its HTML content.

The example below changes the content of the paragraph that has an id of "test".


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>
</style>
</head>
<body>

<p id="demo">
Click the button below to change the content of this paragraph.
</p>

<button onclick="myFunction()">Click Here</button>

<script>
function myFunction() {
    document.getElementById("demo").innerHTML = "The content of this paragraph has been changed.";
}
</script>
</body>
</html>

The example above produces the paragraph and button below.

Click the button below to change the content of this paragraph.

JavaScript console.log() Method

The JavaScript console.log() method prints text to the web browser console. console.log() is useful for debugging JavaScript.

Below is an example of how to write to the web browser console.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>
</style>
</head>
<body>

<script>
	console.log("This is a text.");
</script>
</body>
</html>

Below is another example involving a variable.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>
</style>
</head>
<body>

<script>
	var a = "This is a text."
	console.log(a);
</script>
</body>
</html>