javascript - consolidate multiple null/undefined checks












1












$begingroup$


My brain is fried from looking from looking at this for so long. Is there a more efficient way to do this code block. We have the ability to use es6 code too if that helps.



First it tries to set quantity to itemTemplateIDQty.value if itemTemplateQty is not valid and itemTemplateIDQty is valid. Then it basically checks the opposite and sets quantity to itemTemplateQty.value. I'm thinking since in that else block, I am simply checking the exact opposite, I shouldn't need to retype all that code again. Also I'm wondering if I can remove a lot of code by using something like quantity = itemTemplateIDQty.value || 1;.



Update
I'll try to sum up the code more clearly. The default value for quantity should be 1 if all the checks fail. First if there are no classes of itemTemplateQty found and 1+ classes of 'itemTemplateQty' + itemId found then set quantity to the value of the first class found of 'itemTemplateQty' + itemId. If that check fails, then check if no classes of 'itemTemplateQty' + itemId are found and 1+ classes of itemTemplateQty are found, set quantity to the value of the first class of itemTemplateQty.






let itemId = 5;
let isDynamicRecommendation = false;
let itemTemplateQty =
document.getElementsByClassName('itemTemplateQty').length > 0 ? document.getElementsByClassName('itemTemplateQty') : null;
let itemTemplateIDQty =
document.getElementsByClassName('itemTemplateQty' + itemId).length > 0 ? document.getElementsByClassName('itemTemplateQty' + itemId) : null;
let quantity = 1;
if (!isDynamicRecommendation) {
if ((itemTemplateQty === null || itemTemplateQty.value == null || Number.parseInt(itemTemplateQty.value) <= 0) &&
(itemTemplateIDQty !== null && itemTemplateIDQty.value !== undefined && itemTemplateIDQty.value !== null && Number.parseInt(itemTemplateIDQty.value) > 0)) {
quantity = itemTemplateIDQty.value;
} else if ((itemTemplateIDQty === null || itemTemplateIDQty.value == null || Number.parseInt(itemTemplateIDQty.value) <= 0) &&
(itemTemplateQty !== null && itemTemplateQty.value !== undefined && itemTemplateQty.value !== null && Number.parseInt(itemTemplateQty.value) > 0)) {
quantity = itemTemplateQty.value;
}
}
console.log("quantity: ", quantity);












share|improve this question









New contributor




dmikester1 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$








  • 1




    $begingroup$
    Hey, welcome to Code Review! Please add some more information about what this code does and what the objects in it are (preferably with definitions). Don't forget to take the tour and have a look at our help center which contains a lot on what makes a good question here.
    $endgroup$
    – Graipher
    6 hours ago












  • $begingroup$
    I added more details to the question. Let me know if anything else is needed.
    $endgroup$
    – dmikester1
    5 hours ago






  • 1




    $begingroup$
    As Graipher said, you should provide more context for this code — ideally a live demo including the HTML form (press Ctrl-M in the question editor to make one). How many elements of class itemTemplateQty and itemTemplateQty123 should there be? What is the expected behavior if there are none, or if there are more than one?
    $endgroup$
    – 200_success
    5 hours ago






  • 1




    $begingroup$
    Instead of reiterating what the code does, try telling us what goal of the code is, as if talking to a non-technical person.
    $endgroup$
    – 200_success
    5 hours ago
















1












$begingroup$


My brain is fried from looking from looking at this for so long. Is there a more efficient way to do this code block. We have the ability to use es6 code too if that helps.



First it tries to set quantity to itemTemplateIDQty.value if itemTemplateQty is not valid and itemTemplateIDQty is valid. Then it basically checks the opposite and sets quantity to itemTemplateQty.value. I'm thinking since in that else block, I am simply checking the exact opposite, I shouldn't need to retype all that code again. Also I'm wondering if I can remove a lot of code by using something like quantity = itemTemplateIDQty.value || 1;.



Update
I'll try to sum up the code more clearly. The default value for quantity should be 1 if all the checks fail. First if there are no classes of itemTemplateQty found and 1+ classes of 'itemTemplateQty' + itemId found then set quantity to the value of the first class found of 'itemTemplateQty' + itemId. If that check fails, then check if no classes of 'itemTemplateQty' + itemId are found and 1+ classes of itemTemplateQty are found, set quantity to the value of the first class of itemTemplateQty.






let itemId = 5;
let isDynamicRecommendation = false;
let itemTemplateQty =
document.getElementsByClassName('itemTemplateQty').length > 0 ? document.getElementsByClassName('itemTemplateQty') : null;
let itemTemplateIDQty =
document.getElementsByClassName('itemTemplateQty' + itemId).length > 0 ? document.getElementsByClassName('itemTemplateQty' + itemId) : null;
let quantity = 1;
if (!isDynamicRecommendation) {
if ((itemTemplateQty === null || itemTemplateQty.value == null || Number.parseInt(itemTemplateQty.value) <= 0) &&
(itemTemplateIDQty !== null && itemTemplateIDQty.value !== undefined && itemTemplateIDQty.value !== null && Number.parseInt(itemTemplateIDQty.value) > 0)) {
quantity = itemTemplateIDQty.value;
} else if ((itemTemplateIDQty === null || itemTemplateIDQty.value == null || Number.parseInt(itemTemplateIDQty.value) <= 0) &&
(itemTemplateQty !== null && itemTemplateQty.value !== undefined && itemTemplateQty.value !== null && Number.parseInt(itemTemplateQty.value) > 0)) {
quantity = itemTemplateQty.value;
}
}
console.log("quantity: ", quantity);












