Reputation: 2122
I'm quite new to using jQuery with Javascript and I've got a bug where I need to analyse every part of a pre-written function.
Part of this function includes an if statement seemingly without a condition and I was hoping someone would be able to explain it to me, code below.
$("a").bind("click", myFunction);
function myFunction(event) {
if (event.target) {
// some code
}
}
My confusion here is what "if (event.target)" is equating to/testing as it is doesn't seem to be comparing anything. Any help or pointing towards reading material would be appreciated.
Thanks in advance!
Upvotes: 0
Views: 49
Reputation: 116100
This is unrelated to jQuery, and just plain JavaScript.
The if statement condition is an expression that in the end evaluates to true or false. This can be an explicit comparison like a===b
, but you can also evaluate other values that are considered to be true or false by the if statement. You're testing whether they are 'truthy' or 'falsy'.
In this particular case, you're basically testing if event.target
has something assigned to it. If it has, it is truthy, otherwise it is falsy. The unwritten assumption is that if it has, it's a valid DOM element.
It's unlikely that something else was assigned to event.target, so this code just loosely checks if something is there or not, rather than checking explicitly whether that something is indeed a valid element and not, say, 15
or 'Hello world'
. These kinds of assumptions are pretty common, because otherwise your code will become slow and hardly readable because of all the checks.
See Mozilla to learn more about 'truthy' and 'falsy'.
Upvotes: 0
Reputation: 3487
Any condition can be tested as 'falsy' or 'truthy'.
For exemple :
const iAmTruthy = true;
if (iAmTruthy) {
console.log('the condition is fulfilled');
}
Here's a list of truthy values in JS : https://developer.mozilla.org/en-US/docs/Glossary/Truthy
Here's another example with falsy value :
const iAmTruthy = false;
if (!iAmTruthy) {
console.log('the condition is fulfilled');
}
And a list of falsy values : https://developer.mozilla.org/en-US/docs/Glossary/Falsy
Upvotes: 2
Reputation: 1513
What you're doing here is comparing the event.target
. It will return true
if the variable have some value (and has been defined), otherwise it will return false
.
Note: false
, 0
, ''
, or null
will return false
too.
var a; //undefined
if(a){ console.log('undefined a: true'); } else { console.log('undefined a: false'); }
a = null;
if(a){ console.log('null a: true'); } else { console.log('null a: false'); }
a = 0;
if(a){ console.log('zero a: true'); } else { console.log('zero a: false'); }
a = '';
if(a){ console.log('empty string a: true'); } else { console.log('empty string a: false'); }
a = 1;
if(a){ console.log('number a: true'); } else { console.log('number a: false'); }
Upvotes: 0