The issue arises with the line:
test(name="harry")
In this scenario, you didn't establish a default parameter but instead created a global variable that remains in the global scope, thereby cluttering the environment with that specific value (highlighting why globals are discouraged).
To address default parameters correctly, the code should be structured as follows:
// defining the function while setting its default parameter
// named "name", and assigning it the value of "Harry":
function test(name = "Harry"){
console.log(name)
let test = (name !== "undefined") ? "test" : "welp"
}
test("Marge") // outputs Marge
test() // outputs Harry
An alternative approach involves a slight modification:
// defining the function using a default parameter
// named "name", with a value of "Harry":
const test = function (name = "Harry"){
console.log(name)
let test = (name !== "undefined") ? "test" : "welp"
}
test("Marge") // outputs Marge
test() // outputs Harry
Alternatively, an Arrow function can be used:
// defining the function with a default parameter
// named "name", set to "Harry":
const test = (name = "Harry") => {
console.log(name)
let test = (name !== "undefined") ? "test" : "welp"
}
test("Marge") // outputs Marge
test() // outputs Harry
If multiple defaults are desired:
// defining the function and a parameter to be passed
// to the function, called "opts":
const test = function(opts) {
// specifying defaults for the function
// (other approaches exist, but this is an example):
let defaults = {
givenName: "Harry",
familyName: "Harrison"
},
// merging the defaults with user-supplied options:
details = Object.assign(defaults, opts),
// creating the name using template literals,
// which incorporate JavaScript into the String:
name = `${details.givenName} ${details.familyName}`;
console.log(name)
let test = (name !== "undefined") ? "test" : "welp"
}
test({
givenName: "Marge"
}) // outputs Marge Harrison
test({
familyName: "Kanagarathnam"
}); // outputs Harry Kanagarathnam
test() // outputs Harry Harrison
References: