HTML and CSS Reference
In-Depth Information
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Undefined vs Null</title>
</head>
<body>
<script src="example10-4.js"></script>
</body>
</html>
7. Save the example10-4.html file.
Now open this file in your browser. You should see the following output:
The foo variable is undefined
The bar variable is null
Because the foo variable was declared but not initialized, it never actually existed. Therefore, it is undefined .
The bar variable, on the other hand, was initialized with the text Hello . However, when you set the bar variable to
be empty using the null keyword, it lost its value but still continued to exist. Therefore, when it is written to the
screen, the browser sees that it exists but has no value for it, and so displays null .
Many developers struggle to grasp the difference between undefined and null . Take a look at Jim's video on
the Treehouse website, where he explains this in a little more detail: http://teamtreehouse.com/library/
websites/javascript-foundations/variables/null-and-undefined .
Functions
Functions (sometimes called methods ) are code structures that you can use to store code that might be needed several
times in your script. Instead of having to write this code out multiple times, you can create a function and then call
that function wherever you want the code to run. This makes your code much more maintainable. In Chapter 13 you
will be creating a function that uses the GeoLocation API to find the Joe's Pizza Co. restaurant that is nearest to the
user.
You can pass inputs to a function using parameters. These are placed within parentheses after the function name.
Take a look at a simple function that will take in a name and write a hello message to the screen.
function sayHello(name) {
document.write(“Hello " + name);
}
Here you have defined a parameter called name . When the function is called, the browser will create a variable
name and initialize it with the content that you pass to the function, as shown here:
sayHello(“Joe");
Search WWH ::




Custom Search