Reputation: 11
I am starting to learn JavaScript and have been using w3schools as my resource. As a new kid on the block I would like to ask a humble and simple question. In layman's terms - What is the difference between:
this code
function myFunction() {
return "Hello World"
}
document.getElementById('demo').innerHTML = myFunction();
and that code
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World!";
}
myFunction();
Reason I am asking is:
I am doing some exercises and I got the end result correctly by doing this code but then when I clicked "show answer" the code shown is that code which is different from mine.
In addition to my question - which one is practical and which one is best for what situation?
reference exercise link.
Upvotes: 1
Views: 81
Reputation: 1476
Javascript is well known for multitude of ways to accomplish same result. Based on your code snippets it's very subjective to say which is more practical. Both of them are fairly simple, just to proof the concept (you don't have function that only returns string).
To answer your comment lets try to imagine more practical situation.
var isAuth = true; // lets imagine this comes as result of non trivial authentication process
function customGreeting(isAuthenticated) {
return isAuthenticated ? "Hello, welcome back" : "Please Sign in to continue";
}
document.getElementById('demo').innerHTML = customGreeting(isAuth);
Above code uses approach from first snippet. Some might say that it more 'elegant' than using second approach (bellow).
var isAuth = true; // lets imagine this comes as result of non trivial authentication process
function customGreeting(isAuthenticated) {
if(isAuthenticated){
document.getElementById("demo").innerHTML = "Hello, welcome back";
}else{
document.getElementById("demo").innerHTML = "Please Sign in to continue";
}
}
customGreeting();
If we set functional programming approach aside (with is out of scope for this discussion) it's very hard to argue which approach is better.
Upvotes: 0
Reputation: 5122
Given the code you described,
function myFunction() {
return "Hello World"
}
document.getElementById('demo').innerHTML = myFunction();
If myFunction()
were executed somewhere else (say attached to a button), it would simply return the string "Hello World".
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World!";
}
myFunction();
When myFunction()
is executed as described above, it would change the HTML of an element with the id="demo"
.
The complete set of code, including the fourth line of each would do the same thing, but the function inside each would provide completely different functionality.
Upvotes: 1
Reputation: 1172
They produce the same result however the first one gets the string value from the function call whereas the second assigns the value directly from within the function.
Upvotes: 0