0

retrievedID is a string returned by window localStorage property in my code as:

$(function () {
            var retrievedID = localStorage.getItem('navitemID');
            if ($(retrievedID).val() !== '') {
                $('.navbar-nav li').removeClass('active');
                var myID = "#" + retrievedID;
                $(myID).addClass('active');
            }
        });

if statement in this code isn't working as expected because despite having an empty string inside recievedID variable, code is still entering inside the condition and executing.

Can someone please help. Thanks in advance.

10
  • What exactly is the value of $(retrievedID).val()? Anything other than an empty string will satisfy the condition. Commented May 23, 2022 at 8:25
  • So what is console.log($(retrievedID).val()); is pointing out? Commented May 23, 2022 at 8:25
  • @Thallius: $(retrievedID).val() in console is coming as undefined Commented May 23, 2022 at 8:30
  • 1
    undefined !== '' will evaluate to true Commented May 23, 2022 at 8:41
  • 1
    @phuzi: if condition in Mandeep's solution is always coming as true for all values and hence code inside the if condition is never getting to execute. Commented May 23, 2022 at 9:37

1 Answer 1

1

You can also check undefined type, add to if condition

$(function () {
            var retrievedID = localStorage.getItem('navitemID');
            if ($(retrievedID).val() !== '' ||  typeof $(retrievedID).val() !== "undefined" ) {
                $('.navbar-nav li').removeClass('active');
                var myID = "#" + retrievedID;
                $(myID).addClass('active');
            }
        });
Sign up to request clarification or add additional context in comments.

3 Comments

Maybe you should change || to &&
You should leave out the quotes around undefined, for more information developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
@joronimo typeof returns a string which is why the test is against "undefined" and not undefined

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.