JavaScript Introduction

 

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.

 

JavaScript Can Change HTML Elements

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":  

Example

document.getElementById("demo").innerHTML = "Hello JavaScript";


Try it Yourself » 

The method document.getElementById() is one of many methods in the HTML DOM.

You can use JavaScript to:

  • Change HTML elements
  • Delete HTML elements
  • Create new HTML elements
  • Copy and clone HTML elements
  • And much more ...

There are several chapters, about the HTML DOM, later in this tutorial.

 

JavaScript Can Change HTML Attributes

This example changes the value of the source attribute (src) of an HTML <img> element:

The Light bulb

 

Click the light bulb to turn on/off the light


Try it Yourself » 

With JavaScript, you can change almost any HTML attribute. 

 

JavaScript Can Change HTML Styles (CSS)

Changing the style of an HTML element, is a variant of changing an HTML attribute. 

Example

document.getElementById("demo").style.fontSize = "25px";


Try it Yourself » 

With JavaScript, you can change almost any CSS value. 

 

JavaScript Can Validate Data

JavaScript is often used to validate input:

Please input a number between 1 and 10

 


Try it Yourself » 

 

 

Did You Know?

 

JavaScript and Java are different languages, both in concept and design.

JavaScript was invented by Brendan Eich, to be used in Netscape (a no longer existing browser) in 1995,
and was adopted by the ECMA standard association in 1997.

ECMA-262 is the official name. ECMAScript 5 (version 1.8.5 - July 2010) is the latest standard. 

 

 

JavaScript Where To

« Previous

Next Chapter »

 

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.

 

The <script> Tag

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:

Example

<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.
JavaScript is the default scripting language in all modern browsers, and in HTML5. 

 

 

JavaScript Functions and Events

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.

 

JavaScript in <head> or <body>

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.

 

JavaScript in <head>

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:

Example

<!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> 


Try it Yourself » 

 

 

JavaScript in <body>

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:

Example

<!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> 


Try it Yourself » 

 

It is a good idea to place scripts at the bottom of the <body> element.
This improves page load, because HTML loading is not blocked by scripts loading.

 

External JavaScripts

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:

Example

<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>


Try it Yourself » 

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 Output

« Previous

Next Chapter »

 

JavaScript does not have any print or output functions. 

In HTML, JavaScript can only be used to manipulate HTML elements.

 

Manipulating 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:

Example

<!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> 


Try it Yourself » 

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).

 

In This Tutorial

Most of the time, in this tutorial, we will use the output method described above:

Writing output into a <p> element with id="demo".

 

Writing to The HTML Document

For testing purposes, you can use JavaScript to write directly to the HTML document:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>

<p>My first paragraph.</p>

<script>
document.write(Date());
</script>

</body>
</html> 


Try it Yourself » 

 

Use document.write for testing only.
If you execute it, on a loaded HTML document, all HTML elements will be overwritten.

Example

<!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> 


Try it Yourself » 

 

 

Writing to The Console

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.

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>

<script>
a = 5;
b = 6;
c = a + b;
console.log(c);
</script>

</body>
</html> 


Try it Yourself » 

 

 

Did You Know?

 

Debugging is the process of testing, finding, and reducing bugs (errors) in computer programs.
The first known computer bug was a real bug (an insect), stuck in the electronics.

 

 

JavaScript Syntax

« Previous

Next Chapter »

 

JavaScript Syntax

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.

 

JavaScript Literals (Fixed Values)

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 


Try it Yourself » 

String literals can be written with double or single quotes:

"John Doe"

'John Doe' 


Try it Yourself » 

Expression literals evaluate (compute) to values:

5 + 6

5 * 10 


Try it Yourself » 

 

 

JavaScript Variables

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; 


Try it Yourself » 

 

A literal is a fixed value. A variable is a name. It can have variable values. 

 

JavaScript Operators

JavaScript uses arithmetic operators to compute values (just like algebra): 

(5 + 6) * 10


Try it Yourself » 

JavaScript uses an assignment operator to assign values to variables (just like algebra): 

x = 5;
y = 6;
z = (x + y) * 10;


Try it Yourself » 

 

 

JavaScript Statements

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;

 

 

JavaScript Keywords

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; 

 

 

JavaScript Comments

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.

 

JavaScript Identifiers

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 is Case Sensitive

JavaScript identifiers are case sensitive.  

The variables lastName and lastname, are two different variables.

JavaScript does not interpret Var as the keyword var.

 

JavaScript Character Set

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.

 

Did You Know?

 

It is common, in JavaScript, to use camelCase names.
You will often see identifier names written like lastName (instead of lastname).

 

 

 

JavaScript Statements

« Previous

Next Chapter »

 

In HTML, JavaScript statements are "command lines" executed by the web browser.

 

JavaScript Statements

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":

Example

document.getElementById("demo").innerHTML = "Hello Dolly.";


Try it Yourself » 

 

 

JavaScript Code

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:

Example

document.getElementById("demo").innerHTML = "Hello Dolly.";
document.getElementById("myDiv").innerHTML = "How are you?"; 


Try it Yourself » 

 

 

Semicolon ;

Semicolon separates JavaScript statements.

Normally you add a semicolon at the end of each executable statement: 

a = 5;
b = 6;
c = a + b;


Try it Yourself » 

Multiple statements on one line are allowed:

a = 5; b = 6; c = a + b; 


Try it Yourself » 

 

 

You might see examples without semicolons. 
Ending statements with semicolon is optional in JavaScript.

 

 

