how to use default param in js?
- User
how to use default param in js?
- Assistant
In JavaScript, you can set default parameters by assigning a value directly in the function parameter list. If the caller doesn't pass that argument (or passes undefined), the default will be used. Basic example: jsCopyEditfunction greet(name = "stranger") { console.log(
Hello, ${name}!); }greet(); // Hello, stranger! greet("Shachar"); // Hello, Shachar!
How it works:
If you omit the argument → the default is used.
If you pass undefined → the default is used.
If you pass null or another falsy value → the default is not used (it uses what you passed).
Example: jsCopyEditfunction showValue(x = 10) { console.log(x); }
showValue(); // 10 (default) showValue(undefined); // 10 (default) showValue(null); // null (no default, null is a valid value) showValue(0); // 0 (no default)
You can also use expressions as defaults: jsCopyEditfunction calc(a, b = a * 2) { console.log(a, b); }
calc(5); // 5 10 calc(5, 20) // 5 20
And they work in arrow functions too: jsCopyEditconst add = (a = 1, b = 2) => a + b;
console.log(add()); // 3 console.log(add(5)); // 7
- User
what is the true value of model = "" in js?
- Assistant
In JavaScript, an empty string "" is a falsy value. That means: jsCopyEditif ("") { console.log("truthy"); } else { console.log("falsy"); }
➡️ Output: nginxCopyEditfalsy
Falsy values in JS are:
false
0 and -0
"" (empty string)
null
undefined
NaN
Everything else is truthy (including "0", "false", [], {}, and functions). So for your example: jsCopyEditlet model = ""; Boolean(model) // false
The true value (in Boolean terms) of "" is false. If you want, I can show you a neat trick to check exactly whether something is truthy or falsy in JS.
- User
is there a way to pass only some of the default params?
- Assistant
Yes — in JavaScript, you can pass only some default parameters, but the details depend on how your function is defined.
Case 1: Positional parameters (normal function args) If you use the usual positional parameters with defaults, you can only skip from the end. If you want to skip an earlier argument but still set a later one, you must explicitly pass undefined for the skipped ones. Example: jsCopyEditfunction greet(name = "stranger", age = 30) { console.log(
${name} is ${age} years old); }greet(); // stranger is 30 greet("Shachar"); // Shachar is 30 greet(undefined, 25); // stranger is 25 ✅ greet("Shachar", 40); // Shachar is 40
Notice: You must pass undefined to “trigger” a default if you’re skipping in the middle.
Case 2: Object destructuring (best for partial defaults) If you want to pass only some parameters easily, use an object with destructuring defaults. Example: jsCopyEditfunction createUser({ name = "Anonymous", age = 30, role = "guest" } = {}) { console.log(name, age, role); }