❑ When we click on a link, if we do not want the default behaviour of the browser to load a new page or refresh the same page.
❒ Instead, the browser performs the JavaScript attached to that link.
➋ Let's break it down
✛ javascript:
This is referred to as a Pseudo URL
✛ void
This is a JavaScript Operator
✛ (0)
This is a JavaScript Expression
➋.➊ javascript:
❑ If "javascript:" is at the beginning of the value of "href" on <a> tag, it executes the JS code that follows the ":"
❒ The return value of the executed script "if there is one", becomes the content of a new document which is displayed in the browser
➋.➋ void
⬒ When an input is passed to "void", it evaluates that first. And, in all cases returns "undefined".
⬔ In other words, it suppresses the output of an expression.
⬓ It is useful when we want an expression to be evaluated without any side effects.
➋.➌ javascript:void(0)
⬒ The JavaScript code that will be executed after clicking the link is "void(0)"
⬔ "void" will first evaluate (0). (0) returns 0, but "void" suppresses it and returns "undefined"
⬓ Seeing "href" as "undefined", browser doesn't do anything
➌ Alternative
❑ When user disables "JavaScript to be executed in a browser", the above trick won't work.
❒ The below technique is the alternative and safest option.
<a href="#" onclick="return false;">
➍ Other most used Pseudo URLs
Like "javascript:", we can use below in "href"
✪ mailto:
To send email to an Email Address
✪ tel:
To call a telephone number
⚠️ Warning ⚠️
❑ javascript:void(0) violates Content Security Policy on CSP-enabled HTTPS
❒ Content Security Policy (CSP) is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross-Site Scripting (XSS) and data injection attacks
⚠️ Warning ⚠️
❑ Anchor elements are often abused as fake buttons by setting their href to # or javascript:void(0) to prevent the page from refreshing, then listening for their click events.
❑ The binary '+' operator is generally a "Number Addition" operator.
❒ When one of the operand is string, '+' rather acts like a "String Concatenation" operator. The other operand if not string is converted to string first.
➋ '-' operator operates on numbers only
❑ The binary "-" operator is known as a "Number Subtraction" operator.
❒ If any of the operand is not number, that is first converted to a number before evaluating the expression.