quick basic javascript question

Soldato
Joined
6 Mar 2008
Posts
10,078
Location
Stoke area
Just brushing up on my web skills and starting picking up Javascript too.

The examples I am using will use things like this:

Code:
var guessInput = document.getElementById("guess");
var guess = guessInput.value

is it not just simpler to use:
Code:
var guess = document.getElemenyByID("guess").value
I know in some languages things can be done but are frowned upon so wanted to check what the standard is?

Also, camel case variables? yes? no?
 
Man of Honour
Joined
13 Oct 2006
Posts
91,167
I assume its done that way incase you want to check another attribute/method of guessInput at a later date (assuming getElementByID has anything other than .value).

Saves typing it out long hand every time.

EDIT: Yeah also has stuff like .innerHTML, etc.
 
Last edited:
Soldato
Joined
12 May 2007
Posts
3,896
Location
Bristol
I would generally go with the first example just because it's more flexible.
However, the second is acceptable (imo) if there is little/no chance that you'll actually use it later on.

camelCase is definitely the most common, but it's up to you really; just be consistent. (Also, if editing someone elses stuff, follow the same convention they've used - regardless of your preference)
 
Last edited:
Soldato
Joined
12 May 2007
Posts
3,896
Location
Bristol
Thanks for the tip trip :D

np.

Regarding vars, the general rule of thumb is that if you're going to reference an element more than once, put it in a var.
If you wrote longhand and pulled 5 attributes off an element, that's 5 separate times the browser would have to search through the DOM to find your element.
Doing the same using a var would only require 1 trip through the DOM.
 
Caporegime
Joined
18 Oct 2002
Posts
32,618
With the first example you can check if 'guessInput' is defined because if it is undefined and you try to access the '.value' property bad things might happen.
 
Soldato
Joined
26 Sep 2010
Posts
7,157
Location
Stoke-on-Trent
I echo above.

getElementById() will retrieve a DOM object for you to do stuff and things with. If you're only doing 1 thing on that DOM object, and you're 100% sure what you want to do is possible, then you can get away with chaining the property of the object onto the actual object retrieval and you're fine, as per your second example.

if you want to do more than 1 thing with the object then store that object in a variable so the browser only needs to traverse the DOM once then do what you want to that variable, as per your first example.
 
Back
Top Bottom