I don't understand the logic in the following js-code. When will it be triggered? When does the condition apply, etc.?
if (window.history.replaceState) {
window.history.replaceState(null, null, window.location.href);
}
I do understand, that replaceState() actually replaces the URL and hence does not add another page to the history but when and why will it be triggered? What does if (window.history.replaceState) do?
What does the
if (window.history.replaceState)do:It will evaluate the inner part of the if-condition (the parenthesis) and check if the value that it returns is
true. If this actually is the case, then it will execute the code block inside thecurly-brace: {}.In JavaScript, there is no type-safety. The type of a variable is always inferred by the value it holds.
windowis an object and so ishistory. History is a property of thewindow object.replaceStaterefers to a function that is defined on the history object (again, as a property). In the if-statement context, it means:If it does not exists, it will return return
undefined.Undefinedandnullare both being evaluated asfalsei.e. typecast ofundefinedornullto aboolean. This is casting is referred to astype coercion.If it is defined, however, then it will return
trueand theif-conditionapplies. In this case, history will be an object and therefore it will evaluate astrue. You can read more about type coercion if you are interested.Should be easy to understand: https://www.freecodecamp.org/news/js-type-coercion-explained-27ba3d9a2839/