Why does it matter?
A Basic Example
- We created a new variable by typing the keyword
- We gave the variable a name so we can use it later, which is
- Then we set the value of the variable equal to 1.
onSlide is our variable name.
- Variable names must begin with a letter (can't start with a number)
Variable names can contain letters and numbers, and ARE case sensitive
onslide are different variables
Example: function, url, var, switch, this
For a larger list check out This Link
Setting the value of a variable
- When you first define a variable you can set it's value or you can just define it and leave it blank (
- After you define it you can change it's value at anytime by typing the variable name and the value you want it to equal.
- Notice that when we set the value to 2, we don't put the word
var in front.
var is only needed when we first define/create the variable.
Using the Current Value of a Variable
- Above we are creating a console.log that will log into the browser console whatever the value of the variable currently is.
You can also use an
if statement to ask if the value of the variable equals a certain value.
NOTE: The === (3 equals signs) is how we ask if the variable is equal to 3 (It's a question)
NOTE: The !== is how we ask if the variable is NOT equal to 3 (It's still a question)
NOTE: onSlide = 3 (1 equals sign) is how we set the variable equal to 3
Manipulating the Current Value
- The code above adds 1 to the
onSlide variable. So if it was 2, it will now be 3. Both lines of code add 1 to the current value.
- When you create a variable you don't have to define it's value. The code above creates a new variable but it's not equal to anything.
- If you try to get the value of this variable the result will be
Undefined variables can occur when you're dynamically assigning the value.
Example: If you are trying to find thumbnails on the page you might do
var thumbs = $(".thumbs"). If none exist the variable "thumbs" will be undefined.
How to check if a variable is defined
- The code above creates an if statement that asks if the value of
onSlide does not equal "undefined", which means it is defined/has a value.
- The code //do something will only run if the value of the variable is defined.
Real World Examples
Getting the Current Item Inside a Function (see the functions tutorial if needed)
Create a Timestamp/Random Number
Create a Timer
Setup Slider Options