Javascript Upgrade: default arguments for functions/template strings


This is part of my series about upgrading my Javascript skills.

  1. Previous:
  2. Javascript, I hardly knew ya
  3. Javascript Upgrade: Day 1
  4. Javascript Upgrade: let/const
  5. Javascript Upgrade: Arrow functions


Since these are both fairly quick I’ve put two in one

Default values in functions are something I’m very familiar with as they exist in just about every other language I use.  Either with = like in javascript or // in elixir they are there.

Default values allow you to call a function with fewer parameters than are defined and have the code automatically set the value.  Here’s an example of a function with a default value and using it where we need the default value and where we don’t.

function sayGreeting(name, greeting = "Hi, ") {
  console.log(`${greeting} ${name}`);

sayGreeting("Shawn") //Hi, Shawn
sayGreeting("Shawn", "Yo, ") //Yo, Shawn

If you want to skip an argument you can pass in undefined to trigger the default.  so

function sumThree(one, two=2, three=3) {
  return one + two + three;

sumThree(1) //6
sumThree(1, undefined, 3) //6
sumThree(1, 2) //6
sumThree(1,4,5) //10

Next up are string literals.  These make it much easier to build strings with variables in Javascript and are really simple to use.  Wrap the string in backticks(`) and use ${} around any variables you want to include.

const name = "Shawn";

const test = `Hello ${name}, how are you?` //Hello Shawn, how are you?

//Old way

const test2 = "Hello " + name + ", how are you?" //Hello Shawn, how are you?

I have used similar things in other languages for years now so nothing difficult for me to get use to.  If anything I think this is easier for me.  The only tricky part is remembering it is ${} not #{} which I am more familiar with.

About the author

Add comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

By shawn

Other Things