Jumps in JavaScript

The fundamentals of a programming language involves declaring identities(variables, functions), statement blocks(treating a lot of code as a single block), loops repetitively executing a piece of code and one important aspect of just jumping around in the code. The idea of jumping around in code becomes prevalent if you have thousands of line of code and want to execute just a small piece of it.

For doing this JavaScript uses Jump Statements
• break – Makes interpreter to jump to end of loop or next statement outside loop

• continue – Whenever interpreter sees this, it will just skip rest of loop and would restart executing code from top of loop itself.

• return – If interpreter sees this then it will get value being evaluated by code and would return it to last function call. (Seems tricky but don’t worry I’ll explain this properly for you down below – return Jump Statement JavaScript)

• throw – This statement is most often used for debugging code, for just seeing a message in console.

• try/catch/finally – If interpreter sees this then it will firstly execute code inside try block if it returned something then interpreter would go back to calling function, if nothing is returned then interpreter will execute code inside catch. If catch returned something then again interpreter will go back to calling function, if nothing’s returned then interpreter would execute code inside finally. (Seems very complicated don’t worry I got you covered jump to complete explanation – try/catch/finally JavaScript Explaination)

Labelled Statements in JavaScript?

Most of JavaScript’s Jump statements(all listed above) move interpreter from one point to another in code without going to inbetween code lines. For doing this interpreter need to know where it will be going next, for this JavaScript uses Labeled Statements.

A Labeled Statement consists of two components – identifier, statement. Identifier being some unique name, statement being a code block or body of loop mostly. Common Syntax for Labeled Statements in JavaScript – identifier : statement

Below is a code example of JavaScript’s Labelled Statements –

importantloop : while(token != null){
	/*   Some Code */
	continue importantloop;
	/*   Some code */
}

In the above example – When interpreter executes line 1 it would treat whole while loop’s body as a single variable named importantloop, after executing code on line 2 when interpreter encounters line 3, it would straight away will jump back to top of loop meaning line 1 and again start to execute it.

JavaScript’s Labelled Statements are quite useful for jumping around code lines.

break Statement in JavaScript

JavaScript’s break statement is an instruction to interpreter to just break out of loop/switch statement and move to next code line.

If your not aware of JavaScript’s Loops then see this article which I put together a couple of days ago – JavaScript Loops.

Mostly for breaking out of loops having just break statement is enough, but if you need to break out of a labelled block of code then using break labelname; is a far better choice. Reason being that whenever JavaScript interpreter sees break statement it would just get out of nearest enclosing loop but if there’s nested loops(loop within loop) then using labelled break statement is better choice for specifying which loop to exit.

In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.
Using break statement inside any code block except for loop/switch statement will throw SyntaxError: Illegal break Statement.

Below is a code example explaining How to use break statement within nested loops?

var matrix = getData();
var sum = 0; success = false;

compute_sum : if (matrix) {
	for (var i = 0; i < matrix.length; i++) {
		var row = matrix[i];
		if (!row) break compute_sum; //Jump to compute_sum

		for (var j = 0; j < row.length; j++) {
			var cell = row[j];
			if (isNaN(cell)) break compute_sum; //Jump to compute_sum
			sum += cell;
		}
	}
	success = true;
}

Note – If you use break Jump Statement inside a function then JavaScript will throw SyntaxError: Illegal break Statement.

continue Statement in JavaScript

JavaScript’s continue statement is a sort of escaping mechanism as whenever interpreter sees it inside a loop, it will stop executing statements rather will jump back to start of loop and start from there again.

Like break statement, continue as well can be used alone or with a labelname.
continue; or continue labelname; both are right statements in JavaScript.

While JavaScript’s break statement is just an exit out of loop, what continue statement do is different for each of JavaScript’s loop.

• If continue statement is used inside a while loop then interpreter seeing continue will stop executing further statements, will go back to testing expression at start of loop – Evaluate testing expression and then start executing statements inside while loop again.

• For continue statement inside do while loop, interpreter will skip over all of statements after it – Jump to end of loop evaluate while(testing expression) and then start expecting loop’s statements from top if testing expression evaluates to true only.

