Today we’re going to focus on types and operators.
Dynamic typing: JS figures out what type of data a variable holds while it’s running. You don’t tell it what kind of data it is.
Static typing: languages like Java/C# use static typing, where you tell the language what kind of data a variable should be.
Primitive Types: a type of data that represents a single value (not an object)
- undefined – represents a lack of existence (the JS engine sets this for new vars when deciding memory allocation in the creation phase)
- null – also lack of existence, but you can set a variable to this
- boolean – true or false
- number – floating point number (it has decimals)
- string – a sequence of characters using ” or “”
- symbol – used in ES6 (will discuss later)
Operators: a special function that is syntactically written different than normal functions (ex mathematical operators – these are actually function calls).
Operator precedence – which operator function gets called first / higher precedence wins
Associativity – what order operator function gets called first if there are two or more of the same operators / precedence value (left to right or right to left)
Coercion – converting a value from one type to another
var a = 1 + 2 // 3
var a = 1 + ‘2’ //12
In the second example, the JS engine has decided that when you try to add a string and a number together, it will coerce the number to a string and then perform the operation. JS does its best to try to understand what values should be, which can sometimes lead to weird bugs if we don’t understand what’s happening.
Depending on the value, things can be coerced differently and sometimes in weird ways. null, for example is coerced to 0, so when you do null < 1 you get true.
To avoid some of these unexpected errors, you should almost exclusively use the === operator or !==. These operators are strict equality or strict inequality operators. They do not coerce any of the values. You should only use coercion if you have a clear understanding of what’s happening and that’s exactly what you want to happen.
One practical use of coercion is checking if a variable has something in it. Knowing that “”, null, and undefined all return false, we can have some function that tries to get info from the internet and store it in a variable. We can then say if something is there, do function whatever.
Another variation of this can be in frameworks or libraries. Some libraries may have variable names that collide with others. So to check if something exists they can use the || (or) operator. || returns the first value that can be coerced into true. For example if I had var x = 0 || 1, then x would be set to 1. In the case of this library, perhaps library name was adding some additional function to our program. But if we already had libraryName defined, then it would use the default libraryName. If we didn’t, then it would use lib 2.
That’s it for types and operators. Next up is objects and functions.