JavaScript is the most popular programming language in the world.
This page contains some examples of what JavaScript can do.
One of many HTML methods is getElementById().
This example uses the method to "find" an HTML element (with id="demo"), and changes the element content (innerHTML) to "Hello JavaScript":
This example changes an HTML image, by changing the src attribute of an <img> tag:
Click the light bulb to turn on/off the light
Changing the style of an HTML element, is a variant of changing an HTML attribute:
JavaScript is often used to validate input:
Please input a number between 1 and 10
![]() |
JavaScript and Java are completely different languages, both in
concept and design. JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in 1997. ECMA-262 is the official name. ECMAScript 6 (released in June 2015) is the latest official version of JavaScript. |
---|
JavaScript can be placed in the <body> and the <head> sections of an HTML page.
In HTML, JavaScript code must be inserted into a script block (between <script> and </script> tags).
![]() |
Older examples may use a type attribute: <script
type="text/javascript">. The type attribute is not required anymore since JavaScript is the default scripting language in HTML. |
---|
A JavaScript function is a block of JavaScript code, that can be executed when "asked" for.
For example, a function can be executed when an event occurs, like when the user clicks a button.
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.
![]() |
Keeping 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:
<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:
![]() |
It is a good idea to place scripts at the bottom of the <body>
element. This can improve page load, because script compilation can slow down the display. |
---|
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 src (source) attribute of the <script> tag:
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 the <script> tag is located.
![]() |
External scripts cannot contain <script> tags. |
---|
Placing JavaScripts in external files has some advantages:
JavaScript does NOT have any built-in print or display functions.
JavaScript can "display" data in different ways:
You can use an alert box to display data:
For testing purposes, it is convenient to use document.write():
Using document.write() after an HTML document is fully loaded, will delete all existing HTML:
![]() |
The document.write() method should be used only for testing. |
---|
To access an HTML element, JavaScript can use the document.getElementById(id) method.
The id attribute defines the HTML element. The innerHTML property defines the HTML content:
![]() |
To "display data" in HTML, (in most cases) you will set the value of an innerHTML property. |
---|
In your browser, you can use the console.log() method to display data.
Activate the browser console with F12, and select "Console" in the menu.
JavaScript syntax is the set of rules, how JavaScript programs are constructed.
A computer program is a list of "instructions" to be "executed" by the computer.
In a programming language, these program instructions are called statements.
JavaScript is a programming language.
JavaScript statements are separated by semicolons.
![]() |
In HTML, JavaScript programs can be executed by the web browser. |
---|
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
The JavaScript syntax defines two types of values: Fixed values and variable values.
Fixed values are called literals. Variable values are called variables.
The most important rules for writing fixed values are:
Numbers are written with or without decimals:
Strings are text, written within double or single quotes:
In a programming language, variables are used to store data values.
JavaScript uses the var keyword to declare variables.
An equal sign is used to assign values to variables.
In this example, x is defined as a variable. Then, x is assigned (given) the value 6:
JavaScript uses an assignment operator ( = ) to assign values to variables:
JavaScript uses arithmetic operators ( + - * / ) to compute values:
An expression is a combination of values, variables, and operators, which computes to a value.
The computation is called an evaluation.
For example, 5 * 10 evaluates to 50:
Expressions can also contain variable values:
The values can be of various types, such as numbers and strings.
For example, "John" + " " + "Doe", evaluates to "John Doe":
JavaScript keywords are used to identify actions to be performed.
Thevar keyword tells the browser to create a new variable:
Not all JavaScript statements are "executed".
Code after double slashes// or between /* and */ is treated as a comment.
Comments are ignored, and will not be executed:
Identifiers are names.
In JavaScript, identifiers are used to name variables (and keywords, and functions, and labels).
The rules for legal names are much the same in most programming languages.
In JavaScript, the first character must be a letter, an underscore (_), or a dollar sign ($).
Subsequent characters may be letters, digits, underscores, or dollar signs.
![]() |
Numbers are not allowed as the first character. This way JavaScript can easily distinguish identifiers from numbers. |
---|
All JavaScript identifiers are case sensitive.
The variables lastName and lastname, are two different variables.
JavaScript does not interpret VAR or Var as the keyword var.
Historically, programmers have used three ways of joining multiple words into one variable name:
Hyphens:
first-name, last-name, master-card, inter-city.
Underscore:
first_name, last_name, master_card, inter_city.
Camel Case:
FirstName, LastName, MasterCard, InterCity.
In programming languages, especially in JavaScript, camel case often starts with a lowercase letter:
firstName, lastName, masterCard, interCity.
![]() |
Hyphens are not allowed in JavaScript. It is reserved for subtractions. |
---|
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.
In HTML, JavaScript statements are "instructions" to be "executed" by the web browser.
This statement tells the browser to write "Hello Dolly." inside an HTML element with id="demo":
Most JavaScript programs contain many JavaScript statements.
The statements are executed, one by one, in the same order as they are written.
In this example, x, y, and z is given values, and finally z is displayed:
![]() |
JavaScript programs (and JavaScript statements) are often called JavaScript code. |
---|
Semicolons separate JavaScript statements.
Add a semicolon at the end of each executable statement:
When separated by semicolons, multiple statements on one line are allowed:
![]() |
On the web, you might see examples without semicolons. Ending statements with semicolon is not required, but highly recommended. |
---|
JavaScript ignores multiple spaces. You can add white space to your script to make it more readable.
The following lines are equivalent:
A good practice is to put spaces around operators ( = + - * / ):
For best readability, programmers often like to avoid code 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:
JavaScript statements can be grouped together in code blocks, inside curly brackets {...}.
The purpose of code blocks is to define statements to be executed together.
One place you will find statements grouped together in blocks, are in JavaScript functions:
![]() |
In this tutorial we use 4 spaces of indentation for code blocks. You will learn more about functions later in this tutorial. |
---|
JavaScript statements often start with a keyword to identify the JavaScript action to be performed.
Here is a list of some of the keywords you will learn about in this tutorial:
Keyword | Description |
---|---|
break | Terminates a switch or a loop |
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 |
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 |
try ... catch | Implements error handling to a block of statements |
var | Declares a variable |
![]() |
JavaScript keywords are reserved words. Reserved words cannot be used as names for variables. |
---|
JavaScript comments can be used to explain JavaScript code, and to make it 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 the line, will be ignored by JavaScript (will not be executed).
This example uses a single line comment before each line, to explain the code:
This example uses a single line comment at the end of each line, to explain the code:
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored by JavaScript.
This example uses a multi-line comment (a comment block) to explain the code:
![]() |
It is most common to use single line comments. Block comments are often used for formal documentation. |
---|
Using comments to prevent execution of code, is suitable for code testing.
Adding // in front of a code line changes the code lines from an executable line to a comment.
This example uses // to prevent execution of one of the code lines:
This example uses a comment block to prevent execution of multiple lines:
JavaScript variables are containers for storing data values.
In this example, x, y, and z, are variables:
From the example above, you can expect:
In this example, price1, price2, and total, are variables:
In programming, just like in algebra, we use variables (like price1) to hold values.
In programming, just like in algebra, we use variables in expressions (total = price1 + price2).
From the example above, you can calculate the total to be 11.
![]() |
JavaScript variables are containers for storing data values. |
---|
All JavaScript variables must beidentified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y), or more descriptive names (age, sum, totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
![]() |
JavaScript identifiers are case-sensitive. |
---|
In JavaScript, the equal sign (=) is an "assignment" operator, not an "equal to" operator.
This is different from algebra. The following does not make sense in algebra:
In JavaScript, however, it makes perfect sense: it assigns the value of x + 5 to x.
(It calculates the value of x + 5 and puts the result into x. The value of x is incremented by 5.)
![]() |
The "equal to" operator is written like == in JavaScript. |
---|
JavaScript variables can hold numbers like 100, and text values like "John Doe".
In programming, text values are called text strings.
JavaScript can handle many types of data, but for now, just think of numbers and strings.
Strings are written inside double or single quotes. Numbers are written without quotes.
If you put quotes around a number, it will be treated as a text string.
Creating a variable in JavaScript is called "declaring" a variable.
You declare a JavaScript variable with the var keyword:
After the declaration, the variable has no value. (Technically it has the value of undefined)
To assign a value to the variable, use the equal sign:
You can also assign a value to the variable when you declare it:
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":
![]() |
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:
A declaration can span multiple lines:
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.
A variable declared without a value will have the value undefined.
The variable carName will have the value undefined after the execution of this statement:
If you re-declare a JavaScript variable, it will not lose its value.
The variable carName will still have the value "Volvo" after the execution of these statements:
As with algebra, you can do arithmetic with JavaScript variables, using operators like = and +:
You can also add strings, but strings will be concatenated (added end-to-end):
Also try this:
![]() |
If you add a number to a string, the number will be treated as string, and concatenated. |
---|