Bada
Bada's Coding

Bada's Coding

Difference between 'location.assign' and 'location.replace'

Bada's photo
Bada
·Oct 7, 2022·

1 min read

Introduction

In terms of 'history stack', they are different.

Let me define '[]' sign first. Be careful the sign is arbitrarily made by me, so it can't be applied to other situations.

If I moved from page A to page B, let me describe the history stack as [A, B].

'location.assign'

It is similar to 'history.pushState'.

|example|

The history stack is [A, B, C].

If I am in A and go to D, the history stack becomes [A, D].

'location.replace'

It is similar to 'history.replaceState'.

|example|

The history stack is [A, B, C].

If I am in A and go to D, the history stack becomes [D, B, C].

Example

<body>
  <button onclick="useAssign()">assign</button>
  <button onclick="useReplace()">replace</button>
</body>
<script>
  const url = 'https://developer.mozilla.org';
  function useAssign() {
    location.assign(url);
  }
  function useReplace() {
    location.replace(url);
  }
</script>
 
Share this