Last updated: Mar 3, 2024
Reading timeยท2 min
To check if a parameter is provided to a function, use the strict inequality
(!==) operator to compare the parameter to undefined
.
If the comparison returns true
, then the parameter was provided to the
function.
function getParam(param) { if (param !== undefined) { console.log('The parameter was provided to the function'); 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 the parameter is provided to the function.
if
block wouldn't run if you explicitly pass an undefined
value to the function.function getParam(param) { if (param !== undefined) { console.log('The parameter was provided'); return param; } else { // ๐๏ธ this runs console.log('The parameter was not provided'); } } 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.
Alternatively, you can use the typeof
operator.
If the condition is met, the parameter is provided to the function.
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.
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.
You can assign a default value for the parameter if there is a value that suits your use case.
function getParam(param = 'hello') { return param; } console.log(getParam()); // ๐๏ธ hello console.log(getParam('world')); // ๐๏ธ world
We used a default value of the string hello
for when the function is invoked
without a parameter.
The default value is also used if the function gets passed a value of
undefined
.
function getParam(param = 'hello') { return param; } console.log(getParam(undefined)); // ๐๏ธ hello console.log(getParam('world')); // ๐๏ธ world
If the function gets called with a value for the parameter, the supplied value is used.
You can learn more about the related topics by checking out the following tutorials: