Electric Type

Multimedia

About Us

News

Help

Advanced JavaScript Tutorial
Lesson 1

by Thau!

Page 5 — The Way of Var

To keep JavaScript from mixing up same-name variables, put var in front of your variables as you declare them. A variable inside a function that's declared with var is called a local variable, and it only exists inside that function. In general, you want your variables to be local whenever possible.

Here is the JavaScript with the correct vars in it:

function fahrenToCelsius(faren)

{

	var temp = (faren - 32) * 5 / 9;

	return temp;

}


function convertTemp()


{


	var temp = prompt("what temperature Fahrenheit? ","50");

	var celsius = badFahrenToCelsius(temp);

	alert(temp + " degrees Fahrenheit is " + 

		celsius + " degrees Celsius.");


} 

And here's how it works. Let's say we call convertTemp() and type 50 into the prompt. Because we used var before the prompt, this temp is localized to the convertTemp() function. So ...

(inside convertTemp) temp = 50

As before, we pass temp to the function called fahrenToCelsius(). Inside fahrenToCelsius(), the parameter called faren gets set to 50. Then temp is set with the line:

var temp = (faren - 32) * 5 / 9;
As before, putting that var in front of temp tells JavaScript, "This variable called temp is different than any other variable called temp. This one exists only inside the fahrenToCelsius function." Once JavaScript finishes with fahrenToCelsius(), the special temp variable vanishes. So, just before fahrenToCelsius() returns,
faren = 50

(inside fahrenToCelsius) temp = 10

(inside convertTemp) temp = 50

fahrenToCelsius() then returns its version of the temp variable, which is 10. Once we leave fahrenToCelsius(), its version of the temp variable vanishes.

When fahrenToCelsius() returns, it sets the variable called celsius to 10:

(inside convertTemp) temp = 50

(inside convertTemp) celsius = 10
And thus the alert message says, "50 degrees Fahrenheit is 10 degrees Celsius." Which is exactly what we want.

To review, by using var before a variable, you localize that variable to the one function that houses it. And once that function ends, the variable ceases to exist.

And that's the (loose) end of today's lesson. Now all that's left is your homework assignment.

next page»


Tutorials  

User Blogs  

Teaching Tools  

Authoring  

Design  

Programming help  

Advanced Flash  

Javascript  

Glossary  

PHP Coding  

User Blogs

Screen Shots

Latest Updates

Contact Us

Valid HTML 4.01!
Valid CSS!

Breadcrumb

© ElectricType
Maintained by My-Hosts.com
Site map | Copyright | Disclaimer
Privacy policy | Acceptable Use Policy
Legal information.