Saturday 22 December 2018

JavaScript: Explain about void operator

void operator evaluates an expression and return undefined.

Syntax
void expression
void (expression)

Since ‘void expression’ return undefined, you can use this while checking for undefined variables.

HelloWorld.js
var x;
var y = 10;

if(x === (void 0)){
  console.log("x is undefined");
}else{
  console.log("Value of x is : " +  x);
}

if(y === (void 0)){
  console.log("y is undefined");
}else{
  console.log("Value of y is : " + y);
}

Output
x is undefined
Value of y is : 10

Example 1: Create hyper link that does nothing when user clicks on it
<a href="javascript:void(0)">Click here to do nothing</a>

When the user clicks on hyper link, void(0) returns undefined, which has no effect in JavaScript.

Example 2: Submit the form when user clicks on hyper link
<a href="javascript:void(document.form.submit())">Submit the form</a>



Previous                                                 Next                                                 Home

No comments:

Post a Comment