For this course, you will need a modern web browser, such as Google Chrome or equivalent with developer tools. You will also need a capable text editor. I highly recommend Microsoft Visual Studio Code. The first concept we are going to cover in this lesson is variables. Variables are spaces of memory where you can store information of a certain type, that can be retrieved later in your code.
- Number (including whole, integer, float)
- String (or text)
- Undefined (a variable that has not yet been assigned a value or type)
- Null (an assignment representing no value)
The keyword let is used to declare a variable. A variable can either be declared as undefined (without a value set) or defined with a value. The following examples illustrate declaring variables of different types.
Variable names have certain rules that we need to follow. All variable names must start with an underscore _ or letter. The rest of the name can contain any letter, any number, or the underscore. You can’t use any other characters. Variables are case-sensitive.
Now that you have learned the basics of variables, let’s try using some next.
→ Try it out in the Browser Console
In Chrome (or an equivalent browser), open the development tools. Using Chrome you can access ‘developer’ tools in the view menu (Mac) or tools menu (Windows). Alternatively, right-clicking an empty area in the browser window and selecting ‘inspect’ will also get you there. You can also open the console by pressing Ctrl+Shift+J (Windows / Linux) or Cmd+Opt+J (Mac).
Next try declaring the studentName variable as above. Once you hit enter on the keyboard, enter the command:
You should now see the relevant output showing the value of studentName as shown in the screenshot below.
The console.log command is a very handy way of quickly outputting results to the console. As shown above, we have successfully declared the studentName variable and assigned the value ‘Fred Jones’. Strings are always stored using either single or double quotes. The console.log command confirms our value is stored to the variable.
→ Try it out in Code Files
Open index.html in your browser and open the console, Press Ctrl+Shift+J (Windows / Linux) or Cmd+Opt+J (Mac).
Note each of the different variables display their associated value in the console.
Coercion and Mutation
Other languages, such as Java and C# enforce strict typing, meaning the variable itself (in this case student) would be assigned a type of string. If I later tried to store the boolean true value, I would receive a compilation error.
In your script.js file, update the code, adding the new lines on the end starting with the comments ‘Coercion and Mutation’:
Image Credits: Photo by Clément H on Unsplash.