Setting variables inside if / else-if statment blocks I have written the code below and I am trying to work out if there is a more efficient way of doing it: i.e. less lines of code and quicker etc.

I am also wondering whether it is OK to declare variables inside of an if ... else if statement.

function test() {
    var x = 3;
    if (x &gt; 5) {
        var msg = "m", state = "d";
    } else if (x &lt; 5) {
        var msg = "a", state = "d";
    } else {
        var msg = "e", state = "n";
    }
    $('#id1').removeClass().addClass(state);
    $('#id2').html("Some text " + msg + " and more text.");
    $('#id3').attr('title', "Different text " + msg + " still different text.");
}


As background, the following code is the original code I had before refactoring/rewriting:


function test() {
  var x = 3;
  if (x &gt; 5) {
        $('#id1').removeClass().addClass('d');
        $('#id2').html("Some text message and more text.");
        $('#id3').attr('title', "Different text message still different text.");
  } else if (x &lt; 5) {
        $('#id1').removeClass().addClass('d');
        $('#id2').html("Some text message2 and more text.");
        $('#id3').attr('title', "Different text message2 still different text.");
  } else {
        $('#id1').removeClass().addClass('n');
        $('#id2').html("Some text message3 and more text.");
        $('#id3').attr('title', "Different text message3 still different text.");
  }
}
I don't know what the purpose of declaring your variable within your if statement is supposed to be here. For readability, I would declare those variables at the beginning of your function, like so:

function test() {
    var x = 3, 
        msg, 
        state;
    if (x &gt; 5) {
        msg = "m", state = "d";
    } else if (x &lt; 5) {
        msg = "a", state = "d";
    } else {
        msg = "e", state = "n";
    }
    $('#id1').removeClass().addClass(state);
    $('#id2').html("Some text " + msg + " and more text.");
    $('#id3').attr('title', "Different text " + msg + " still different text.");
}


That being said, I don't know a reason why you couldn't do so; it most depends on readability and the best practices you are following.