<body>
<h1>Insert here:</h1>
<button>Try</button>
<input name='myName' type="text">
<h2>No one here</h2>
<script>
let button = document.querySelector('button');
let h2 = document.querySelector('h2');
let myName = document.querySelector('input');
function sayHi(name = 'Stranger'){
h2.innerHTML = `Hello ${name}`;
}
button.addEventListener('click', ()=>{
sayHi(myName.value);
});
</script>
</body>
So, I recently started JS and I was trying simple functions, just to practice. This code basically should take whatever you write and print "hello (whatyouwrite)" or simply print "hello Stranger" if you write nothing. However I cannot manage to use the default parameter and when I write nothing and press the button it prints "Hello " whith a blank space after hello. I realize the "nothing" I send is still something but I cannot figure out what it is or how to do it properly.
Lastly, I've been following this tutorials: https://youtu.be/WyC678zya3E?list=PLP5MAKLy8lP9FUx06-avV66mS8LXz7_Bb&t=489 which writes the exact same code and, for him, works as it should...
CodePudding user response:
button.addEventListener('click', ()=>{
sayHi(myName.value);
sayHi();//this will invoke default parameter
});
do this instead
function sayHi(name){
if (name.length === 0)
name = 'Stranger';
h2.innerHTML = `Hello ${name}`;
}
CodePudding user response:
It's because myName.value is passing an empty string to the sayHi function. You can add an if condition in the callback for the event listener to check whether myName.value is an empty string or not like this.
button.addEventListener("click", () => {
if (myName.value) {
sayHi(myName.value);
} else {
sayHi();
}
});
or use the ternary operator if you want to be more concise.