Check if Parameter is provided to Function in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 30 20212 min read

banner

Photo by Ruthie Martin

Check if Parameter is provided to Function #

To check if a parameter is provided to a function, use the strict inequality (!==) operator to compare the parameter to undefined, e.g. if (param !== undefined). If the comparison returns true, then the parameter was provided to the function.

index.js
function getParam(param) { if (param !== undefined) { return param; } } console.log(getParam(5)); // ๐Ÿ‘‰๏ธ 5 console.log(getParam()); // ๐Ÿ‘‰๏ธ undefined

We used the strict inequality (!==) operator to check if the value of the parameter is not equal to undefined.

If the condition passes, then we know that the parameter was provided to the function.

Note that the if block wouldn't run if you explicitly pass an undefined value to the function.
index.js
function getParam(param) { if (param !== undefined) { return param; } } console.log(getParam(undefined)); // ๐Ÿ‘‰๏ธ undefined

I can't think of a good use case to do this, so I don't see this as a drawback.

If any other value is passed to the function, the if block runs.

An alternative approach is to use the typeof operator.

To check if a parameter is provided to a function, use the typeof operator to check if the parameter is not equal to the string "undefined", e.g. if (typeof param !== 'undefined'). If the condition is met, the parameter was provided to the function.

index.js
function getParam(param) { if (typeof param !== 'undefined') { return param; } } console.log(getParam(5)); // ๐Ÿ‘‰๏ธ 5 console.log(getParam()); // ๐Ÿ‘‰๏ธ undefined

We used the typeof operator to get a string that indicates the type of a value.

Here are some examples of using the typeof operator.

index.js
console.log(typeof undefined); // ๐Ÿ‘‰๏ธ "undefined" console.log(typeof (() => {})); // ๐Ÿ‘‰๏ธ "function" console.log(typeof function () {}); // ๐Ÿ‘‰๏ธ "function" console.log(typeof null); // ๐Ÿ‘‰๏ธ "object" console.log(typeof []); // ๐Ÿ‘‰๏ธ "object" console.log(typeof {}); // ๐Ÿ‘‰๏ธ "object" console.log(typeof ''); // ๐Ÿ‘‰๏ธ "string" console.log(typeof 0); // ๐Ÿ‘‰๏ธ "number"

When the typeof operator is used on an undefined value it returns the string "undefined", which is exactly what we check for in our if statement.

This is very similar to the previous approach, however I see the first approach used more commonly.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee