Return Statements And Chaining

When writing concise code it is important to remember the simple return statement. The return statement is a staple in many languages; it is important to understand how it works.


How It Works

A return statement simply returns whatever data you want. The most important thing to understand is that there are some specifics in each language. But, you can pretend that every method or function has an implicit return unless explicitly stated regardless of language. Here’s an example in JavaScript.

If you run both functions in the browser, you’ll notice they both return something. The first function returns undefined. The second function returns 3. This is because in JavaScript a function returns undefined implicitly unless a return statement is explicitly defined such as in the second function. Now, you might think this only applies to JavaScript, but it applies to languages like Java as well. When writing methods for Java classes, you have to set the return type to void or another type. In Java, void is the implicit return; all other return types require an explicit return. Understanding this concept allows us to better understand other programming languages. For example, in many functional languages, you have to explicitly return something. Also, return statements can be used for other practical things, such as chaining. Chaining is when you chain method calls together. This is an important concept to understand when it comes to creating robust code. Here’s an example.

As you can see, we can chain the upgradeValue method together, because we’re returning “this”. At that moment, it returns the newly created object; by returning the object, we have access to the functions we defined like upgradeValue and currentValue. The key here is to use the dot operator (.); the dot operator often allows us to access methods, but it really depends entirely on the return type. For example, if you returned an array, you could use square brackets ([]) to access the elements in the array. Understanding what each method returns allows you to write more robust code with fewer variables.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s