• Whenever JavaScript sees continue statement inside for loop, interpreter would jump excape executing statements after it rather would evaluate increment expression first then test expression(need to comes true) and then start executing loop statements again.

• JavaScript’s for in loop is kind of unique in the sense that it’s mostly used for dealing with JavaScript Arrays(mostly getting values out of array). Having a continue statement inside for in loop would tell interpreter to skip over one index of array and move onto next index value.

If you don’t understand this, then its totally fine – No need to worry as your experience grows your understanding of different aspects of JavaScript Loops, Arrays will grow.
DO NOT WORRY!! KEEP ON LEARNING
Moreover if your not aware of what are different types of loops in JavaScript or different components out of which these are made. Then see this article about JavaScript’s Loops.

Difference between JavaScript’s for loop and while loop?

Moreover for any piece of code, it could be written a for loop then it can be written as well as a while loop(For most of cases). But if there’s a continue statement withing loop, then be careful as in case of while loop directly testing expression is executed whilst in for loop first increment expression – then testing expression is computed. That’s why there may come differences.

Below is a code example of How to use continue Statement in JavaScript?

for (var i = 0; i < a.length; i++) {
	if (!a[i]) continue;
	total += a[i];
}

return JavaScript Statement

return statement is only legal to be written inside a function’s code block, if it appears anywhere else in code then JavaScript’s interpreter would throw a TypeError. Syntax for JavaScript’s return statement is return expression; or return;

• For return expression; JavaScript’s interpreter would return expression’s computed value to line of code from where function is called.

• return; Doesn’t return any value to it’s caller location.

Code examples for JavaScript’s return statement

function add(a, b){
	return a + b;
}
add(10, 5);

// For this JavaScript's interpreter will return 15 to line of code
add(10, 5)


function not_exist(x){
	if(!o){
		return;  // Just exist out of function is x doesn't exist
	}
	else{
		console.log("Hi object o does exist");
	}
}

throw JavaScript Statement

JavaScript’s throw statement is used for showing some error to users of program or even it’s used by programmers to actually debug the code. It’s very helpful for both users/developers. Mostly this is used alongwith try/catch/finally statements.

Syntax for JavaScript’s throw statement – throw expression;

Most this throw statement either returns an error code or some message.

Below is a code example showing How throw statement can be used in JavaScript?

function factorial(x) {
	// If input value x is invalid, throw an error
	if (x < 0) throw new Error("x must not be negative");
	// If it's not negative then execute following statements
	for (var i = 0; x > 1; i *= x, x--);
	return i;
}

JavaScript have a whole class called Error, by calling which you could construct different types of error messages.
Read more about Error Class, here at JavaScript’s Official Documentation.
Some common examples of throw Errors are –
• Eval Error
• Reference Error
• Syntax Error
• Internal Error

Conclusion

Jumps in JavaScript code are quite important as these help to escape out certain piece of code while executing only required code statements. If in case you’ve thousands of lines of JavaScript code then simply executing unnecessary lines of code would consume a lot of time. So it’s quite crucial to have jumping statements to refractor out not needed code.

Note that JavaScript doesn’t have goto statement like some other programming languages( Example – C Sharp ). Instead having a Jump Statement(continue or break) with a label can mimic same behaviour as of goto statement.

Moreover if in case your learning JavaScript Programming Language then I’ve put together number of articles about it here on this website. If your interested then you can check those articles here – JavaScript Computer Science Hub.

Gagan

Hi, there I'm founder of ComputerScienceHub(Started this to bring useful Computer Science information just at one place). Personally I've been doing JavaScript, Python development since 2015(Been long) - Worked upon couple of Web Development Projects, Did some Data Science stuff using Python. Nowadays primarily I work as Freelance JavaScript Developer(Web Developer) and on side-by-side managing team of Computer Science specialists at ComputerScienceHub.io

One thought on “Jumps in JavaScript

  1. Pingback: Statements in JavaScript - Computer Science Hub

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts