SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Apr 2010
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question Switch Statement and Variable Scope

    Hello,

    I hope one (or some) of the experts in this forum would chime-in on this thread to help clear my understanding.

    I've created a jQuery script that uses a switch statement. However, my experience with it, relative to variable scope, doesn't seem to follow the logic.

    According to the JavaScript/jQuery theory, a global variable was accessible (meaning read & write) throughtout any function within any script (one that page).

    However, apparently that theory wasn't completely true as it pertained to switch statements that contained variables.

    To illustrate my case in point, I've included a simplistic version of my code:
    --------------------------------------------------------
    $("#selector").delegate("div", "click", function(event) {

    var testVar = 4;
    switch (this.id) {

    case "id1":
    alert(testVar); message returns 4
    do something
    var testVar = 3;
    alert(testVar); message returns 3

    case "id2":
    alert(testVar); message returns 4 "yikes!"

    }
    });
    ------------------------------------------------------

    As shown, the variable "testVar" is not accessible from one case to the next case .

    This situation drove me nuts until I figured it out, which in my mind is stupid.
    Am I missing something terribly important in my assessment here?

    Furthermore, to add insult to injury, I am seeing the same behavior within the conditional if else statement counterpart to the switch statement.

    As always, thank you for your comments.

    Bryan

  2. #2
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,862
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    If a statement doesn't get run because of being inside of an if statement or switch statement in a path that isn't true then that statement is effectively not there in so far as JavaScript is concerned since the JavaScript doesn't run that statement.
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •