zik
zik

Reputation: 3085

Can value of a JavaScript variable be changed twice in the same function?

Not sure if this is considered best practice or if you should even do this but I have a small block of Javascript and I want to know if you can declare a variable, display that variable and then reassign it and display it again? Syntactically this seems correct but I would assume that this is not best practice and should be avoided?

Note: I did not write this block I just want to know if it's ok or if I should change it and use 2 variables code below:

var u1 = 'something';

if (u1.indexOf('Accept') > 0)
{       
var URL = 'some URL';
document.writeln(URL);
URL = 'another URL';
document.writeln(URL);
}

Thanks in advance.

EDIT:Thanks for the answers, thought it was a bit daft. :/

Upvotes: 2

Views: 1796

Answers (6)

RReverser
RReverser

Reputation: 2035

Why not? Of course, it's normal to change variable value as much times as you want. That's actually reason why it's called "variable", not "constant" :)

Upvotes: 3

Robert Koritnik
Robert Koritnik

Reputation: 105029

Yes you can

You can change variable's value as many times as you need to. Variables are quite often reused so we save memory resources. Not in the way you've used them (because that's an example that would be better off providing constant strings directly when calling functions) but think of an everyday example where we don't even think of multiple variable value assignments. A for loop:

for (var i = 0; i < 100; i++)
{
    ...
}

In this loop variable i gets assigned a new value 101 times. This is a rather obvious example, where we don't think of this at all, but other than that, we could have a set of loops and reuse the same variable more explicitly and assign it a value lots of times like:

var counter = 0;
for(var item = GetLinkedListFirstItem(); item != null; item = item.Next)
{
    counter++;
}
// other code...
counter = 0;
while (counter < 10 || someOtherCondition)
{
    // do something else
}

This may be a much better example of explicit variable reusability where its value gets changed lots of times and for different purposes.

Variable naming

Variable reuse is sometimes unwanted/undesired. And that's when we have a meaningful variable name like isUserLoggedIn. It's hard to reuse such variable for other purposes because it would make code unmaintainable.

Variables that are usually reused may hence be iterators (ie. i) or generally named variables without too much meaning. Or variables with more universal name (ie. finished) which can be reused in different contexts that can be associated with such variable name.

Asynchronous code

There are certain situations where you may have problems even though looking at code may seem perfectly fine. And that's when you use async functions which is frequently the case when using Ajax calls or time-deferred calls (ie. setTimeout). Consider the following code:

var loaded = false;

$.ajax({
    url: "...",
    type: "POST",
    success: function(){
        loaded = true;
    }
});

if (loaded === true)
{
    // do something important
}

// ok loaded not used any more, so we can reuse it
// we can easily change its type from number to string or anything else
loaded = "Peter loaded his gun";

This code has a bug, because important code won't be executed. Ever! This is quite a frequent misconception by unsavvy developers not understanding asynchronism.

Hint: When code issues an Ajax call it doesn't wait for a response but rather continues execution and executes if statement. Even though Ajax call would respond in 0time ticks, success function wouldn't execute until this currently running code wouldn't finish execution. That's how Javascript works. Queued code execution. In the end when Ajax async code would execute it would eventually overwrite the string that was stored in the variable.

Upvotes: 6

Paul Beusterien
Paul Beusterien

Reputation: 29572

Variables can be reassigned in JavaScript. Whether they should or not is a question of style and context.

Upvotes: 1

Evert
Evert

Reputation: 8541

I normally prefer to re-use variables rather than create new ones

Upvotes: 0

qw3n
qw3n

Reputation: 6334

Yes it is possible, and in this case there is no point in creating a new variable. However, if you have a lot of code reassigning a variable later could definitely be confusing especially if at first it's an object then later it is a string.

Upvotes: 1

pimvdb
pimvdb

Reputation: 154858

I'd say it's perfectly fine to do so.

However, keep in mind that it can cause problems with asynchronous code. Take the following example for instance, where async accepts a callback that runs some time later:

var a = 123;

async(function() {
    alert(a); // alerts 456, because `a` was set to 456
              // *before* this callback was run.
              // Because there is only one `a`, that variable
              // has been overridden
});

a = 456;

async(function() {
    alert(a); // alerts 456
});

Upvotes: 2

Related Questions