Implementing Short-Circuit Evaluation for Efficient JavaScript Code
Guidelines on using short-circuit evaluation to simplify code and avoid unnecessary operations in JavaScript.
0 likes
179 views
Rule Content
{
"title": "Implementing Short-Circuit Evaluation for Efficient JavaScript Code",
"description": "Guidelines on using short-circuit evaluation to simplify code and avoid unnecessary operations in JavaScript.",
"category": "JavaScript Cursor Rules",
"rules": [
{
"id": "JS-SHORT-CIRCUIT-001",
"name": "Use Logical AND (&&) for Conditional Execution",
"description": "Utilize the logical AND operator to execute code only when a condition is truthy, reducing the need for explicit if statements.",
"examples": {
"good": [
"user.isAuthenticated && displayUserProfile(user);"
],
"bad": [
"if (user.isAuthenticated) {\n displayUserProfile(user);\n}"
]
}
},
{
"id": "JS-SHORT-CIRCUIT-002",
"name": "Use Logical OR (||) for Default Values",
"description": "Employ the logical OR operator to assign default values when a variable is falsy, streamlining variable initialization.",
"examples": {
"good": [
"const username = inputName || 'Guest';"
],
"bad": [
"const username = inputName ? inputName : 'Guest';"
]
}
},
{
"id": "JS-SHORT-CIRCUIT-003",
"name": "Use Nullish Coalescing Operator (??) for Null or Undefined Checks",
"description": "Apply the nullish coalescing operator to provide default values only when a variable is null or undefined, preserving other falsy values.",
"examples": {
"good": [
"const count = userInput ?? 0;"
],
"bad": [
"const count = userInput || 0;"
]
}
},
{
"id": "JS-SHORT-CIRCUIT-004",
"name": "Use Optional Chaining (?.) for Safe Property Access",
"description": "Utilize optional chaining to access nested object properties safely, preventing errors when intermediate properties are null or undefined.",
"examples": {
"good": [
"const city = user?.address?.city;"
],
"bad": [
"const city = user && user.address && user.address.city;"
]
}
},
{
"id": "JS-SHORT-CIRCUIT-005",
"name": "Use Logical Assignment Operators for Concise Assignments",
"description": "Leverage logical assignment operators (||=, &&=, ??=) to simplify variable assignments based on their current value.",
"examples": {
"good": [
"let config = {};\nconfig.settings ||= defaultSettings;"
],
"bad": [
"let config = {};\nif (!config.settings) {\n config.settings = defaultSettings;\n}"
]
}
}
]
}