Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type of undefined in javascript? [closed]

Tags:

javascript

This is not a practical problem, I just need an explanation.

I have the following code:

var src = container.find('img').attr('src');
if(src === 'undefined') {
    alert('No src');
}

When i fire up the console and log the src it says it's undefined but the alert is not fired. Debugging this piece of code justifies previous behaviour. When i remove the '' in the if statement and leave undefined as a type, the alert gets triggered.

On the other hand, further down my code i have this piece:

var pathname = (window.location.pathname).split('/');
if(pathname[5] === 'undefined') {
    alert('Something...');
}

And the alert gets triggered properly whenever the console says that pathname[5] is undefined.

Therefore, i figured that in the first case undefined is returned as type and in the second as a string. Is this correct, and why such behaviour?

Thanks for all smart answers!

like image 550
Svemirko Avatar asked Oct 18 '25 13:10

Svemirko


1 Answers

Since src has already has been declared all you need to do is check its truthyness:

if (!src) alert('no src');

If the variable can have a falsy value (empty string, zero, false) then you should check for both undefined and null like:

if (src === null || src === undefined)

Or taking advantage of type casting since null == undefined

if (src == null)
like image 94
elclanrs Avatar answered Oct 20 '25 04:10

elclanrs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!