I am pretty new to web dev and I have been doing some JavaScript exercises I found on line. One of them asks to prompt the user for a first and last name and add these names to the document.
In researching this I found code that used a lot of variables. My solution was this:
var el = document.getElementById("welcome");
var txt = fullName;
var node = document.createTextNode(txt);
el.appendChild(node);
};
greet()
I played around a bit, and found that this worked:
document.getElementById("welcome").appendChild(document.createTextNode(fullName));
You can see my original solution at jsFiddle. I also added the instructions to the HTML.
My question is why do most tuts suggest putting in the variables at all? Is it best practice? Why?
Oh, and if you go there, can someone tell me why my ordered list came out with no numbers? Does jsFiddle use a reset on their CSS?
Note: I’m not sure I needed to put it in a function, but right now, putting everything in a box helps me keep organized.
Thanks for any help
Dave
It is not that you need to use many variables in your code, it’s just that you are a beginner and often author doesn’t use super programming skills to teach beginner’s, as and when you learn you can make your code stronger, shorter, and much intelligent. So if you are writing a better code while you are studying that’s seems that you are learning much much faster…Using variables to hold values is often a good practice..but ofcourse if you are smart enough to make your work without using much of them is no harm…here’s a simple example where you don’t actually need 2 variables
could be simply written as
But again when going for the second approach you might not be using
var totaleverywhere and you need to change the values yourself everytime you want a result, so better create sufficient variables which will be easier for you to modify your code and use the data accordinglyAnd for the other question, yes jsfiddle do resets CSS
Just uncheck Normalized CSS if you don’t want to reset the elements