Tutorial Ref.com

Javascript Call Variable: Example of Variable Called from an External Function

This is a short tutorial on how to call a variable from a Javascript function. I created a Javascript function like so:

1
2
3
4
function myArray(a) {
    var a=5;
    return a;
}

I placed this Javascript function in an external file from the html file as follows:

1
2
3
4
5
6
7
8
<html>
<head>
    <script type="text/javascript" src="test_var.js"></script>
</head>
<body>
    <script type="text/javascript">alert(myArray())</script>
</body>
</html>

This is pretty straight forward and nothing complicated. You no longer the need the type parameter for the script html tag. It's the default for modern browsers (Firefox 3.x or greater, IE 7.x or greater, Safari OSX). If you omit the type parameter the code will even validate according to W3C Markuup Validation Service.

However, if you wish to fully validate to the W3C Makrup Validation Service with XHTML 1.0 Strict then you need to use the following code at the bare minimum:

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>Javascript Call Variable</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script src="test_var.js"></script>
</head>
<body>
    <script type="text/javascript">alert(myArray())</script>
</body>
</html>

If you're interested you can learn more about W3.org's strictly conforming documents. The page will explain the DOCTYPE html tag and the requirements of the xmlns (XML namespace) reference. But I digress. The Javascript function called simply returns a variable that is assigned the number 5. So if you wish to call a Javascript variable from a function then simply use 'return' and then the variable name.

There are other ways of calling a Javascript variable from a function using the object constructor. It's similar to the way of calling a php variable from a function but instead of using "->" calling a Javascript variable using the object constructor uses a dot ".". I'll explain this in another tutorial though.

TutorialRef.com - tutorials, guides, how-tos, helps