George Ristic
George Ristic

Reputation: 77

Reason to declare variable if it's going to be used only once

What is the point of declaring variable if that variable is going to be used only once? Take a look at those two functions. Is there a difference? Which one is better and why?

function showtext(){
var elem = document.getElementById("elemid");
var txt1 = '<p>Some random text</p>';
elem.innerHTML = txt1;
}

or

function showtext(){
document.getElementById("elemid").innerHTML = '<p>Some random text</p>';
}

Upvotes: 1

Views: 2524

Answers (2)

beautifulcoder
beautifulcoder

Reputation: 11330

JavaScript is function scoped, so all variables get cleaned up once you leave the function.

To me, declaring separate variables for each thing makes sense to keep the code legible. The point of using variables in any programming language is to name and describe things.

So instead of:

function showtext(){
    var unimaginativeName1 = document.getElementById("elemid");
    var unimaginativeName2 = '<p>Some random text</p>';
    unimaginativeName1.innerHTML = unimaginativeName2;
}

You can tell a better story with:

function showtext(){
    var elemDescription = document.getElementById("elemid");
    var elemTxt = '<p>Some random text</p>';
    elemDescription.innerHTML = elemTxt;
}

It would read better than this.

document.getElementById("elemid").innerHTML = '<p>Some random text</p>';

Upvotes: 1

Bergi
Bergi

Reputation: 664599

The only reason for using variables in such a case is better readable code (spread over multiple lines instead of a single too-long one), especially if you use descriptive variable names for your declarations.

In this particular case (except we're dealing with absolute beginners) nothing is gained, as getElementById obviously returns an element, and txt1 means nothing.

Upvotes: 1

Related Questions