1

I'm new to javascript and programming and I am trying to understand this piece of code to implement in my project

function url_redirect(url){
    var X = setTimeout(function(){
        window.location.replace(url);
        return true;
    },300);

    if( window.location = url ){
        clearTimeout(X);
        return true;
    } else {
        if( window.location.href = url ){
            clearTimeout(X);
            return true;
        }else{
            clearTimeout(X);
            window.location.replace(url);
            return true;
        }
    }
    return false;
};

Source - https://stackoverflow.com/a/53706698. I can't figure out the logic in this. Why is a single '=' used in a if statement? What does if(window.location = url) mean?

Kreo021
  • 165
  • 1
  • 1
  • 6
  • A single = means assignment of a value to a variable. When you assign a value to a variable it returns the value itself. so if(window.location=url) will return first assign the location to url.If url is not null it'll go inside the if statement since assignment returns the value it was assigned. But I'm not sure if its right – Vikrant Sep 28 '20 at 19:15
  • 2
    @Vikrant In general, yes, but in this particular case `if (window.location = url)` redirects immediately. There should be comparison operators instead of the assignments in the code, i.e. it's not a "_working solution_". – Teemu Sep 28 '20 at 19:18
  • What are you really trying to do here/ problem you are attempting to solve? That might yield an answer that you might find of more use to you/give you better information. – Mark Schultheiss Sep 28 '20 at 19:42

1 Answers1

0

Check conditions first, next execute (if needed) change:

function url_redirect(url){    
    if( window.location.href == url ){
       return false;
    }

    // if you need wait
    setTimeout(function(){
        window.location.replace(url);
    }, 300);

    // if you don't need to wait
    window.location.replace(url);

    return true;
};

I am not sure about the expectations of return - when true when false, assume that if the URL changed -> true otherwise -> false

bensiu
  • 24,660
  • 56
  • 77
  • 117
  • Can you explain the meaning of if( window.location = url ). Why is a single = used in a if statement – Kreo021 Sep 28 '20 at 19:16
  • Sorry - it is your code - I missed those wrong comparisons - it should be `==` or even `===` instead `=` – bensiu Sep 28 '20 at 19:18
  • It's not my code actually. Got it from another post. Source - https://stackoverflow.com/a/53706698 – Kreo021 Sep 28 '20 at 19:20