What does “[removed]void(0)” mean?

前端 未结 14 1370
说谎
说谎 2020-11-21 15:23
login

I\'ve seen such hrefs many times, but I don\'t know what exactly

相关标签:
14条回答
  • 2020-11-21 16:17

    To understand this concept one should first understand the void operator in JavaScript.

    The syntax for the void operator is: void «expr» which evaluates expr and returns undefined.

    If you implement void as a function, it looks as follows:

    function myVoid(expr) {
        return undefined;
    }
    

    This void operator has one important usage that is - discarding the result of an expression.

    In some situations, it is important to return undefined as opposed to the result of an expression. Then void can be used to discard that result. One such situation involves javascript: URLs, which should be avoided for links, but are useful for bookmarklets. When you visit one of those URLs, many browsers replace the current document with the result of evaluating the URLs “content”, but only if the result isn’t undefined. Hence, if you want to open a new window without changing the currently displayed content, you can do the following:

    javascript:void window.open("http://example.com/")
    
    0 讨论(0)
  • 2020-11-21 16:23

    javascript: URLs aside; this is where void can be used to write shorter code:

    var error1 = false,
        error2 = false,
        error3 = false;
    
    function error1() {
    
        error1 = true;
    }
    
    function myFunction() {
    
        // You can easily return and call a function at once, if you don't care about myFunction's return value
        if (!someCondition1)
            return error1();
    
        // What if you want to set a value first?
        if (!someCondition2) {
            error2 = true;
            return
        }
    
        // Shortest way to return and set a value at once
        if (!someCondition3)
            return void(error3 = true);
    
        // More code goes here
    }
    
    
    0 讨论(0)
提交回复
热议问题