How to set a default parameter value in a JavaScript function?
Hi everyone! I just started learning JavaScript and encountered a problem. I'm writing a function that greets a user. I want it to use the value "Guest" if no name is passed. Here's my code:
```javascript
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Anna")); // Hello, Anna!
console.log(greet()); // Hello, undefined!
```
As you can see, if I call the function without an argument, "undefined" appears in the string. I've read that in other languages, like Python, you can set a default value directly in the parameter. How do I do this in JavaScript? I tried writing `function greet(name = "Guest")`, but I'm not sure if it's correct and if it works in all browsers.
I've also heard about the old way using a check like `if (typeof name ==`
No answers yet.
Log in to leave an answer
Blogs