1

I'm getting stuck somewhere (as newbies do). Is it ok to re-define a variable once it has been trimmed and tested for content?

    function setarea() {

        var dbasedata = document.forms[0]._dbase_name.value;
            dbasedata = dbasedata.toUpperCase();
            dbasedata = dbasedata.replace(/\s/g, "");
            dbasedata = dbasedata.remove("UK_CONTACTS", "");

        if (dbasedata != "") {
            _area.value = _dbase_name.value;
        } 

   else var dbasedata = document.forms[0]._dbase_name.value;
            dbasedata = dbasedata.toUpperCase();
            dbasedata = dbasedata.replace(/\s/g, "");

        if (dbasedata.indexOf("UK_CONTACTS")>-1 {
        var dbaseterm = "UK_CONTACTS";
   else var dbaseterm = "";     
            }
4
  • 2
    Your identation doesn't really help with reading your code :). Commented May 30, 2012 at 18:18
  • Have a look at this hoisting article, it may explain a few related concepts. Commented May 30, 2012 at 18:21
  • better do: var dbaseterm = (dbasedata.indexOf("UK_CONTACTS") > -1)?'UK_CONTACTS':''; Commented May 30, 2012 at 18:24
  • A little off topic, but I'd chain those first lines in the function. var dbasedata = document.forms[0]._dbase_name.value.toUpperCase().replace(/\s/g, "").remove("UK_CONTACTS", ""); I assume .remove() is being added to String.prototype. Commented May 30, 2012 at 18:30

3 Answers 3

4

It makes no sense to use var more than once for the same variable in the same scope. Since all var x; are hoisted to the top of the scope every additional var on that variable will be a no-op.

Assigning a new value is fine though - they are variables and not constants after all.

function x() {
    var x = 123;
    foo();
    x = 456;
    var y = 'hello';
    var x = 678;
}

is actually this internally:

function x() {
    var x, y; // both are === undefined
    x = 123;
    foo();
    x = 456;
    y = 'hello';
    x = 678;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Yes, you can do this and it is legal.

2 Comments

It is legal but the 'var' declaration is not needed after line: ' dbasedata = dbasedata.remove("UK_CONTACTS", "");'
I want to test the string to see if it contains UK_CONTACTS. If it does I want it to do something. Then, I want to test the the same original string after removing UK_CONTACTS (and white spaces) to see if there is anything else in the string. Not sure how to do that without re-defining the string again.
0

It may 'work', but isn't recommended. You don't need to redeclare it.

Probably want to run your code through JSLint . There are a few tidyness/bracing issues you would want to address.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.