How to set a default parameter value in JavaScript?
Hello everyone! I'm just starting to learn JavaScript and ran into a problem. I'm writing a function that greets a user. I want that if no name is passed, a default value is used — for example, "Guest". But I can't do it elegantly.
Here's my code:
```javascript
function greet(name) {
console.log("Hello, " + name + "!");
}
```
I tried checking inside the function: `if (name === undefined) { name = "Guest"; }`. It works, but looks cumbersome, especially if there are many parameters. In other languages (e.g., Python), you can just write `def greet(name="Guest"):`. Is there a similar syntax in JavaScript?
I'm also curious what happens if you pass `null` or an empty string. Is that considered "no value"? And how to handle multiple pa
No answers yet.
Log in to leave an answer
Blogs