share|improve this question









New contributor




dmikester1 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$








  • 1




    $begingroup$
    Hey, welcome to Code Review! Please add some more information about what this code does and what the objects in it are (preferably with definitions). Don't forget to take the tour and have a look at our help center which contains a lot on what makes a good question here.
    $endgroup$
    – Graipher
    6 hours ago












  • $begingroup$
    I added more details to the question. Let me know if anything else is needed.
    $endgroup$
    – dmikester1
    5 hours ago






  • 1




    $begingroup$
    As Graipher said, you should provide more context for this code — ideally a live demo including the HTML form (press Ctrl-M in the question editor to make one). How many elements of class itemTemplateQty and itemTemplateQty123 should there be? What is the expected behavior if there are none, or if there are more than one?
    $endgroup$
    – 200_success
    5 hours ago






  • 1




    $begingroup$
    Instead of reiterating what the code does, try telling us what goal of the code is, as if talking to a non-technical person.
    $endgroup$
    – 200_success
    5 hours ago














1












1








1





$begingroup$


My brain is fried from looking from looking at this for so long. Is there a more efficient way to do this code block. We have the ability to use es6 code too if that helps.



First it tries to set quantity to itemTemplateIDQty.value if itemTemplateQty is not valid and itemTemplateIDQty is valid. Then it basically checks the opposite and sets quantity to itemTemplateQty.value. I'm thinking since in that else block, I am simply checking the exact opposite, I shouldn't need to retype all that code again. Also I'm wondering if I can remove a lot of code by using something like quantity = itemTemplateIDQty.value || 1;.



Update
I'll try to sum up the code more clearly. The default value for quantity should be 1 if all the checks fail. First if there are no classes of itemTemplateQty found and 1+ classes of 'itemTemplateQty' + itemId found then set quantity to the value of the first class found of 'itemTemplateQty' + itemId. If that check fails, then check if no classes of 'itemTemplateQty' + itemId are found and 1+ classes of itemTemplateQty are found, set quantity to the value of the first class of itemTemplateQty.






let itemId = 5;
let isDynamicRecommendation = false;
let itemTemplateQty =
document.getElementsByClassName('itemTemplateQty').length > 0 ? document.getElementsByClassName('itemTemplateQty') : null;
let itemTemplateIDQty =
document.getElementsByClassName('itemTemplateQty' + itemId).length > 0 ? document.getElementsByClassName('itemTemplateQty' + itemId) : null;
let quantity = 1;
if (!isDynamicRecommendation) {
if ((itemTemplateQty === null || itemTemplateQty.value == null || Number.parseInt(itemTemplateQty.value) <= 0) &&
(itemTemplateIDQty !== null && itemTemplateIDQty.value !== undefined && itemTemplateIDQty.value !== null && Number.parseInt(itemTemplateIDQty.value) > 0)) {
quantity = itemTemplateIDQty.value;
} else if ((itemTemplateIDQty === null || itemTemplateIDQty.value == null || Number.parseInt(itemTemplateIDQty.value) <= 0) &&
(itemTemplateQty !== null && itemTemplateQty.value !== undefined && itemTemplateQty.value !== null && Number.parseInt(itemTemplateQty.value) > 0)) {
quantity = itemTemplateQty.value;
}
}
console.log("quantity: ", quantity);












share|improve this question









New contributor




dmikester1 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$




My brain is fried from looking from looking at this for so long. Is there a more efficient way to do this code block. We have the ability to use es6 code too if that helps.



First it tries to set quantity to itemTemplateIDQty.value if itemTemplateQty is not valid and itemTemplateIDQty is valid. Then it basically checks the opposite and sets quantity to itemTemplateQty.value. I'm thinking since in that else block, I am simply checking the exact opposite, I shouldn't need to retype all that code again. Also I'm wondering if I can remove a lot of code by using something like quantity = itemTemplateIDQty.value || 1;.



Update
I'll try to sum up the code more clearly. The default value for quantity should be 1 if all the checks fail. First if there are no classes of itemTemplateQty found and 1+ classes of 'itemTemplateQty' + itemId found then set quantity to the value of the first class found of 'itemTemplateQty' + itemId. If that check fails, then check if no classes of 'itemTemplateQty' + itemId are found and 1+ classes of itemTemplateQty are found, set quantity to the value of the first class of itemTemplateQty.






