0

What is the best way to test if a javascript variable is passed a value into a function

function test(a, b) {  /* check if b was given a value */ }

I want to say

if(!b)

but this doesn't work if b = 0. Do I have to individually check if it is undefined or null like

if(typeof(b) === 'undefined' || b === null)

or is there a better way to write this?

2 Answers 2

2

you can check the arguments property

if(arguments.length > 1){ //is there a 'b' argument
 //do stuff
}
Sign up to request clarification or add additional context in comments.

Comments

0

I believe you can simply check for undefined:

if (b === undefined)

See http://www.w3schools.com/jsref/jsref_undefined.asp

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.