Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I exit from a javascript function? [duplicate]

I have the following:

function refreshGrid(entity) {     var store = window.localStorage;     var partitionKey;     ...     ... 

I would like to exit from this function if an "if" condition is met. How can I exit? Can I just say break, exit or return?

like image 731
Samantha J T Star Avatar asked May 05 '12 05:05

Samantha J T Star


People also ask

How do you exit a function in javascript?

You can do it using the return keyword. Whenever JavaScript sees the return keyword, it immediately exits the function and any variable (or value) you pass after return will be returned back as a result.

How do you stop a return in javascript?

Using break to exit a function in javascript Using break to exit from functions in javascript is a less traditional way compared to using return. Break is mostly used to exit from loops but can also be used to exit from functions by using labels within the function.

Does return terminate a function javascript?

The return statement stops the execution of a function and returns a value.


2 Answers

if ( condition ) {     return; } 

The return exits the function returning undefined.

The exit statement doesn't exist in javascript.

The break statement allows you to exit a loop, not a function. For example:

var i = 0; while ( i < 10 ) {     i++;     if ( i === 5 ) {         break;     } } 

This also works with the for and the switch loops.

like image 184
Florian Margaine Avatar answered Oct 20 '22 21:10

Florian Margaine


Use return statement anywhere you want to exit from function.

if(somecondtion)    return;  if(somecondtion)    return false; 
like image 22
Adil Avatar answered Oct 20 '22 21:10

Adil