Creating and Using Functions and Variables in JavaScript - HTML5 APPLICATIONS DEVELOPMENT MANUAL (2016)

HTML5 APPLICATIONS DEVELOPMENT MANUAL (2016)

20 - Creating and Using Functions and Variables in JavaScript

A function is a group of statements that are combined to perform a specific task.

A statement is a line of code that performs an action. Statements should end with a semicolon (;).

If different parts of a script repeat the same task, then you can reuse a function instead of repeating the same statements.

A JavaScript function is executed when "something" invokes it (calls it).

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: {}

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 (the parameters) behave as local variables.

<!DOCTYPE html>

<html>

<head>

<title></title>

<script type="text/javascript">

function HelloWorld() {

alert("Hello World!");

}

</script>

</head>

<body>

<a href="javascript:HelloWorld()">Hello</a>

</body>

</html>

Definition and Execution of Functions

The way that a function is defined is different from how it is executed by a browser.

A function’s definition outlines its name, any parameters it may take, and its statements.

NOTE: a definition doesn’t perform any of a function’s statements.

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)

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

<!DOCTYPE html>

<html>

<head>

<title></title>

</head>

<body>

<h2>JavaScript Functions</h2>

<p>This example calls a function which performs a calculation and returns the result:</p>

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

<script>

function myFunction(a, b) {

return a * b;

}

document.getElementById("demo").innerHTML = myFunction(4, 3);

</script>

</body>

</html>

Variables

Scripts should temporarily store pieces of information. These bits of data can be stored as variables.

It’s called a variable because its values can vary every time a program is run. Variables can be defined using the var syntax with a unique keyword, such as height or width.

<!DOCTYPE html>

<html>

<head>

<title></title>

</head>

<body>

<h2>JavaScript Variables</h2>

<p>In this example, x, y, and z are variables</p>

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

<script>

var x = 5;

var y = 6;

var z = x + y;

document.getElementById("demo").innerHTML = z;

</script>

</body>

</html>

All JavaScript variables must be identified 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:

- Names can contain letters, digits, underscores, and dollar signs.

- Names must begin with a letter

- Names can also begin with $ and _ (but we will not use it in this tutorial)

- Names are case sensitive (y and Y are different variables)

- Reserved words (like JavaScript keywords) cannot be used as names

- JavaScript identifiers are case-sensitive.

Types of Data

- Numbersà 1, 2, 3

var length = 16;

- Stringsà ‘Zombies freak me out!’

· Must always be surrounded by quote marks

var lastName = "Johnson";

- Booleanà true, false

var x = true; var y = false;

- Objects

var x = { firstName:"John", lastName:"Doe" };

- Arrays

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

Comments

Add comments to your script to explain what it does. It will also make your code easier for others to read and understand.

Add a single-line comment by placing two forward slash characters // in front of your comment. Anything after the slashes won’t be interpreted by the browser.

Add a multi-line comment by starting with the /* characters and ending with the */ characters. Anything between these characters won’t be interpreted by the browser.

/*These comments are typically reserved for describing how an entire script file works or to comment out an entire block of script. */

//this function does something awesome!

function doSomethingAwesome() {

var name = prompt(“What is your name?”);

alert(name + “, you just did something awesome!");