jQuery does not add a new if keyword, but it is often used inside jQuery code to control what happens after a selection, event, or AJAX response. The real value is in combining jQuery selections with normal JavaScript conditionals.
That pattern is useful when you need to check element count, visibility, or data before applying jQuery hide() or another DOM action.
Tested on: Node.js v20.18.2. A short note after each runnable snippet describes what you should see in the console.
Method 1: Use if with a jQuery selection
A common check is whether the selection matched any elements.
const count = 1;
if (count > 0) {
console.log("jquery-if:", "matched");
}Expected output:
You should see one line logging jquery-if: matched.
Use this pattern before you call a method on a collection that might be empty.
Method 2: Use else if and else for branch logic
You can branch your code based on the state of the page or the selected element.
const status = "hidden";
if (status === "visible") {
console.log("jquery-status:", "show");
} else if (status === "hidden") {
console.log("jquery-status:", "hide");
} else {
console.log("jquery-status:", "toggle");
}Expected output:
You should see one line logging jquery-status: hide.
This style is common when you are deciding whether to hide, show, or toggle an element.
Method 3: Combine conditional checks with jQuery methods
Check the state first, then call the effect or DOM method.
const visible = false;
if (visible) {
console.log("action:", "show");
} else {
console.log("action:", "hide");
}Expected output:
You should see one line logging action: hide.
That pattern keeps jQuery code predictable and easy to maintain.
Summary
A jQuery if statement is really normal JavaScript condition logic used around jQuery selections and events. Use it to check state, branch cleanly, and decide whether to show, hide, or update an element.
