Variables and Typing Christopher M. Harden Contents 1 The basic workflow 2 2 Variables 3 2.1 Declaring a variable........................ 3 2.2 Assigning to a variable...................... 4 2.3 Other types of variables..................... 5 3 Type system 6 3.1 Types............................... 6 3.1.1 Strings........................... 7 3.1.2 Numbers.......................... 8 3.2 Coercion.............................. 9 4 Try it yourself 9 1
1 The basic workflow JavaScript code is written in a script file. The bare minimum required to write a script is a plain text editor. There are a variety of programs you can use to write JavaScript script files, with useful functions such as syntax highlighting and code validation. In your own time you can look at various programs and see what works best for you. In classes, I will always use Notepad, which exists on every Windows installation. Linux users, with easy access to a terminal, should also find a plain text editor as standard on their distro (though each distro may pick a different editor, they all have the same function). Note. Programs such as Microsoft Word will not produce plain text. Such documents will contain hidden markup to represent properties of the document, and a JavaScript interpreter will see that markup and get quickly confused. Since our code will eventually end up on a website, what we will do is create a basic HTML page. When we load the page in a web browser such as Firefox or Chrome, the script will run. To do this, we put listing 1 into a text file called test.html, and then open the file in a web browser with Ctrl-O. Simply replace script.js with whatever your file is called, and place this in the same directory as your script. Listing 1: HTML Boilerplate Code 1 <!DOCTYPE html> 2 <html> 3 <head> 4 <t i t l e>javascript Scratchpad</ t i t l e> 5 <script src="script.js"></ script> 6 </head> 7 <body> 8 </body> 9 </html> Note. Modern web browsers tend to have scratchpads built in if you wish to use them. Firefox users will find one in developer options, aptly called Scratchpad. Chrome/Chromium users will find in the developer console a tab labelled Sources. Right click in the blank area under the Snippits tab to create a new file to type in. Once you have a workflow you prefer, we must test it. script.js can be found in listing 2. 2 An example
1 "use strict" ; Listing 2: Your first JavaScript script 2 3 // This should create a box onscreen 4 a l e r t ( "Hello world!" ) ; JavaScript files contain a list of commands separated by semicolons. If you forget the semicolons, the JavaScript interpreter (the program responsible for running your code) will attempt to put them in for you. It is best that you always put them in yourself, to remove the possibility of the interpreter making a mistake. Line 1 is a special command which activates strict mode. Strict mode is recommended to be used, and should appear at the top of every script. This line is magic, and can only appear in the first line. For now, just place it at the top of scripts you write. Changes will be marked as the class progresses. Line 3 is called a comment. Every on a line after // is ignored by the interpreter. Thus you may use them to describe what is happening in your program for future reference. Well written comments will help you understand code better, particularly if you wrote it many years previously! For wordier comments, you can surround text with /* and */. This can take up multiple lines if you choose, and can contain absolutely anything. Line 4 is the main part. It requests a box be displayed with the text Hello world! in it without quotes. 2 Variables The basic concept of any programming language is data. Almost every script or program will have to store and manipulate data in some form. To do this, we use variables. 2.1 Declaring a variable Before we can use a variable, we must declare that it exists and what it is called. You can name a variable using letters, numbers, or the symbols and $. There are only two restrictions. You cannot start a variable name with a number, and you cannot use any of the words listed below. break catch const debugger case class continue default 3
delete if private try do else enum implements import in protected public return typeof var export instanceof static void extends finally for interface let new super switch this while with function package throw yield Once you have a name for a variable, declare it with the var keyword. For example, to declare a variable called firstprimeministerofuk, we write 1 var firstprimeministerofuk ; Listing 3: Declaring a variable Note. Remember that firstprimeministerofuk, firstprimeministerofuk, and firstprimeministerofuk are all different names. Case matters! Once declared, a variable exists for as long as it is in scope. The true meaning of this statement will not be apparent until later classes. For now, just remember that variables declared with var can be seen by any script on the same web page at any time. Officially, we say that variables declared with var have global scope. 2.2 Assigning to a variable Once we have a variable, we can use it to store data. For example, the first Prime Minister of the United Kingdom is generally considered to be Sir Robert Walpole. To store this information in the variable we declared earlier we write Listing 4: Assigning to a variable 1 firstprimeministerofuk = "Sir Robert Walpole" ; If we know what to assign to a variable the moment we declare it, we can roll these two statements into one line. This is called initialization, and it is 4
recommended to initialize variables whenever possible. Thus we can replace the last two statements with listing 5. Listing 5: Initializing a variable 1 var firstprimeministerofuk = "Sir Robert Walpole" ; Variables can be reassigned whenever you like. With our variable above, while Sir Robert Walpole is considered by historians to be the first Prime Minister, he himself denied such a job even existed. The first mention of a Prime Minister in legal documents is in a treaty signed by Benjamin Disraeli. To change our variable to reflect this, we write Listing 6: Reassigning to a variable 1 firstprimeministerofuk = "Benjamin Disraeli" ; Once a variable has been assigned to, its former contents are gone forever and cannot be recovered. If you assign to a variable you haven t declared yet, the results depend on if you opted into strict mode or not. If you have not, JavaScript will helpfully declare it immediately on your behalf (as a var). If you have then JavaScript will report an error and stop immediately. To avoid mistakes such as accidental misspellings of variable names it is recommended to use strict mode. 2.3 Other types of variables There are two other methods of declaring a variable. Both of these methods have block scope, which will be important to remember for when we meet blocks. The first new keyword is let. It is used in the exact same way as var, and apart from the concept of block scope, is exactly the same. It is recommended to use let whenever possible, and var only when necessary. For example 1 let c a l o r i e s I n C a k e = 5118; Listing 7: Declaring a variable with let The final method of declaring a variable is const. const declares a constant. In the context of a JavaScript script, a constant is a variable that you promise not to reassign. At the time of writing this document, Barack Obama is the current President of the USA. Unlike our Prime Minister example above, there is no question on who is the first President of the USA. Thus we can count all the Presidents and find that Barack is the 44th. No 5
matter what happens in the future, the 44th President will never change. A constant would be best for representing this fact, which we do in listing 8. Listing 8: Declaring a variable with const 1 const PresidentofUSANo44 = "Barack Obama" ; 2 // This next line will generate an error! 3 PresidentofUSANo44 = "John McCain" ; As promised, if you attempt to run listing 8, an error will indeed occur the moment you attempt to reassign this variable. We promised not to do so in our script, and the JavaScript interpreter will enforce that restriction for as long as this variable exists. Note how the constant must be initialized, since we can t assign to it later. Constants do not just represent unchanging facts, but merely variables we promise not to change. For example, if we have the base and height of a triangle in aptly named variables, it is valid to write Listing 9: Constants as a promise not to reassign 1 const areaoftriangle = base height / 2 ; Even though the area changes depending on the base and height, once we know what triangle we are looking at we know what its area is. As long as we do not need to change the base or height of the triangle, we never need to change its area. It is recommended to use constants whenever possible. 3 Type system 3.1 Types Since computers store data as binary numbers, there is a possibility of confusion on what a variable contains. For example, the letter a is stored in a computer using the ASCII encoding. Under ASCII, a is stored as the number 97, which could be confused for the actual number 97. To handle this problem, JavaScript uses the concept of typing. A variable has a type attached to it, so that when you store the letter a you can retrieve it later. This type changes as needed automatically. There are 6 primitive data types. These are called strings, numbers, booleans, undefined, null, and Symbols. Additionally, there is one nonprimitive data type called Object. If you ever need to know what type your variable is, you can use the typeof keyword as in listing 10. The result is a string representing that type. 6
1 var a = "Hello" ; 2 typeof a ; // "string" 3 a = 2 1 ; 4 typeof a ; // "number" 5 a = "Goodbye" ; 6 typeof a ; // "string" Listing 10: Checking the type of a variable 3.1.1 Strings A character represents an individual letter, number, space, punctuation, symbols, and so on. Anything you can consider text is a character. A sequence of these characters is called a string. Strings can be used to represent almost anything, and as such is one of the most common types you will see. To type a string into JavaScript, you must quote them with either or. There is no difference in using either quote, as long as you use the same quote on each end of the string. However, the choice is useful in trying to store strings that themselves contain either a or. If you need to store a string with both of these characters in them, you must escape the quote that needs to be in the string. To do that, prefix the quote with the \ character. If your string needs an actual \ character, you can escape the \ with another \. Note. The \ also allows you to type in specific characters that are otherwise hard to type manually. This is called escape notation. One such example is the newline character, represented by \n. In JavaScript these characters are not used often. However, it is useful to note both in case they are needed and if you accidentally use one. 1 "Hello" ; Listing 11: Example strings 2 "Hello", she greeted. 3 "Hello", David\ s sister greeted. 4 "Hello", David\\\ s sister greeted. The most common operation performed on strings is called concatenation. This glues together two strings to make one larger string, and is performed with the + operator. An example can be seen in listing 12. Listing 12: String concatenation 7
1 const g r e e t i n g = "Hello" ; 2 var t a r g e t = world ; 3 4 a l e r t ( g r e e t i n g + " " + t a r g e t + "!" ) ; 3.1.2 Numbers The number type represents general numbers. More specifically, it represents either a decimal number or a few numerical concepts such as infinity. A number may have an optional + or - denoting its sign, and it may use a period as a decimal separator. This type is for performing calculations with numbers, and not for representing items such as fax numbers or addresses. Note. The use of a comma to separate numbers, such as 1, 234 is not supported. Additionally, a period is the only decimal separator, so one-half is written as 0.5 and not 0, 5. Regardless of your native language, JavaScript is written as if you was an American English speaker. Just like with regular numbers, you can add, subtract, multiply, and divide with +, -, *, and / respectively. These operators match the standard arithmetic rules, namely that * and / are prioritised over + and -, and that these operators are associative when appropriate. New in the current standard is the exponentiation operator, represented by **. Exponentiation also follows standard exponentiation rules, such as 2 3 4 being approximately equal to 2.41 10 24, and not 4096. If you are targeting web browsers that do not support this, there is an alternative using Math.pow. Note that a b is equivalent to Math.pow(a, b). The dot in Math.pow has special meaning we will discuss later, and is not a part of the name. If you need to deviate from the standard rules, or if you wish to make a complicated expression easier to look at, you may use ( and ) to group parts of an expression together. As in regular mathematics, brackets are top priority and will be evaluated first. An example of everything discussed can be seen in listing 13. Listing 13: Working with numbers 1 const pi = 3. 1 4 1 5 9 ; 2 var r a d i u s = (3 + 9 2) / 2 ; 3 4 const area = pi r 2; 5 // This is the Math.pow equivalent 8
6 const area = pi Math. pow( r, 2) ; 7 8 a l e r t ( "The circle of radius " + r a d i u s + " has area " + area ) ; 3.2 Coercion The + operator can be used to concatenate two strings and add two numbers. As long as the types match the JavaScript interpreter can work out what to do. However, if the types don t match then the interpreter cannot proceed. To fix this problem, JavaScript employs a technique called type coercion. For the + operator, if a number and a string is found then the number is turned into a string first. This is how the alert in listing 13 worked. To avoid having to remember type coercion rules for every operator, you can do the conversion yourself. Listing 14: Converting between types 1 var iamastring = S t r i n g (12) ; 2 var iamanumber = Number( "12" ) ; 3 4 typeof iamastring ; // "string" 5 typeof iamanumber ; // "number" This is also useful to know for dealing with functions (a topic to be discussed later). For example, prompt("what is your age?") will create a popup box containing a text field. The user can type an answer to your question in that box, and the function will return it. However, any answer given will always be returned as a string. Attempting to add to this number will cause concatenation to occur. This problem can be solved by converting the string into a number before using it. 4 Try it yourself To check this week s knowledge, try the following tasks below. Each task should take no more than a few minutes, and does not require information from a future class. 1. Try saving and running the code in listings 1 and 2. 9
2. Create appropriately named variables that stores the name, email address, phone number, and number of years of operation for a fictitious company. Explain, using comments, what type each variable is, and why it is appropriate for that variable. 3. The command alert ("text") will display text to the user in an alert box. The command prompt("question") will display a question to the user, and this answer can be saved to a variable using 1 var answer = prompt ( " question" ) ; Assuming the user does not cancel, it will be a string containing the answer. Using these commands: (a) Get the name of the user, and display Hello name, where name is the name you was given by the user. (b) Get two numbers from the user, and display their sum. 10