JavaScript lets you do this, but you don't have to. You may find it easier to understand code if variables usually keep the same type. Whether or not you use this dynamic typing feature is up to your preferred coding style.
It's also worth mentioning other programming languages have different types for numbers, such as representing integers and floating point (fractional) numbers with separate data types. JavaScript doesn't do this though, and there's only one number type, which as mentioned is a floating point number type.
typeof
JavaScript also provides the typeof
operator, which can tell you what type something is. It returns a string.
// Try entering in to the console:
typeof 100 // number
typeof "Hello" // string
typeof true // boolean
This can help you identify what type something is if you're not sure, e.g.:
let myVar = "Hello"; // start off with string
myVar = 100; // change to number
// ... lots more code ...
// What type is myVar?
console.log(typeof myVar); // number
The special type undefined
has also come up previously, and it has its own type of "undefined"
as well.
// Try entering in to the console:
typeof undefined // "undefined"
This will also be the type of a variable that never had anything assigned.
let unassignedVariable;
console.log(typeof unnasignedVariable); // undefined
Conclusion
In this part we've covered;
- Statements
- Comments
- Variables, assignment and constants
- Numbers, strings and boolean data types
- Dynamic typing
- The
typeof
operator
Hopefully by now you're getting familiar with entering code in both Construct and the browser console. The guide will continue to use both. In the next part, we'll learn more about operators, booleans, comparisons, and converting types.
Learn more
At the end of each part of this guide we'll include links to learn more about the JavaScript features mentioned on the MDN Web Docs, which is one of the best references for web development. You can skip over this and just carry on with the guide if you want, but if you're comfortable with what you've learned and want to dig deeper with a more complete reference or dig in to more advanced details, you can use these links to learn more.
Part 3
When you're ready to continue, head to the next part at Learning JavaScript in Construct, part 3: operators!