When using canvas, in order to judge whether the getContext method in canvas exists, the commonly used if judgment condition is used to prevent the code from continuing execution:

let canvas = document.querySelector('#canvas')
if(! canvas.getContext) {return;
}
Copy the code

But the code doesn’t seem to be working properly, and the browser console throws an error:

Uncaught SyntaxError: Illegal return statement Uncaught SyntaxError: Illegal return statementCopy the code

Stackoverflow poses the same question.

The answer gives the reason: return only makes sense inside a function.

That is, a return can only be used inside a function:

function myFun() {
  return '... ';
}
Copy the code

Since return can only be used inside a function, I thought it would be ok to terminate code execution in another way when getContext does not exist.

So when can you terminate the code and continue? When the program throws an error, it seems to terminate the code and continue execution:

throw new Error(a);Copy the code

Finally, I changed the initial return to throw New Error and threw the corresponding message:

let canvas = document.querySelector('#canvas')
if(! canvas.getContext) {throw new Error('Canvas getContext method not found! ');
}
Copy the code