let itemId = 5;
let isDynamicRecommendation = false;
let itemTemplateQty =
document.getElementsByClassName('itemTemplateQty').length > 0 ? document.getElementsByClassName('itemTemplateQty') : null;
let itemTemplateIDQty =
document.getElementsByClassName('itemTemplateQty' + itemId).length > 0 ? document.getElementsByClassName('itemTemplateQty' + itemId) : null;
let quantity = 1;
if (!isDynamicRecommendation) {
if ((itemTemplateQty === null || itemTemplateQty.value == null || Number.parseInt(itemTemplateQty.value) <= 0) &&
(itemTemplateIDQty !== null && itemTemplateIDQty.value !== undefined && itemTemplateIDQty.value !== null && Number.parseInt(itemTemplateIDQty.value) > 0)) {
quantity = itemTemplateIDQty.value;
} else if ((itemTemplateIDQty === null || itemTemplateIDQty.value == null || Number.parseInt(itemTemplateIDQty.value) <= 0) &&
(itemTemplateQty !== null && itemTemplateQty.value !== undefined && itemTemplateQty.value !== null && Number.parseInt(itemTemplateQty.value) > 0)) {
quantity = itemTemplateQty.value;
}
}
console.log("quantity: ", quantity);








let itemId = 5;
let isDynamicRecommendation = false;
let itemTemplateQty =
document.getElementsByClassName('itemTemplateQty').length > 0 ? document.getElementsByClassName('itemTemplateQty') : null;
let itemTemplateIDQty =
document.getElementsByClassName('itemTemplateQty' + itemId).length > 0 ? document.getElementsByClassName('itemTemplateQty' + itemId) : null;
let quantity = 1;
if (!isDynamicRecommendation) {
if ((itemTemplateQty === null || itemTemplateQty.value == null || Number.parseInt(itemTemplateQty.value) <= 0) &&
(itemTemplateIDQty !== null && itemTemplateIDQty.value !== undefined && itemTemplateIDQty.value !== null && Number.parseInt(itemTemplateIDQty.value) > 0)) {
quantity = itemTemplateIDQty.value;
} else if ((itemTemplateIDQty === null || itemTemplateIDQty.value == null || Number.parseInt(itemTemplateIDQty.value) <= 0) &&
(itemTemplateQty !== null && itemTemplateQty.value !== undefined && itemTemplateQty.value !== null && Number.parseInt(itemTemplateQty.value) > 0)) {
quantity = itemTemplateQty.value;
}
}
console.log("quantity: ", quantity);





let itemId = 5;
let isDynamicRecommendation = false;
let itemTemplateQty =
document.getElementsByClassName('itemTemplateQty').length > 0 ? document.getElementsByClassName('itemTemplateQty') : null;
let itemTemplateIDQty =
document.getElementsByClassName('itemTemplateQty' + itemId).length > 0 ? document.getElementsByClassName('itemTemplateQty' + itemId) : null;
let quantity = 1;
if (!isDynamicRecommendation) {
if ((itemTemplateQty === null || itemTemplateQty.value == null || Number.parseInt(itemTemplateQty.value) <= 0) &&
(itemTemplateIDQty !== null && itemTemplateIDQty.value !== undefined && itemTemplateIDQty.value !== null && Number.parseInt(itemTemplateIDQty.value) > 0)) {
quantity = itemTemplateIDQty.value;
} else if ((itemTemplateIDQty === null || itemTemplateIDQty.value == null || Number.parseInt(itemTemplateIDQty.value) <= 0) &&
(itemTemplateQty !== null && itemTemplateQty.value !== undefined && itemTemplateQty.value !== null && Number.parseInt(itemTemplateQty.value) > 0)) {
quantity = itemTemplateQty.value;
}
}
console.log("quantity: ", quantity);






javascript






share|improve this question









New contributor




dmikester1 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




dmikester1 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 5 hours ago







dmikester1













New contributor




dmikester1 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 6 hours ago









dmikester1dmikester1

1115




1115




New contributor




dmikester1 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





dmikester1 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






dmikester1 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








  • 1




    $begingroup$
    Hey, welcome to Code Review! Please add some more information about what this code does and what the objects in it are (preferably with definitions). Don't forget to take the tour and have a look at our help center which contains a lot on what makes a good question here.
    $endgroup$
    – Graipher
    6 hours ago












  • $begingroup$
    I added more details to the question. Let me know if anything else is needed.
    $endgroup$
    – dmikester1
    5 hours ago






  • 1




    $begingroup$
    As Graipher said, you should provide more context for this code — ideally a live demo including the HTML form (press Ctrl-M in the question editor to make one). How many elements of class itemTemplateQty and itemTemplateQty123 should there be? What is the expected behavior if there are none, or if there are more than one?
    $endgroup$
    – 200_success
    5 hours ago






  • 1




    $begingroup$
    Instead of reiterating what the code does, try telling us what goal of the code is, as if talking to a non-technical person.
    $endgroup$
    – 200_success
    5 hours ago














  • 1




    $begingroup$
    Hey, welcome to Code Review! Please add some more information about what this code does and what the objects in it are (preferably with definitions). Don't forget to take the tour and have a look at our help center which contains a lot on what makes a good question here.
    $endgroup$
    – Graipher
    6 hours ago












  • $begingroup$
    I added more details to the question. Let me know if anything else is needed.
    $endgroup$
    – dmikester1
    5 hours ago






  • 1




    $begingroup$
    As Graipher said, you should provide more context for this code — ideally a live demo including the HTML form (press Ctrl-M in the question editor to make one). How many elements of class itemTemplateQty and itemTemplateQty123 should there be? What is the expected behavior if there are none, or if there are more than one?
    $endgroup$
    – 200_success
    5 hours ago






  • 1




    $begingroup$
    Instead of reiterating what the code does, try telling us what goal of the code is, as if talking to a non-technical person.
    $endgroup$
    – 200_success
    5 hours ago








