ITSE 1411 Beginning Web
JS Function Syntax Module 2 Discussion
Discussion
- Creating a JavaScript function
- Calling a JavaScript function
- A function is only executed when called from somewhere else in the page.
- Some functions perform a specific task and then ends. Other functions perform a
specific task and then return a single value. Each type of function call has a
different syntax.
- A function that returns a value does so with a return statement. The syntax for
a return statement is:
return some_value;
Understanding variable scope
- The scope of a variable is the context of when the variable name can be used.
- A global variable is known from the location the variable is declared throughout
the rest of the page. You should declare your global variables at the top of
the JavaScript code in the head of your page.
- A local variable is declared inside a function (including the parameter list)
and is only known by that name within the function in which it is declared.
- It is not recommended to use the same variable name for a global variable as
a local variable, but when it is done, the global variable is not known
within the function, only the local variable is known.
- Technically, the keyword var is not required for global variables but
can be used. The keyword var is required for a local variable. When a var
is not used in a function, then the variable becomes global. It is highly
recommended that you do not create global variables inside a function as this
can cause considerable confusion in the program.
Using built-in JavaScript functions
- Built-in JavaScript functions are called the same way you call a user-defined
function. Built-in functions will be explained as they are needed throughout the course.
- One function used often is isNaN() that stands for is not a number.
When a user enters data into a text box, that data is ALWAYS text. When
you require that the data entered is numeric, you can test the entered
data with the isNaN() function. Then, if the data is all numeric, you
can convert the text into either a float number using the parseFloat()
function, or into an integer using the parseInt() function.