When you create a variable, you create a container. And, by default, the container is empty or undefined. We can now assign something to it. A value, an object, or something else. That's done with the equals symbol. There's a formula to this. First, create the variable by typing in its name. Then assign something to it using the equals symbol and the value. Let's do that simple math example again, only this time, we'll use our variables. First, I define three variables: a, b, and sum.
Next, we assign four to a and five to b. And to get sum, I assign a and b to the sum variable by quite literally putting them into the sum variable. In code, it looks like this. Var a; var b; var sum; a equals four; b equals five; sum equals a plus b.
The sum variable is populated by the contents of a and b, so we define it first, then put the other variables into it. In code, this can often feel a bit backward, but when you see what's going on in real life, it makes a lot of sense. Creating variables, and then calling them in to set their values in a separate statement is a bit clunky, so there's a shorthand we can use instead. Var a equals five; var b equals four; var sum equals a plus b.
Here, we create the variable and set its value right away. Less code and it still makes sense. If you're creating a bunch of variables at the same time, you can create them all in one statement by saying "var" and then listing the variable names separated by commas. You can also do this with values, though that will quickly become hard to read. Exactly how you do this depends on the script you're writing. In some cases, it makes sense to create variables without setting their values. In others, it makes sense to set a value right away.
What's happening here is, the browser says, "I see you're using a variable named c, "but I don't see it defined, "so I'm going to assume you are defining it now." That seems useful, but it's actually a problem. Later in the course, you'll learn about scoping, and how we can place variables in scope or out of scope of functions. Basically, you can create a variable that only exists within a function in your code but nowhere else in the code. If you don't create that variable using the var prefix, though, the new variable gets a global scope, and that can lead to all sorts of weird problems.
We'll talk about most of these data types in this chapter.
- Working with data
- Using functions and objects
- Changing DOM elements
- Handling events
- Working with loops
- Making images responsive using markup
- Troubleshooting code
- Validating functionality