1




1




$begingroup$
Hey, welcome to Code Review! Please add some more information about what this code does and what the objects in it are (preferably with definitions). Don't forget to take the tour and have a look at our help center which contains a lot on what makes a good question here.
$endgroup$
– Graipher
6 hours ago






$begingroup$
Hey, welcome to Code Review! Please add some more information about what this code does and what the objects in it are (preferably with definitions). Don't forget to take the tour and have a look at our help center which contains a lot on what makes a good question here.
$endgroup$
– Graipher
6 hours ago














$begingroup$
I added more details to the question. Let me know if anything else is needed.
$endgroup$
– dmikester1
5 hours ago




$begingroup$
I added more details to the question. Let me know if anything else is needed.
$endgroup$
– dmikester1
5 hours ago




1




1




$begingroup$
As Graipher said, you should provide more context for this code — ideally a live demo including the HTML form (press Ctrl-M in the question editor to make one). How many elements of class itemTemplateQty and itemTemplateQty123 should there be? What is the expected behavior if there are none, or if there are more than one?
$endgroup$
– 200_success
5 hours ago




$begingroup$
As Graipher said, you should provide more context for this code — ideally a live demo including the HTML form (press Ctrl-M in the question editor to make one). How many elements of class itemTemplateQty and itemTemplateQty123 should there be? What is the expected behavior if there are none, or if there are more than one?
$endgroup$
– 200_success
5 hours ago




1




1




$begingroup$
Instead of reiterating what the code does, try telling us what goal of the code is, as if talking to a non-technical person.
$endgroup$
– 200_success
5 hours ago




$begingroup$
Instead of reiterating what the code does, try telling us what goal of the code is, as if talking to a non-technical person.
$endgroup$
– 200_success
5 hours ago










2 Answers
2






active

oldest

votes


















2












$begingroup$

.getElementsByClassName() returns an HTMLCollection, not a single element. You can use bracket notation [n] to get an element at index n of the collection returned.



One if statement can be used to evalaute !itemData.isDynamicRecommendation. One if..else..if can be used to evaluate itemTemplateQty[0] && itemTemplateQty[0].value <= 0 or itemTemplateIDQty[0] && itemTemplateIDQty[0].value <= 0.



To convert the string .value to an integer you can use + operator preceding +itemTemplateQty[0].value.value or alternatively use .valueAsNumber.






let itemData = 5;
let isDynamicRecommendation = false;

let itemTemplateQty = document.getElementsByClassName('itemTemplateQty')[0];
let itemTemplateIDQty = document.getElementsByClassName('itemTemplateQty' + itemData)[0];
let quantity = 1;
if (!isDynamicRecommendation) {
if (itemTemplateQty && itemTemplateQty.value <= 0) {
quantity = +itemTemplateQty.value;
} else if (itemTemplateIDQty && itemTemplateIDQty.value <= 0) {
quantity = +itemTemplateIDQty.value;
}
}

console.log({quantity});








share|improve this answer











$endgroup$













  • $begingroup$
    Wouldn't you want this and the next one to be || not &&? if (itemTemplateQty && itemTemplateQty[0].value <= 0) {
    $endgroup$
    – dmikester1
    5 hours ago












  • $begingroup$
    @dmikester1 Not sure what you mean?
    $endgroup$
    – guest271314
    5 hours ago










  • $begingroup$
    the if and else if should have or's not and's I think
    $endgroup$
    – dmikester1
    5 hours ago










  • $begingroup$
    @dmikester1 if..else could essentially be considered an OR gate. The code could be re-written many different ways. For example, conditional operator could be substituted for if and if..else. One issue with the code at the question was not using bracket notation to get a specific element in the returned collection, resulting in false positive results. Is quantity expected to be an integer or a string?
    $endgroup$
    – guest271314
    5 hours ago












  • $begingroup$
    quantity should be an integer
    $endgroup$
    – dmikester1
    5 hours ago



















0












$begingroup$

Without the HTML it is hard to workout what is wanted.



