Presentation is loading. Please wait.

Presentation is loading. Please wait.

JavaScript Variables.

Similar presentations


Presentation on theme: "JavaScript Variables."— Presentation transcript:

1 JavaScript Variables

2 Learning Objectives By the end of this lecture, you should be able to:
Declare a variable, giving it a clear, useful identifier Apply a basic mathematical formula and assign the value to a variable Become more comfortable with the use of Strings FROM MEMORY: Be able to to create a simple conversion page such as a conversion between fahrenheit and celcius.

3 Stop! Whatever you do, do NOT casually watch this lecture, knock off the quiz and mentally check the topic off your list! This, and subsequent JavaScript topics will involve many seemingly minor issues that can trip you up. In addition, various small details that may appear insignificant right now, will turn out to be very important. In other words, this is a KEY point in the course where you must make frequent stops in order to practice coding the concepts as they are being discussed. It is certainly a good idea to first watch the lecture all the way through. However, then be sure to go back and re-watch it again, making sure to practice each step along the way. Only move on to the next lecture once you can carry out all of these steps on your own with few (preferably zero) peeks at the notes.

4 Using “variables” to store information
What is a variable? Often (very often) in programming, we need to temporarily store information. For example, suppose you want to retrieve the user’s name and address from a web form so that you can enter it into a database. Where will you store this information in the short term? You can store this information inside something called a ‘variable’. A variable is a tiny space in your computer’s memory that you reserve in order to store a piece of information. How to we create a variable? In order to create a variable we simply “declare” it. Here is an example of declaring a variable called ‘userName’: var userName; That’s it!! You can now store any information in this variable that you want. Example: var userName;  Declaring the variable userName = "Robert Smith"; Assigning a value to the variable

5 Variables contd You can create as many variables as you want in a script. A variable should only be declared one time in a script. In other words, once you’ve declared a variable, you do not declare it again. Here is an example of a simple script that declares two variables, one to store a quantity in U.S. Dollars, and second to store a value in Mexican Pesos. We then do a mathematical conversion and output the result in an alert box. Note the naming convention we use for our identifiers. We use the same camel-case naming that we used when naming functions. Examine the following code. The full script is on the next slide. var usDollars; var mexicanPesos; usDollars = 50; mexicanPesos = usDollars * 12.87; alert(mexicanPesos);

6 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Practice Makes Perfect</title> <script type="text/javascript"> function dollarsToPesos() { var usDollars; var mexicanPesos; usDollars = 50; mexicanPesos = usDollars * 12.87; alert(mexicanPesos); } </script> </head> <body> <h1>It Takes Practice...</h1> <hr> <input type="button" value="Convert Dollars to Pesos" id="btnSubmit" onclick="dollarsToPesos()" > </body> </html>

7 What is the best way to practice?
Do not copy and paste any new code. Unless you are fully comfortable and familiar with the code, you should always type it out yourself. Experiment with the code examples. Start by typing out the exact example. Then write a page that does something similar. For example, in our conversion code, write a page that does a similar calculation. Try looking up the conversion between a different currency (e.g. Euros), and write a program that outputs an example of that conversion. Then look up the conversion between pounds and kilograms and create a page that does that conversion.

8 Some Notes usDollars=50;
Naming convention: Note that we use the same naming convention for our variable identifiers as we’ve used for our function identifiers, i.e. camel-case. Declaring variables: We typically declare one variable per line. However, if you have related variables, we often will group them together on the same line with commas in between: var firstName, middleName, lastName; Assigning values to our variables: Notice how we assigned a value to our variable: usDollars=50; At the moment, the only we can assign a value inside our variable is by putting it there ourselves. For example, in the example above, we manually typed in the value of '50' to the variable usDollars. However, we will soon learn how to retrieve values from our HTML forms. At this point, our code becomes much more powerful. When we reach that point, we will allow the user to enter the value via the form. For example, we will create a form that asks the user to enter an amount in US Dollars. Our script will then retrieve that value from the form, and assign it to the variable usDollars.

9 Variables can store just about anything
Variables will be used in nearly every bit of code that you will ever write! Variables are used to store values such as Strings and Numbers Some examples: var temperatureCelcius, temperatureFarenheit; var userName, userAddress; temperatureCelcius = 33; temperatureFarenheit = (9.0 / 5 * temperatureCelcius)+32; userName = "John Doe"; userAddress = "222 Memory Lane";

10 STRINGS A combination of letters / words / symbols, etc is called a “String”. Strings are always placed in quotes. Some examples of Strings: "Robert Smith Johnson"  a simple string "12345"  (a string of digits – NOT a number!!)  a string of random characters ""  (an empty string) var userName, , favoriteBand; userName = " John Doe "; telephoneNumber = " "; favoriteBand = " Spinal Tap";

11 Doing Math with JavaScript
var temperatureCelcius, temperatureFahrenheit; var miles, kilometers; temperatureCelcius = 33; temperatureFahrenheit = (9.0/5* temperatureCelcius )+32; // the decimal after the 9 is needed //will explain more in a later lecture alert(temperatureFahrenheit) miles = 72; kilometers = miles * 1.6; alert(kilometers);

12 Practice Time Practice using the Dollars to Pesos example that was mentioned earlier. Once that’s done, continue to experiment. For example, modify your program to convert from U.S. Dollars into, say, Thai Baht. My version of the complete temperature conversion web page discussed previously is on the next slide. First make sure you do it on your own, though! Then compare with my version. Do NOT move forward until you are fairly comfortable with this process!

13 File: temperature_conversion.htm
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Practice Makes Perfect</title> <script type="text/javascript"> function celciusToFahrenheit() { var fahrTemperature; var celciusTemperature; celciusTemp = 40; fahrTemp = 9.0/5*celciusTemp +32; alert(fahrTemp); } </script> </head> <body> <h1>It Takes Practice...</h1> <hr> <input type="button" value="Convert Temperatures" id="btnSubmit" onclick="celciusToFahrenheit()" > </body> </html>

14 Reivew: Creating Variables – “Declaring”
You must always DECLARE a variable before you can use it by using the ‘var’ command. JS will work if you forget to declare your variables, however, many languages absolutely require that you declare your variables. Because I want you to use best practices at all times, this course requires that you always declare your variables. You only declare a variable once in a function. Once a variable has been declared, you can use it as many times as you want. You must not re-declare a variable within the same function.

15 A common shortcut We can declare a variable and assign it a value in the same line: var age = 34; This is a very commonly used syntax, so you should be familiar with it.

16 Naming your variable: When choosing your identifier, keep the following in mind: A variable name must be a sequence of letters digits A variable can NOT: Begin with a digit Have a space Have mathematical operators such as: +, -, /, *, %, etc Be a ‘reserved’ word (discussed on the next slide) Have various other characters such as & : ^ # Don't forget: JavaScript is case sensitive so “firstName” and “FirstName” are different variables.

17 Reserved Words Here is a list of words that can not be used as an identifier (variable name, function name, etc). We call these 'reserved keywords'. Most of these are words that ‘mean something' in JS – e.g. ‘function’ or ‘var’. You do not need to memorize this list. It's just something you should keep in the back of your mind when you are choosing an identifier.

18 Quick Review Which of the following are legal variable names?
Why/Why Not? fav_movie Legal You&I Illegal: contains & Also violates naming convention by beginning with a capital letter first Name Illegal: has a space 3rdNumber Illegal: begins with a digit userBirthCity Legal x Legal (but not very clear!)

19


Download ppt "JavaScript Variables."

Similar presentations


Ads by Google