I am trying to pass a function to createTextNode
so that I will have printed on screen : i am singing Let It GO
& i am dancing as well while singing
which are passed to the function through parameters.
The problem is that only the first argument appears.
function sing(song ,dance){
return`i am singing ${song}`
callback();
}
function dance(){
return "i am dancing as well while singing";
}
let singing=sing("Let It GO","dance");
const elP=document.createElement("p");
const elT=document.createTextNode(singing)
elP.appendChild(elT);
document.body.appendChild(elP);
Just reference dance
using string interpolation the same way you referenced song
like this:
function sing(song ,dance){
return `i am singing ${song}, ${dance}`;
}
function dance(){
return "i am dancing as well while singing";
}
let singing=sing("Let It GO", dance());
const elP=document.createElement("p");
const elT=document.createTextNode(singing)
elP.appendChild(elT);
document.body.appendChild(elP);
However, if the dance function only returns a string, a cleaner approach would be to reference the dance
string in the sing()
parameter itself as you did with the song
string.
In the following I created a function called sing
just as you did and simply used ${song}
and ${dance}
to retrieve the parameters, input the parameter values within the function parentheses itself and use them anywhere I want may it be in a console log or a div or an alert box.
Check this jsFiddle or run the Code Snippet below to see the results of the following code:
var div = document.getElementById("output");
function sing(song, dance) {
div.innerHTML = `<p>The song is: <strong>${song}</strong> and the dance is: <strong>${dance}</strong></p>`
}
sing("HipHop", "BreakDance");
<div id="output"></div>