Reputation: 31
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?
Upvotes: 0
Views: 447
Reputation: 4062
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 the curly-brace: {}
.
In JavaScript, there is no type-safety. The type of a variable is always inferred by the value it holds.
window
is an object and so is history
. History is a property of the window object
.
replaceState
refers to a function that is defined on the history object (again, as a property). In the if-statement context, it means:
"Please check the history property on object window and see if the replaceState function exists".
If it does not exists, it will return return undefined
. Undefined
and null
are both being evaluated as false
i.e. typecast of undefined
or null
to a boolean
. This is casting is referred to as type coercion
.
If it is defined, however, then it will return true
and the if-condition
applies. In this case, history will be an object and therefore it will evaluate as true
. 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/
Upvotes: 0