Numbers Strings And Booleans
Goals
- Use the browser's console
- Understand the primitive types of numbers, strings and booleans
Overview
Using the Browser's Console
We'll experiment with javascript using the console of our browser. We recommend everyone use Chrome, for consistency through the class.
To open the console on a Mac, use the shortcut
Command+Option+J. To open the console in Windows or Linux, use the keyboard shortcutControl+Shift+J. Alternatively, right click, select 'Inspect Element' from the right-click menu, and click the 'Console' tab.The console is where we can experiment with javascript, by typing after the
>prompt. The console will also show us the return value of an expression we type and will display any errors we get.Numbers
Steps
Step 1
In the console, type
5and press enter. Notice that it will display the value5in response. Thus, our return value for the expression5is5.Step 2
Try
typeof(5)and note what kind of object5is.Step 3
Try creating decimal numbers.
Step 4
Try creating irrational numbers (a number that can only be fully expressed as the ratio of two numbers, like 2/3). Notice that it will convert it to a decimal.
Step 5
Try adding or subtracting numbers in the console by typing
6 + 12or15 - 32.Step 6
Try an edge case with numbers, like
12 / 0.Step 7
To assign a number to a variable, type
favoriteNumber = 5into the console prompt. Then use favoriteNumber in the next expression, likefavoriteNumber + 7. Variables in Javascript are traditionally 'camel-cased' with capital letters separating words in a variable name.Step 8
More complex math, like exponents, will require us to use the Math object, as in
Math.pow(12, 2), but that shouldn't stop us from trying it out!Step 9
Bonus Points: Check out Mozilla Developer Network Docs for the Math object, and try using some of the other methods they describe in your console!
Strings
Strings are units of text, and we encapsulate them in
'single quotes'or"double quotes".Steps
Step 10
Try creating a string by typing
'this is a string'into the console prompt.Step 11
You can grab a string's individual characters with
'this is a string'[6], where the number 6 is the index of the character you want, starting at 0.Step 12
Concatenate strings with
'my name is' + 'Michelle' + '.'.Step 13
Assign a string to a variable by writing
myName = 'Michelle'.Step 14
Use the variable as you would a literal string:
'Is your name ' + myName + '?'Step 15
If you're ahead of others, check out the MDN docs on strings.
Booleans (True/False)
Booleans are a type of object used to indicate true or false values in Javascript. They are most often used to help check whether a condition is true or not, or whether something exists.