Tags : JavaScript Intro



Variables

Variables are used when you want to store a value for later use.

We are going to be using variables on the code we wrote in the previous lesson.

Local Variables

Local variables are only available in the nested code of block where they are defined. Once we move out of the block of code (often called "scope", the variable will no longer be available. Watch the video for further explanation.

Local variables are always defined with the "var" keyword. For example, var exampleGreeting = "hello" is a local variable. exampleGreeting is only available within the scope where it was defined.

Global Variables

Global variables are available at all levels of the codes, once the global variable is defined you can access it basically anywhere.

We define global variables without using the keyword "var". So, globalGreeting = "hello" would be a global variable.

Using global variable is a bit dangerous as you can loose track of names and start to overwrite global variables causing your code to have bugs. For now, we are going to avoid using global variables.

index.html

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="css/example.css">
  </head>
  <body>
    <div class="actions">
      <button id="bark">Bark</button>
      <button id="growl">Growl</button>
      <button id="hide">Hide</button>
      <button id="blue">Background Blue</button>
      <button id="none">Remove Background</button>
    </div>
    <div class="activity-tracker">
      <ul></ul>
    </div>  
    <script src="scripts/jquery-1.11.3.js"></script>
    <script src="scripts/myscript.js"></script>
  </body>  
</html>

example.css

.turn-blue {
  background-color: blue;
}

myscript.js

$("button#blue").on("click", function(){
  var makeBlue = "Full moon tonight!";
  $(".activity-tracker ul").prepend("<li>"+ makeBlue +"</li>")
  $("body").addClass("turn-blue");
})

$("#none").on("click", function(){
  var makeClear = "It is daytime";
  $(".activity-tracker ul").empty().prepend("<li>" + makeClear +"</li>")
  $("body").removeClass("turn-blue");
})

$("button#bark").on("click", function(){
  $(".activity-tracker ul").prepend("<li>Woof woof!</li>")
})

$("button#growl").on("click", function(){
  $(".activity-tracker ul").prepend("<li>Was that a bear?</li>")
})

$("button#hide").on("click", function(){
  $(".activity-tracker ul").prepend("<li>Climb up a tree!</li>")
})

Try the following:

  • Try to use local variables for the strings inserted in the li's.
  • Recreate the undefined error for a local variable and try to understand why it happened.
  • Understand the differences between a global and local variable.