JavaScript Variables
Basics
- You can also declare it and give it a value in separate lines (e.g. var y; and y = 3;)
- Variable names can contain letters (uppercase or lowercase), numbers, $ symbols, and underscores
- Variable names are case sensitive, so "mynum" is not the same as "myNum"
- Variable names cannot match special JavaScript keywords (such as "var", "if", "false", ...)
- Unlike with Java, you don't have to indicate the variable type
Data Types
- Although you don't have to state the variable type, it is implied by the assigned value
- A bigint type (Big Integer) should be used for values 2^53 or greater (positive or negative). Don't forget to add 'n' at the end
- Booleans can also be assigned a boolean equation (e.g. x < 12), not only true or false
- Variable types behave differently in mathematical operations, (2+2=4, but "2" + 2 is "22")
- See also object, null, and symbol types
Changing Data Types (Conversion)
- Changing type is useful for ensuring that the values are treated in the expected way for certain actions (e.g. math)
- For example, a number cannot be added to a bigint, you must first convert the number to a bigint
- If you convert a string of letters into a number or bigint, it will get a value of NaN (not a number)
Adding to Variable Values
- When you add two strings together, it just combines them as one string (e.g "Hi, I'm Bob")
- Remember to use parentheses when adding math in strings, after the calculation it will treat the number like a string
Challenge
Create a variable called name, and a variable called age. Display the following, replacing the values in angle brackets with the variable values: "Joe is <age + 5> years old, which is about five years older than <name>"