General point




  • Use const for variables that do not change.

  • Use functions to do common tasks, they simplify the code by reducing its size.

  • Don't test more that you need to. If a is true then you know its not false, you don't then test if its not false.

  • The statement if (!isDynamicRecommendation) { is always true and not needed. (A reminder that at codeReview code must not be example code, we assume this is production code)

  • Use querySelector if you are after just the first instance of an element. It returns null if nothing is found.

  • The code given should be as a function.


  • Names ar poor and too verbose. We read words by their shape especially when they are more than half a dozen characters long. Long names means it's hard to spot errors. This is especially bad in JS as it does not care if you use an undefined variable names.





    • itemTemplateQty and itemTemplateIDQty if you have a single line with these variables repeated 7 times. Can you spot the error in the following? itemTemplateQty, itemTemplateQty, itemTemplateQty, itemTemplateIDQty, itemTemplateIDQty, itemTemplate1DQty, itemTemplateIDQty



      You know its an item. the template part is irrelevant, the only important part is to differentiate the ID (BTW Id should have a lowercase d), qty and qtyId would be better.



      Now spot the same error qty, qty, qty, qtyId, qtyId, qty1d, qtyId



    • itemId??? Have no idea what this actually is?





Example



By using two functions we can greatly reduce the complexity of the code. Removing the overly verbose names also make things easier on the eyes, and helps prevent brain fry.



function getQuantity() {
const query = id => document.querySelector(".itemTemplateQty" + id);
const valid = item => item && !isNaN(item.value) && Number(item.value) > 0.5;
const qty = query(""), qtyId = query("5");
return Math.round(valid(qty) ?
(!valid(qtyId) ? qty.value : 1) :
( valid(qtyId) ? qtyId.value : 1));
}





share|improve this answer









$endgroup$













    Your Answer





    StackExchange.ifUsing("editor", function () {
    return StackExchange.using("mathjaxEditing", function () {
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    });
    });
    }, "mathjax-editing");

    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "196"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });






    dmikester1 is a new contributor. Be nice, and check out our Code of Conduct.










    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f212099%2fjavascript-consolidate-multiple-null-undefined-checks%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2












    $begingroup$

    .getElementsByClassName() returns an HTMLCollection, not a single element. You can use bracket notation [n] to get an element at index n of the collection returned.



    One if statement can be used to evalaute !itemData.isDynamicRecommendation. One if..else..if can be used to evaluate itemTemplateQty[0] && itemTemplateQty[0].value <= 0 or itemTemplateIDQty[0] && itemTemplateIDQty[0].value <= 0.



    To convert the string .value to an integer you can use + operator preceding +itemTemplateQty[0].value.value or alternatively use .valueAsNumber.






    let itemData = 5;
    let isDynamicRecommendation = false;

    let itemTemplateQty = document.getElementsByClassName('itemTemplateQty')[0];
    let itemTemplateIDQty = document.getElementsByClassName('itemTemplateQty' + itemData)[0];
    let quantity = 1;
    if (!isDynamicRecommendation) {
    if (itemTemplateQty && itemTemplateQty.value <= 0) {
    quantity = +itemTemplateQty.value;
    } else if (itemTemplateIDQty && itemTemplateIDQty.value <= 0) {
    quantity = +itemTemplateIDQty.value;
    }
    }

    console.log({quantity});








    share|improve this answer











    $endgroup$













    • $begingroup$
      Wouldn't you want this and the next one to be || not &&? if (itemTemplateQty && itemTemplateQty[0].value <= 0) {
      $endgroup$
      – dmikester1
      5 hours ago












    • $begingroup$
      @dmikester1 Not sure what you mean?
      $endgroup$
      – guest271314
      5 hours ago










    • $begingroup$
      the if and else if should have or's not and's I think
      $endgroup$
      – dmikester1
      5 hours ago










    • $begingroup$
      @dmikester1 if..else could essentially be considered an OR gate. The code could be re-written many different ways. For example, conditional operator could be substituted for if and if..else. One issue with the code at the question was not using bracket notation to get a specific element in the returned collection, resulting in false positive results. Is quantity expected to be an integer or a string?
      $endgroup$
      – guest271314
      5 hours ago












    • $begingroup$
      quantity should be an integer
      $endgroup$
      – dmikester1
      5 hours ago
















    2












    $begingroup$

    .getElementsByClassName() returns an HTMLCollection, not a single element. You can use bracket notation [n] to get an element at index n of the collection returned.



    One if statement can be used to evalaute !itemData.isDynamicRecommendation. One if..else..if can be used to evaluate itemTemplateQty[0] && itemTemplateQty[0].value <= 0 or itemTemplateIDQty[0] && itemTemplateIDQty[0].value <= 0.



    To convert the string .value to an integer you can use + operator preceding +itemTemplateQty[0].value.value or alternatively use .valueAsNumber.






    let itemData = 5;
    let isDynamicRecommendation = false;

    let itemTemplateQty = document.getElementsByClassName('itemTemplateQty')[0];
    let itemTemplateIDQty = document.getElementsByClassName('itemTemplateQty' + itemData)[0];
    let quantity = 1;
    if (!isDynamicRecommendation) {
    if (itemTemplateQty && itemTemplateQty.value <= 0) {
    quantity = +itemTemplateQty.value;
    } else if (itemTemplateIDQty && itemTemplateIDQty.value <= 0) {
    quantity = +itemTemplateIDQty.value;
    }
    }

    console.log({quantity});








    share|improve this answer











    $endgroup$













    • $begingroup$
      Wouldn't you want this and the next one to be || not &&? if (itemTemplateQty && itemTemplateQty[0].value <= 0) {
      $endgroup$
      – dmikester1
      5 hours ago












    • $begingroup$
      @dmikester1 Not sure what you mean?
      $endgroup$
      – guest271314
      5 hours ago










    • $begingroup$
      the if and else if should have or's not and's I think
      $endgroup$
      – dmikester1
      5 hours ago










    • $begingroup$
      @dmikester1 if..else could essentially be considered an OR gate. The code could be re-written many different ways. For example, conditional operator could be substituted for if and if..else. One issue with the code at the question was not using bracket notation to get a specific element in the returned collection, resulting in false positive results. Is quantity expected to be an integer or a string?
      $endgroup$
      – guest271314
      5 hours ago












    • $begingroup$
      quantity should be an integer
      $endgroup$
      – dmikester1
      5 hours ago














    2












    2








    2





    $begingroup$

    .getElementsByClassName() returns an HTMLCollection, not a single element. You can use bracket notation [n] to get an element at index n of the collection returned.



    One if statement can be used to evalaute !itemData.isDynamicRecommendation. One if..else..if can be used to evaluate itemTemplateQty[0] && itemTemplateQty[0].value <= 0 or itemTemplateIDQty[0] && itemTemplateIDQty[0].value <= 0.



    To convert the string .value to an integer you can use + operator preceding +itemTemplateQty[0].value.value or alternatively use .valueAsNumber.






    let itemData = 5;
    let isDynamicRecommendation = false;

    let itemTemplateQty = document.getElementsByClassName('itemTemplateQty')[0];
    let itemTemplateIDQty = document.getElementsByClassName('itemTemplateQty' + itemData)[0];
    let quantity = 1;
    if (!isDynamicRecommendation) {
    if (itemTemplateQty && itemTemplateQty.value <= 0) {
    quantity = +itemTemplateQty.value;
    } else if (itemTemplateIDQty && itemTemplateIDQty.value <= 0) {
    quantity = +itemTemplateIDQty.value;
    }
    }

    console.log({quantity});








    share|improve this answer











    $endgroup$



    .getElementsByClassName() returns an HTMLCollection, not a single element. You can use bracket notation [n] to get an element at index n of the collection returned.



    One if statement can be used to evalaute !itemData.isDynamicRecommendation. One if..else..if can be used to evaluate itemTemplateQty[0] && itemTemplateQty[0].value <= 0 or itemTemplateIDQty[0] && itemTemplateIDQty[0].value <= 0.



    To convert the string .value to an integer you can use + operator preceding +itemTemplateQty[0].value.value or alternatively use .valueAsNumber.






    let itemData = 5;
    let isDynamicRecommendation = false;

    let itemTemplateQty = document.getElementsByClassName('itemTemplateQty')[0];
    let itemTemplateIDQty = document.getElementsByClassName('itemTemplateQty' + itemData)[0];
    let quantity = 1;
    if (!isDynamicRecommendation) {
    if (itemTemplateQty && itemTemplateQty.value <= 0) {
    quantity = +itemTemplateQty.value;
    } else if (itemTemplateIDQty && itemTemplateIDQty.value <= 0) {
    quantity = +itemTemplateIDQty.value;
    }
    }

    console.log({quantity});








    let itemData = 5;
    let isDynamicRecommendation = false;

    let itemTemplateQty = document.getElementsByClassName('itemTemplateQty')[0];
    let itemTemplateIDQty = document.getElementsByClassName('itemTemplateQty' + itemData)[0];
    let quantity = 1;
    if (!isDynamicRecommendation) {
    if (itemTemplateQty && itemTemplateQty.value <= 0) {
    quantity = +itemTemplateQty.value;
    } else if (itemTemplateIDQty && itemTemplateIDQty.value <= 0) {
    quantity = +itemTemplateIDQty.value;
    }
    }

    console.log({quantity});





    let itemData = 5;
    let isDynamicRecommendation = false;

    let itemTemplateQty = document.getElementsByClassName('itemTemplateQty')[0];
    let itemTemplateIDQty = document.getElementsByClassName('itemTemplateQty' + itemData)[0];
    let quantity = 1;
    if (!isDynamicRecommendation) {
    if (itemTemplateQty && itemTemplateQty.value <= 0) {
    quantity = +itemTemplateQty.value;
    } else if (itemTemplateIDQty && itemTemplateIDQty.value <= 0) {
    quantity = +itemTemplateIDQty.value;
    }
    }

    console.log({quantity});






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited 5 hours ago

























    answered 5 hours ago









    guest271314guest271314

    38018




    38018












    • $begingroup$
      Wouldn't you want this and the next one to be || not &&? if (itemTemplateQty && itemTemplateQty[0].value <= 0) {
      $endgroup$
      – dmikester1
      5 hours ago












    • $begingroup$
      @dmikester1 Not sure what you mean?
      $endgroup$
      – guest271314
      5 hours ago










    • $begingroup$
      the if and else if should have or's not and's I think
      $endgroup$
      – dmikester1
      5 hours ago










    • $begingroup$
      @dmikester1 if..else could essentially be considered an OR gate. The code could be re-written many different ways. For example, conditional operator could be substituted for if and if..else. One issue with the code at the question was not using bracket notation to get a specific element in the returned collection, resulting in false positive results. Is quantity expected to be an integer or a string?
      $endgroup$
      – guest271314
      5 hours ago












    • $begingroup$
      quantity should be an integer
      $endgroup$
      – dmikester1
      5 hours ago


















    • $begingroup$
      Wouldn't you want this and the next one to be || not &&? if (itemTemplateQty && itemTemplateQty[0].value <= 0) {
      $endgroup$
      – dmikester1
      5 hours ago












    • $begingroup$
      @dmikester1 Not sure what you mean?
      $endgroup$
      – guest271314
      5 hours ago










    • $begingroup$
      the if and else if should have or's not and's I think
      $endgroup$
      – dmikester1
      5 hours ago










    • $begingroup$
      @dmikester1 if..else could essentially be considered an OR gate. The code could be re-written many different ways. For example, conditional operator could be substituted for if and if..else. One issue with the code at the question was not using bracket notation to get a specific element in the returned collection, resulting in false positive results. Is quantity expected to be an integer or a string?
      $endgroup$
      – guest271314
      5 hours ago












    • $begingroup$
      quantity should be an integer
      $endgroup$
      – dmikester1
      5 hours ago
















    $begingroup$
    Wouldn't you want this and the next one to be || not &&? if (itemTemplateQty && itemTemplateQty[0].value <= 0) {
    $endgroup$
    – dmikester1
    5 hours ago






    $begingroup$
    Wouldn't you want this and the next one to be || not &&? if (itemTemplateQty && itemTemplateQty[0].value <= 0) {
    $endgroup$
    – dmikester1
    5 hours ago














    $begingroup$
    @dmikester1 Not sure what you mean?
    $endgroup$
    – guest271314
    5 hours ago




    $begingroup$
    @dmikester1 Not sure what you mean?
    $endgroup$
    – guest271314
    5 hours ago












    $begingroup$
    the if and else if should have or's not and's I think
    $endgroup$
    – dmikester1
    5 hours ago




    $begingroup$
    the if and else if should have or's not and's I think
    $endgroup$
    – dmikester1
    5 hours ago












    $begingroup$
    @dmikester1 if..else could essentially be considered an OR gate. The code could be re-written many different ways. For example, conditional operator could be substituted for if and if..else. One issue with the code at the question was not using bracket notation to get a specific element in the returned collection, resulting in false positive results. Is quantity expected to be an integer or a string?
    $endgroup$
    – guest271314
    5 hours ago






    $begingroup$
    @dmikester1 if..else could essentially be considered an OR gate. The code could be re-written many different ways. For example, conditional operator could be substituted for if and if..else. One issue with the code at the question was not using bracket notation to get a specific element in the returned collection, resulting in false positive results. Is quantity expected to be an integer or a string?
    $endgroup$
    – guest271314
    5 hours ago














    $begingroup$
    quantity should be an integer
    $endgroup$
    – dmikester1
    5 hours ago




    $begingroup$
    quantity should be an integer
    $endgroup$
    – dmikester1
    5 hours ago













    0












    $begingroup$

    Without the HTML it is hard to workout what is wanted.



    General point




    • Use const for variables that do not change.

    • Use functions to do common tasks, they simplify the code by reducing its size.

    • Don't test more that you need to. If a is true then you know its not false, you don't then test if its not false.

    • The statement if (!isDynamicRecommendation) { is always true and not needed. (A reminder that at codeReview code must not be example code, we assume this is production code)

    • Use querySelector if you are after just the first instance of an element. It returns null if nothing is found.

    • The code given should be as a function.


    • Names ar poor and too verbose. We read words by their shape especially when they are more than half a dozen characters long. Long names means it's hard to spot errors. This is especially bad in JS as it does not care if you use an undefined variable names.





      • itemTemplateQty and itemTemplateIDQty if you have a single line with these variables repeated 7 times. Can you spot the error in the following? itemTemplateQty, itemTemplateQty, itemTemplateQty, itemTemplateIDQty, itemTemplateIDQty, itemTemplate1DQty, itemTemplateIDQty



        You know its an item. the template part is irrelevant, the only important part is to differentiate the ID (BTW Id should have a lowercase d), qty and qtyId would be better.



        Now spot the same error qty, qty, qty, qtyId, qtyId, qty1d, qtyId



      • itemId??? Have no idea what this actually is?





    Example



    By using two functions we can greatly reduce the complexity of the code. Removing the overly verbose names also make things easier on the eyes, and helps prevent brain fry.



    function getQuantity() {
    const query = id => document.querySelector(".itemTemplateQty" + id);
    const valid = item => item && !isNaN(item.value) && Number(item.value) > 0.5;
    const qty = query(""), qtyId = query("5");
    return Math.round(valid(qty) ?
    (!valid(qtyId) ? qty.value : 1) :
    ( valid(qtyId) ? qtyId.value : 1));
    }





    share|improve this answer









    $endgroup$


















      0












      $begingroup$

      Without the HTML it is hard to workout what is wanted.



      General point




      • Use const for variables that do not change.

      • Use functions to do common tasks, they simplify the code by reducing its size.

      • Don't test more that you need to. If a is true then you know its not false, you don't then test if its not false.

      • The statement if (!isDynamicRecommendation) { is always true and not needed. (A reminder that at codeReview code must not be example code, we assume this is production code)

      • Use querySelector if you are after just the first instance of an element. It returns null if nothing is found.

      • The code given should be as a function.


      • Names ar poor and too verbose. We read words by their shape especially when they are more than half a dozen characters long. Long names means it's hard to spot errors. This is especially bad in JS as it does not care if you use an undefined variable names.





        • itemTemplateQty and itemTemplateIDQty if you have a single line with these variables repeated 7 times. Can you spot the error in the following? itemTemplateQty, itemTemplateQty, itemTemplateQty, itemTemplateIDQty, itemTemplateIDQty, itemTemplate1DQty, itemTemplateIDQty



          You know its an item. the template part is irrelevant, the only important part is to differentiate the ID (BTW Id should have a lowercase d), qty and qtyId would be better.



          Now spot the same error qty, qty, qty, qtyId, qtyId, qty1d, qtyId



        • itemId??? Have no idea what this actually is?





      Example



      By using two functions we can greatly reduce the complexity of the code. Removing the overly verbose names also make things easier on the eyes, and helps prevent brain fry.



      function getQuantity() {
      const query = id => document.querySelector(".itemTemplateQty" + id);
      const valid = item => item && !isNaN(item.value) && Number(item.value) > 0.5;
      const qty = query(""), qtyId = query("5");
      return Math.round(valid(qty) ?
      (!valid(qtyId) ? qty.value : 1) :
      ( valid(qtyId) ? qtyId.value : 1));
      }





      share|improve this answer









      $endgroup$
















        0












        0








        0





        $begingroup$

        Without the HTML it is hard to workout what is wanted.



        General point




        • Use const for variables that do not change.

        • Use functions to do common tasks, they simplify the code by reducing its size.

        • Don't test more that you need to. If a is true then you know its not false, you don't then test if its not false.

        • The statement if (!isDynamicRecommendation) { is always true and not needed. (A reminder that at codeReview code must not be example code, we assume this is production code)

        • Use querySelector if you are after just the first instance of an element. It returns null if nothing is found.

        • The code given should be as a function.


        • Names ar poor and too verbose. We read words by their shape especially when they are more than half a dozen characters long. Long names means it's hard to spot errors. This is especially bad in JS as it does not care if you use an undefined variable names.





          • itemTemplateQty and itemTemplateIDQty if you have a single line with these variables repeated 7 times. Can you spot the error in the following? itemTemplateQty, itemTemplateQty, itemTemplateQty, itemTemplateIDQty, itemTemplateIDQty, itemTemplate1DQty, itemTemplateIDQty



            You know its an item. the template part is irrelevant, the only important part is to differentiate the ID (BTW Id should have a lowercase d), qty and qtyId would be better.



            Now spot the same error qty, qty, qty, qtyId, qtyId, qty1d, qtyId



          • itemId??? Have no idea what this actually is?





        Example



        By using two functions we can greatly reduce the complexity of the code. Removing the overly verbose names also make things easier on the eyes, and helps prevent brain fry.



        function getQuantity() {
        const query = id => document.querySelector(".itemTemplateQty" + id);
        const valid = item => item && !isNaN(item.value) && Number(item.value) > 0.5;
        const qty = query(""), qtyId = query("5");
        return Math.round(valid(qty) ?
        (!valid(qtyId) ? qty.value : 1) :
        ( valid(qtyId) ? qtyId.value : 1));
        }





        share|improve this answer









        $endgroup$



        Without the HTML it is hard to workout what is wanted.



        General point




        • Use const for variables that do not change.

        • Use functions to do common tasks, they simplify the code by reducing its size.

        • Don't test more that you need to. If a is true then you know its not false, you don't then test if its not false.

        • The statement if (!isDynamicRecommendation) { is always true and not needed. (A reminder that at codeReview code must not be example code, we assume this is production code)

        • Use querySelector if you are after just the first instance of an element. It returns null if nothing is found.

        • The code given should be as a function.


        • Names ar poor and too verbose. We read words by their shape especially when they are more than half a dozen characters long. Long names means it's hard to spot errors. This is especially bad in JS as it does not care if you use an undefined variable names.





          • itemTemplateQty and itemTemplateIDQty if you have a single line with these variables repeated 7 times. Can you spot the error in the following? itemTemplateQty, itemTemplateQty, itemTemplateQty, itemTemplateIDQty, itemTemplateIDQty, itemTemplate1DQty, itemTemplateIDQty



            You know its an item. the template part is irrelevant, the only important part is to differentiate the ID (BTW Id should have a lowercase d), qty and qtyId would be better.



            Now spot the same error qty, qty, qty, qtyId, qtyId, qty1d, qtyId



          • itemId??? Have no idea what this actually is?





        Example



        By using two functions we can greatly reduce the complexity of the code. Removing the overly verbose names also make things easier on the eyes, and helps prevent brain fry.



        function getQuantity() {
        const query = id => document.querySelector(".itemTemplateQty" + id);
        const valid = item => item && !isNaN(item.value) && Number(item.value) > 0.5;
        const qty = query(""), qtyId = query("5");
        return Math.round(valid(qty) ?
        (!valid(qtyId) ? qty.value : 1) :
        ( valid(qtyId) ? qtyId.value : 1));
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 2 hours ago









        Blindman67Blindman67

        7,3811521




        7,3811521






















            dmikester1 is a new contributor. Be nice, and check out our Code of Conduct.










            draft saved

            draft discarded


















            dmikester1 is a new contributor. Be nice, and check out our Code of Conduct.













            dmikester1 is a new contributor. Be nice, and check out our Code of Conduct.












            dmikester1 is a new contributor. Be nice, and check out our Code of Conduct.
















            Thanks for contributing an answer to Code Review Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f212099%2fjavascript-consolidate-multiple-null-undefined-checks%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            How to reconfigure Docker Trusted Registry 2.x.x to use CEPH FS mount instead of NFS and other traditional...

            is 'sed' thread safe

            How to make a Squid Proxy server?