JavaScript Code Blocks

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:

Example

function myFunction() {
    document.getElementById("demo").innerHTML = "Hello Dolly.";
    document.getElementById("myDIV").innerHTML = "How are you?";
}


Try it Yourself » 

 

In this tutorial we use 4 spaces of indentation for code blocks.
You will learn much more about functions later in this tutorial. 

 

JavaScript Statement Identifiers

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 White Space

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"; 

 

 

JavaScript Line Length and Line Breaks

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.

Example

document.getElementById("demo").innerHTML =
    "Hello Dolly.";


Try it Yourself » 

 

 

JavaScript Line Break in a String

You can break up a code line within a text string with a backslash:

Example

document.getElementById("demo").innerHTML = "Hello \
    Dolly!"; 


Try it Yourself » 

However, you cannot break up a code line like this:

Example

document.getElementById("demo").innerHTML = \ 
    "Hello Dolly!"; 

 

 

 

JavaScript Comments

« Previous

Next Chapter »

 

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

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:

Example

// Change heading:
document.getElementById("myH").innerHTML = "My First Page";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph."; 


Try it Yourself » 

This example uses a single line comment at the end of each line, to explain the code:

Example

var x = 5;      // Declare x, give it the value of 5
var y = x + 2;  // Declare y, give it the value of x + 2 


Try it Yourself » 

 

 

Multi-line Comments

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:

Example

/*
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."; 


Try it Yourself » 

 

It is most common to use single line comments.
Block comments are often used for formal documentation.

 

Using Comments to Prevent Execution

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.

Example

//document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph."; 


Try it Yourself » 

The following example uses a comment block to prevent execution of multiple lines:

Example

/*
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
*/ 

 

 

 

JavaScript Variables

« Previous

Next Chapter »

 

JavaScript variables are "containers" for storing data values

 

JavaScript Variables Stores Data

Example

var x = 5;
var y = 6;
var z = x + y;


Try it Yourself » 

From the example we can expect: x stores the value 5, y stores the value 6, and z stores the value 11.

 

Much Like Algebra

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. 

 

 

JavaScript Variables

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.

  • Variable names must begin with a letter
  • Variable names can also begin with $ and _ (but we will not use it)
  • Variable names are case sensitive (y and Y are different variables)
  • Reserved words (like JavaScript keywords) cannot be used as variable names
 

Both JavaScript statements and JavaScript variables are case-sensitive. 

 

 

The Assignment Operator

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 Data Types

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.

Example

var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';


Try it Yourself » 

 

 

Declaring (Creating) JavaScript Variables

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":

Example

<p id="demo"></p>

<script>
var carName = "Volvo";
document.getElementById("demo").innerHTML = carName; 
</script>


Try it Yourself » 

 

 

It's a good programming practice to declare all variables at the beginning of a script. 

 

 

One Statement, Many Variables

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"; 

 

 

Value = undefined

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;

 

 

Re-Declaring JavaScript Variables

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;

 

 

JavaScript Arithmetic

As with algebra, you can do arithmetic with JavaScript variables, using operators like = and +: 

Example

var y = 5;
var x = y + 2; 


Try it Yourself » 

You can also add strings, but strings will be concatenated (added end-to-end):

Example

var y = "5";
var x = y + 2; 


Try it Yourself » 

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.

 

 

JavaScript Data Types

« Previous

Next Chapter »

 

String, Number, Boolean, Array, Object, Null, Undefined.

 

JavaScript Data Types

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 

 

 

The Concept of Data Types

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

JavaScript has dynamic types. This means that the same variable can be used as different types:

Example

var x;               // Now x is undefined
var x = 5;           // Now x is a Number
var x = "John";      // Now x is a String

 

 

JavaScript Strings

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:

Example

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:

Example

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 


Try it yourself »

You will learn a lot more about strings later in this tutorial.

 

JavaScript Numbers

JavaScript has only one type of numbers.

Numbers can be written with, or without decimals:

Example

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:

Example

var y = 123e5;       // 12300000
var z = 123e-5;      // 0.00123


Try it yourself »

You will learn a lot more about numbers in the advanced section of this tutorial.

 

JavaScript Booleans

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

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):

Example

var cars = ["Saab", "Volvo", "BMW"]; 


Try it Yourself » 

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

JavaScript objects are written with curly braces.

Object properties are written as name:value pairs, separated by commas.

Example

var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};


Try it Yourself » 

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.

 

Undefined and Null

The value of a variable with no value is undefined.

Variables can be emptied by setting the value to null.

Example

var cars;              // Value is undefined
var person = null;     // Value is null


Try it Yourself » 

 

 

The typeof Operator

You can use the JavaScript typeof operator to find the type of a JavaScript variable.

Example

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 


Try it yourself » 

 

 In JavaScript, an array is a special type of object. Therefore typeof [1,2,3,4] returns object.  

 

Do Not Declare String, Number, and Boolean as Objects!

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. 

 

 

 

JavaScript Functions

« Previous

Next Chapter »

 

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).

 

Example

function myFunction(p1, p2) {
    return p1 * p2;              // the function returns the product of p1 and p2
}


Try it Yourself » 

 

 

JavaScript Function Syntax

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.

 

 

Function Invocation

The code inside the function will execute when "something" invokes (calls) the function:

  • When an event occurs (when a user clicks a button)
  • When it is invoked (called) from JavaScript code
  • Automatically (self invoked)

You will learn a lot more about function invocation later in this tutorial.

 

Function Return

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":

Example

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