Adventures in Node: Default Parameters

As you have read in my previous posts, I’ve been taking this amazing course on Node.js. I have found that deeply learning a coding language has really helped me in my testing. In previous years I had learned just enough of a language to get by; now I see the value of really understanding a language!

One of the fun things I’ve learned in this Node.js course is the concept of default parameters. When we create a function, we usually include whatever parameters need to be passed into the function, like this:
const greeting = (name, hometown) => {
console.log(‘Hello, ‘ + name + ‘! How is the weather in ‘ + hometown + ‘ today?’)
}


Then when we call the function, we need to include arguments for those parameters in order for the function to run:
greeting(‘Kristin’, ‘Boston’)
and we’ll get this response:
Hello, Kristin! How is the weather in Boston today?

But what if you’re going to use this function a lot, and most of the time you’ll be passing in the same arguments? Won’t you get tired of typing in those arguments every time?
This is where default parameters come in!

When we create our function, we can set one or more parameters to have a default argument, like this:
const greeting = (name = ‘Kristin’, hometown = ‘Boston’) => {
console.log(‘Hello, ‘ + name + ‘! How is the weather in ‘ + hometown + ‘ today?’)
}

Now we can call the greeting function without passing in any parameters:
greeting()
And we’ll get this response:
Hello, Kristin! How is the weather in Boston today?

If we want to set the first argument to something different, we can call
greeting(‘Joe’)
And we’ll get this response:
Hello, Joe! How is the weather in Boston today?

If instead we want to set the second argument to something different, we can call
greeting(undefined, ‘Seattle’)
And we’ll get this response:
Hello, Kristin! How is the weather in Seattle today?

Or we can decide to replace both arguments, by calling
greeting(‘Joe’, ‘Seattle’)
And we’ll get this response:
Hello, Joe! How is the weather in Seattle today?

It’s really very simple once you see how it works. Think about how many times you’ve gotten tired of typing the same thing over and over in your code, and how many times you’ve accidentally missed a single quote or a comma. Typing () without having to fill in any arguments can really save time over the long run!

3 thoughts on “Adventures in Node: Default Parameters

  1. Pingback: Five Blogs – 19 October 2020 – 5blogs

Comments are closed.