Difference between break and return?

Y

Yansky

Hi, I've looked through the tutorial on w3cschools.com, but I'm still
uncertain as to the difference between using break and using return.

If I have a simple "for" loop that I want to stop if a condition is
met, should I use break or return to stop the loop?

e.g. is something like this ok? Would using return do the same thing?

var dow = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',
'Saturday', 'Sunday'];

var d = 'Wednesday';

for(var i = 0; i < dow.length; i++){

if (dow == d){

var abc = dow;

break;

}

}
 
T

Thomas 'PointedEars' Lahn

dn said:
simply put,

break exits a loop,
return exits a function.

That is too much simplified.

For the `break' statement may also occur outside of loops (i.e. `for',
for..in, do..while, and while..do statements followed by an execution
block), in the `switch' statement where it prevents execution from
considering the following `case' statements or the following `default'
statement within that `switch' statement.

Also, `break' does not return a value. `return', which exits the current
local execution context (the current function), does (if not explicitly
stated, it returns `undefined' from that context implicitly).


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,143
Latest member
SterlingLa
Top