void 0 or undefined

82 阅读1分钟

void 0 or undefined

  • in old browsers undefined's value can be rewrite,so we use void 0
  • in new browsers undefined can't change it's value, so just the same.

void operator

the void operator evaluates the given expression and returns undefined

uses:

  • iife

    void function () {
      console.log("Executed!");
    }();
    
  • JavaScript URIs

    <a href="javascript:void(0);">
      Click here to do nothing
    </a>
    ​
    <a href="javascript:void(document.body.style.backgroundColor='green');">
      Click here for green background
    </a>
    
  • Non-leaking Array Functions

    button.onclick = () => void doSomething();
    

refrense

void-mdn

javascript-undefined-vs-void-0