I have written a function that calls a zipcode API to retrieve the address when entering a ZIP code. (Note: it's a Dutch application and a Dutch zipcode consists of 4 numbers and 2 letters.)
This is the function:
function zipcodeApiCall(zipcodeNum, zipcodeAlfa)
{
console.log(zipcodeNum);
if(zipcodeNum.length == 4 && zipcodeAlfa.length == 2)
{
//some code to call the API that returns some data
}
}
//Call the function
var zipcodeNum = $("#zipcodeNum").val(); //Retrieve val from input field
var result = zipcodeApiCall(zipcodeNum, 'KK');
The problem is that I get the error that zipcodeNum is undefined when retrieving its length. The output of:
console.log(zipcodeNum);
for zipcode numbers 1312 is two lines:
1312
undefined
Which gives me the error 'Uncaught TypeError: Cannot read property 'length' of undefined'. Why does this happen?
What's also strange is that when I retrieve the value of zipcodeNum inside the function, like so:
function zipcodeApiCall()
{
var zipcodeNum = $("#zipcodeNum").val(); //Retrieve val from input field
var zipcodeAlfa = 'KK';
console.log(zipcodeNum);
if(zipcodeNum.length == 4 && zipcodeAlfa.length == 2)
{
//some code to call the API that returns some data
}
}
var result = zipcodeApiCall();
the code executes fine and I don't get any errors.