JavaScript is the most popular programming language in the world.
It is the language for HTML, for the Web, for computers, servers, laptops, tablets, smart phones, and more.
This page contains some examples of what JavaScript can do in HTML.
The HTML DOM (the Document Object Model) is the official W3C standard for accessing HTML elements.
JavaScript can manipulate the DOM (change HTML contents).
The following example changes the content (innerHTML) of an HTML element identified with id="demo":
document.getElementById("demo").innerHTML = "Hello JavaScript";
The method document.getElementById() is one of many methods in the HTML DOM.
You can use JavaScript to:
There are several chapters, about the HTML DOM, later in this tutorial.
This example changes the value of the source attribute (src) of an HTML <img> element:
Click the light bulb to turn on/off the light
With JavaScript, you can change almost any HTML attribute.
Changing the style of an HTML element, is a variant of changing an HTML attribute.
document.getElementById("demo").style.fontSize = "25px";
With JavaScript, you can change almost any CSS value.
JavaScript is often used to validate input:
Please input a number between 1 and 10
JavaScript and Java are different languages, both in concept and design. |
In HTML, JavaScripts must be inserted between <script> and </script> tags.
JavaScripts can be put in the <body> and in the <head> section of an HTML page.
To insert a JavaScript into an HTML page, use the <script> tag.
The <script> and </script> tells where the JavaScript starts and ends.
The lines between <script> and </script> contain the JavaScript code:
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "My First JavaScript Function";
}
</script>
You don't have to understand the code above.
Just take it for a fact, that the browser will interpret the code as JavaScript.
Old examples may have type="text/javascript" in the <script> tag. This is no longer required. |
Often, JavaScript code is written to be executed when an event occurs, like when the user clicks a button.
JavaScript code inside a function, can be invoked, when an event occurs.
Invoke a function = call upon a function (ask for the code in the function to be executed).
You will learn much more about functions and events in later chapters.
You can place any number of scripts in an HTML document.
Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.
Often you will see scripts at the bottom of the <body> section. This can reduce display time.
Sometimes you will see all JavaScript functions in the <head> section.
Anyway, separating HTML and JavaScript, and putting all code in one place, is always a good habit.
In this example, a JavaScript function is placed in the <head> section of an HTML page.
The function is invoked (called) when a button is clicked:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
In this example, a JavaScript function is placed in the <body> section of an HTML page.
The function is invoked (called) when a button is clicked:
<!DOCTYPE html>
<html>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>
It is a good idea to place scripts at the bottom of the <body> element. |
Scripts can also be placed in external files.
External scripts are practical when the same code is used in many different web pages.
JavaScript files have the file extension .js.
To use an external script, put the name of the script file in the source (src) attribute of the <script> tag:
<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>
You can place an external script reference in <head> or <body> as you like.
The script will behave as if it was located exactly where you put the reference in the HTML document.
External scripts cannot contain <script> tags. |
JavaScript does not have any print or output functions.
In HTML, JavaScript can only be used to manipulate HTML elements.
To access an HTML element from JavaScript, you can use the document.getElementById(id) method.
Use the id attribute to identify the HTML element, and innerHTML to refer to the element content:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p id="demo">My First Paragraph</p>
<script>
document.getElementById("demo").innerHTML = "Paragraph changed.";
</script>
</body>
</html>
The JavaScript statement above (inside the <script> tags) is executed by the web browser:
document.getElementById("demo") is JavaScript code for finding an HTML element using the id attribute.
innerHTML = "Paragraph changed." is JavaScript code for changing an element's HTML content (innerHTML).
Most of the time, in this tutorial, we will use the output method described above:
Writing output into a <p> element with id="demo".
For testing purposes, you can use JavaScript to write directly to the HTML document:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
document.write(Date());
</script>
</body>
</html>
Use document.write for testing only. |
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.write(Date());
}
</script>
</body>
</html>
If your browser supports debugging, you can use the console.log() method to display JavaScript values.
Activate debugging in your browser with F12, and select "Console" in the debugger menu.
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<script>
a = 5;
b = 6;
c = a + b;
console.log(c);
</script>
</body>
</html>
Debugging is the process of testing, finding, and reducing bugs (errors) in computer programs. |
JavaScript is a scripting language. A scripting language is a lightweight programming language.
The sentences in a programming language are called statements.
The principles, how sentences are constructed in a language, are called language syntax.
In computer science , literals are representing fixed values.
With JavaScript, the most important rules for writing fixed (constant) values in are:
Number literals can be written with or without decimals, and with or without scientific notation (e):
3.14
1001
123e5
String literals can be written with double or single quotes:
"John Doe"
'John Doe'
Expression literals evaluate (compute) to values:
5 + 6
5 * 10
In a programming language (and in algebra), variables are used to store values.
JavaScript uses the var keyword to define variables.
An equal sign is used to assign values to variables (just like algebra).
In this example, length is defined as a variable. Then, length is assigned (given) the value 6:
var length;
length = 6;
A literal is a fixed value. A variable is a name. It can have variable values. |
JavaScript uses arithmetic operators to compute values (just like algebra):
(5 + 6) * 10
JavaScript uses an assignment operator to assign values to variables (just like algebra):
x = 5;
y = 6;
z = (x + y) * 10;
A computer program is a sequences of "executable commands" called statements.
JavaScript statements are separated by semicolon:
x = 5 + 6;
y = x * 10;
When separated by semicolon, multiple statements on one line is allowed:
x = 5 + 6; y = x * 10;
A JavaScript statement often starts with a keyword.
The var keyword tells the browser to create a new variable:
var x = 5 + 6;
var y = x * 10;
Not all JavaScript statements are "executable commands".
Anything after double slashes // is treated as a comment.
Comments are ignored, and will not be executed:
// x = 5 + 6; I will not be executed
In this tutorial, we use colors to highlight reserved words, values, and comments. |
In a programming language, all variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can contain letters, digits, underscores, and dollar signs, but cannot begin with a number.
Reserved words (like JavaScript keywords) cannot be used as identifiers.
JavaScript identifiers are case sensitive.
The variables lastName and lastname, are two different variables.
JavaScript does not interpret Var as the keyword var.
JavaScript uses the Unicode character set.
Unicode covers (almost) all the characters, punctuations, and symbols in the world.
For a closer look, please study our Complete Unicode Reference.
It is common, in JavaScript, to use camelCase names. |
In HTML, JavaScript statements are "command lines" executed by the web browser.
In HTML, JavaScript statements are "commands" to the browser.
The purpose, of the statements, is to tell the browser what to do.
This statement tells the browser to write "Hello Dolly" inside an HTML element identified with id="demo":
document.getElementById("demo").innerHTML = "Hello Dolly.";
JavaScript code (or just JavaScript) is a sequence of JavaScript statements.
Each statement is executed by the browser in the sequence they are written.
This example will manipulate two different HTML elements:
document.getElementById("demo").innerHTML = "Hello Dolly.";
document.getElementById("myDiv").innerHTML = "How are you?";
Semicolon separates JavaScript statements.
Normally you add a semicolon at the end of each executable statement:
a = 5;
b = 6;
c = a + b;
Multiple statements on one line are allowed:
a = 5; b = 6; c = a + b;
You might see examples without semicolons. |
JavaScript statements can be grouped together in blocks.
Blocks start with a left curly bracket, and end with a right curly bracket.
The purpose of a block is to make the sequence of statements execute together.
A good example of statements grouped together in blocks, are in JavaScript functions.
This example will run a function that will manipulate two HTML elements:
function myFunction() {
document.getElementById("demo").innerHTML = "Hello Dolly.";
document.getElementById("myDIV").innerHTML = "How are you?";
}
In this tutorial we use 4 spaces of indentation for code blocks. |
JavaScript statements often start with a statement identifier to identify the JavaScript action to be performed.
Statement identifiers are reserved words and cannot be used as variable names (or any other things).
Here is a list of some of the JavaScript statements (reserved words) you will learn about in this tutorial:
Statement |
Description |
break |
Terminates a switch or a loop |
catch |
Marks the block of statements to be executed when an error occurs in a try block |
continue |
Jumps out of a loop and starts at the top |
debugger |
Stops the execution of JavaScript, and calls (if available) the debugging function |
do ... while |
Executes a block of statements, and repeats the block, while a condition is true |
for |
Marks a block of statements to be executed, as long as a condition is true |
for ... in |
Marks a block of statements to be executed, for each element of an object (or array) |
function |
Declares a function |
if ... else |
Marks a block of statements to be executed, depending on a condition |
return |
Exits a function |
switch |
Marks a block of statements to be executed, depending on different cases |
throw |
Throws (generates) an error |
try |
Implements error handling to a block of statements |
var |
Declares a variable |
while |
Marks a block of statements to be executed, while a condition is true |
JavaScript ignores extra spaces. You can add white space to your script to make it more readable.
The following lines are equivalent:
var person = "Hege";
var person="Hege";
For best readability, programmers often like to avoid lines longer than 80 characters.
If a JavaScript statement does not fit on one line, the best place to break it, is after an operator or a comma.
document.getElementById("demo").innerHTML =
"Hello Dolly.";
You can break up a code line within a text string with a backslash:
document.getElementById("demo").innerHTML = "Hello \
Dolly!";
However, you cannot break up a code line like this:
document.getElementById("demo").innerHTML = \
"Hello Dolly!";
JavaScript comments can be used to explain the code, and make the code more readable.
JavaScript comments can also be used to prevent execution, when testing alternative code.
Single line comments start with //.
Any text between // and the end of a line, will be ignored by JavaScript (will not be executed).
The following example uses a single line comment in front of each line, to explain the code:
// Change heading:
document.getElementById("myH").innerHTML = "My First Page";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";
This example uses a single line comment at the end of each line, to explain the code:
var x = 5; // Declare x, give it the value of 5
var y = x + 2; // Declare y, give it the value of x + 2
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored by JavaScript.
The following example uses a multi-line comment (a comment block) to explain the code:
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
It is most common to use single line comments. |
Using comments to prevent execution of code, can be very suitable for testing.
Adding // in front of a code line changes the code lines from an executable line to a comment.
The next example uses // to prevent execution of one of the code lines.
//document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
The following example uses a comment block to prevent execution of multiple lines:
/*
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
*/
JavaScript variables are "containers" for storing data values
var x = 5;
var y = 6;
var z = x + y;
From the example we can expect: x stores the value 5, y stores the value 6, and z stores the value 11.
x = 5
y = 6
z = x + y
In algebra we use letters (like x) to hold values (like 5).
From the expression z = x + y above, we can calculate the value of z to be 11.
In JavaScript these letters are called variables.
JavaScript variables are containers for storing values. |
As with algebra, JavaScript variables can be used to hold values (x = 5) or expressions (z = x + y).
Variable can have short names (like x and y) or more descriptive names (age, sum, totalVolume).
Variable names can contain letters, digits, underscores, and dollar signs.
Both JavaScript statements and JavaScript variables are case-sensitive. |
In JavaScript, the equal sign (=) is an "assignment" operator, is not an "equal to" operator.
This is different from algebra. The following does not make any sense in algebra:
x = x + 5
In JavaScript, however it makes perfect sense: Assign the value of x + 5 to the variable x.
In reality: Calculate the value of x + 5. Then put the result into the variable x.
The "equal to" operator in JavaScript, is written like == or ===. You will see it soon! |
JavaScript variables can hold many types of data, like text values (person = "John Doe").
In JavaScript texts are called strings or text strings.
JavaScript can handle many types of data, but for now, just think of numbers and strings.
When you assign a string value to a variable, you put double or single quotes around the value.
When you assign a numeric value to a variable, you do not put quotes around the value.
If you put quotes around a numeric value, it will be treated as a text string.
var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';
Creating a variable in JavaScript is called "declaring" a variable.
You declare JavaScript variables with the var keyword:
var carName;
After the declaration, the variable is empty (it has no value).
To assign a value to the variable, use the equal sign:
carName = "Volvo";
You can also assign a value to the variable when you declare it:
var carName = "Volvo";
In the example below, we create a variable called carName and assign the value "Volvo" to it.
Then we "output" the value inside an HTML paragraph with id="demo":
<p id="demo"></p>
<script>
var carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>
It's a good programming practice to declare all variables at the beginning of a script. |
You can declare many variables in one statement.
Start the statement with var and separate the variables by comma:
var lastName = "Doe", age = 30, job = "carpenter";
Your declaration can also span multiple lines:
var lastName = "Doe",
age = 30,
job = "carpenter";
In JavaScript you can always separate statements by semicolon, but then you cannot omit the var keyword.
Wrong:
var lastName = "Doe"; age = 30; job = "carpenter";
Right:
var lastName = "Doe"; var age = 30; var job = "carpenter";
In computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input. Variable declared without a value will have the value undefined.
The variable carName will have the value undefined after the execution of the following statement:
var carName;
If you re-declare a JavaScript variable, it will not lose its value:.
The value of the variable carName will still have the value "Volvo" after the execution of the following two statements:
var carName = "Volvo";
var carName;
As with algebra, you can do arithmetic with JavaScript variables, using operators like = and +:
var y = 5;
var x = y + 2;
You can also add strings, but strings will be concatenated (added end-to-end):
var y = "5";
var x = y + 2;
Note that if you add a number to a string, both will be treated as strings.
You will learn a lot more about arithmetic operators later in this tutorial.
String, Number, Boolean, Array, Object, Null, Undefined.
JavaScript variables can hold many data types: numbers, strings, arrays, objects and more:
var length = 16; // Number assigned by a number literal
var points = x * 10; // Number assigned by an expression literal
var lastName = "Johnson"; // String assigned by a string literal
var cars = ["Saab", "Volvo", "BMW"]; // Array assigned by an array literal
var x = {firstName:"John", lastName:"Doe"}; // Object assigned by an object literal
In programming, data types is an important concept.
To be able to operate on variables, it is important to know something about the type.
Without data types, a computer can not safely solve this:
16 + "Volvo"
Does it make any sense to add "Volvo" to sixteen? Will it produce an error or a result?
"16Volvo"
JavaScript has dynamic types. This means that the same variable can be used as different types:
var x; // Now x is undefined
var x = 5; // Now x is a Number
var x = "John"; // Now x is a String
A string (or a text string) is a series of characters like "John Doe".
String are written with quotes. You can use single or double quotes:
var carName = "Volvo XC60"; // Using double quotes
var carName = 'Volvo XC60'; // Using single quotes
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
var answer = "It's alright"; // Single quote inside double quotes
var answer = "He is called 'Johnny'"; // Single quotes inside double quotes
var answer = 'He is called "Johnny"'; // Double quotes inside single quotes
You will learn a lot more about strings later in this tutorial.
JavaScript has only one type of numbers.
Numbers can be written with, or without decimals:
var x1 = 34.00; // Written with decimals
var x2 = 34; // Written without decimals
Extra large or extra small numbers can be written with scientific (exponential) notation:
var y = 123e5; // 12300000
var z = 123e-5; // 0.00123
You will learn a lot more about numbers in the advanced section of this tutorial.
Booleans can only have two values: true or false.
var x = true;
var y = false;
Booleans are often used in conditional testing.
You will learn a lot more about conditional testing later in this tutorial.
JavaScript arrays are written with square brackets.
Array items are separated by commas.
The following code declares (creates) an array called cars, containing three items (car names):
var cars = ["Saab", "Volvo", "BMW"];
Array indexes are zero-based, which means the first item is [0], second is [1], and so on.
You will learn a lot more about arrays later in this tutorial.
JavaScript objects are written with curly braces.
Object properties are written as name:value pairs, separated by commas.
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
The object (person) in the example above has 4 properties: firstName, lastName, age, and eyeColor.
You will learn a lot more about objects later in this tutorial.
The value of a variable with no value is undefined.
Variables can be emptied by setting the value to null.
var cars; // Value is undefined
var person = null; // Value is null
You can use the JavaScript typeof operator to find the type of a JavaScript variable.
typeof "John" // Returns string
typeof 3.14 // Returns number
typeof false // Returns boolean
typeof [1,2,3,4] // Returns object
typeof {name:'John', age:34} // Returns object
In JavaScript, an array is a special type of object. Therefore typeof [1,2,3,4] returns object. |
When a JavaScript variable is declared with the keyword "new", the variable is created as an object:
var x = new String(); // Declares x as a String object
var y = new Number(); // Declares y as a Number object
var z = new Boolean(); // Declares z as a Boolean object
Avoid String, Number, and Boolean objects. They complicate your code and slow down execution speed. |
A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when "something" invokes it (calls it).
function myFunction(p1, p2) {
return p1 * p2; // the function returns the product of p1 and p2
}
A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {}
functionName(parameter1, parameter2, parameter3) {
code to be executed
}
Function parameters are the names listed in the function definition.
Function arguments are the real values received by the function when it is invoked.
Inside the function, the arguments are used as local variables.
A Function is much the same as a Procedure or a Subroutine, in other programming languages. |
The code inside the function will execute when "something" invokes (calls) the function:
You will learn a lot more about function invocation later in this tutorial.
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement.
Functions often compute a return value. The return value is "returned" back to the "caller":
Calculate the product of two numbers, and return the result:
var x = myFunction(4, 3); // Function is called, return value will end up in x
function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}
The result in x will be:
12