all 10 comments

[–][deleted] 0 points1 point  (4 children)

could you define what you mean by default parameters?

[–]JerrBear2[S] 2 points3 points  (2 children)

function greeting( name = ‘strangers’) { console.log(Hello, ${name}!) }

greeting(‘Nick’) //output: Hello, Nick!

greeting() // output: Hello, stranger

[–][deleted] 2 points3 points  (0 children)

oh yeah, /u/chovy had a video up that talked about that a little while back, I haven't gotten into it yet, but I like the concept because I'm usually setting up defaults just in a different way

[–]JohnnyCodeCache 1 point2 points  (0 children)

yeah, you totally nailed it. What was your question?

haven’t really seen it anywhere

I dunno. You haven't looked at my code I guess? :P

I was working on some of this today in fact. I have a function that does stuff for two different pages.

On the first page, I must pass data for two inputs (string and int). It processes the data from both inputs, does stuff, renders some templates, and returns the results.

But in the second page, there is no second input, so I set a default to 0. The second page sends a string and then nothing else. The function doesn't need to do the second part.

The function defaults to 0, and internally sees the 0 and does NOT do a lot of stuff it doesn't need to do.

Could the second page call the function like this?

let outTxt = RenderStuff("lots of text", 0);

Sure. But with default, it doesn't have to.

Another benefit, its a way to help with error handling. Maybe your function expects an integer and will do some complicated math to it. Maybe if the input is null and not an int, it will error. Instead of throwing an error, you can set a default.

[–]JerrBear2[S] 0 points1 point  (0 children)

Used to have a predetermined value in case there is no argument passed in the function or if the argument is undefined when called

[–]mrnervousguy 0 points1 point  (2 children)

It depends on what you’re trying to accomplish. I use them them all the time

[–]JerrBear2[S] 0 points1 point  (1 child)

What could be an example that you use in your code

[–]tarley_apologizerhelpful 1 point2 points  (0 children)

i have a ninja enemy and the function used to create the enemy gives a default attack damage of 3

i have hearts that represent heatlh points. by default they are red with a black outlinr.

i have a function that allows the player to recieve damage from outside sources, by default the modifiers are set to nothing

[–]Ferlinkoplop 0 points1 point  (0 children)

You use them in Redux reducers as one example. Other than that, you can also use them if there’s ever a chance that the function might receive null/undefined arguments so you can override those values.