Last Updated: February 25, 2016
·
554
· joseluisq

How assign default value to a param in a Javascript function: Basic

Defining a function

In this case true it's the default value.

function myfunction(param) {
   param = (param === undefined) ? true : param;
   return param;
}

Obviously you can define your own custom value.

Testing in console

For the first example the default value output is true

> myfunction();
  true

> myfunction("Hello world !");
  "Hello world !"

> myfunction("");
  ""

> myfunction(123456);
  123456

> myfunction(null);
  null

> myfunction(false);
  false

> myfunction(true);
  true

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside