Reputation: 18520
Say I've got this code:
function helloWorld() {
console.log(helloText);
}
When I call this function, I'd like to do something like this:
helloWord(
helloText = "some example text";
)
which of course doesn't work. But the idea is that I want to change a variable by referencing it's name when calling that function. I see numerous jQuery slideshows and stuff that do this, but I can't seem to figure it out. The closest thing I can find is this:
function helloWorld(helloText) {
console.log(helloText);
}
helloWorld("some example text");
Which will work, but with a longer list of variables, that gets unwieldy. So how can I instead change the variable value by using its name?
Upvotes: 0
Views: 88
Reputation: 816334
Building on the other answers, ECMAScript 6 introduces destructuring and default parameters. This allows you to easily simulate keyword arguments:
function helloWorld({helloText} = {}) {
console.log(helloText);
}
helloWord({
helloText: "some example text"
});
You can use ES6 features today with preprocessors such as 6to5.
Upvotes: 2
Reputation: 782
There are no keyword arguments in Javascript. In order to mimic that behavior, you could use an object literal, like so:
function helloWorld(args) {
console.log(args.helloText);
}
helloWord({
helloText: "some example text"
});
Upvotes: 5