Is a lack of return statement in sub-functions a problem? [JavaScript]

I am currently studying Chapter 3 on Functions from a book called "Eloquent JavaScript".

Although I understand most of the code presented, one thing puzzles me.

Why do the sub-functions within the code snippet not have return statements?

var landscape = function() {
var result = "";
var flat = function(size) {
    for (var count = 0; count < size; count++)
      result += "_";
  };
  var mountain = function(size) {
    result += "/";
    for (var count = 0; count < size; count++)
      result += "'";
    result += "\\";
  };

  flat(3);
  mountain(4);
  flat(6);
  mountain(1);
  flat(1);
  return result;
};

console.log(landscape());
// → ___/''''\______/'\_

Perhaps I am overlooking something crucial about the role of return statements despite consulting various sources for clarification.

I've experimented with adding return statements to the sub-functions. However, it either prematurely ends the function or yields identical results as if no return statement was included.

Thank you for taking the time to read this inquiry.

Answer №1

The code snippet demonstrates how the functions manipulate the outer scoped variable result. Instead of returning values from the inner functions, they directly modify the main result variable. This approach eliminates the need for explicit return statements within the inner functions.

An alternative implementation is presented below, showcasing a version of the code with return statements:

var landscape = function() {

  var result = "";

  var flat = function(size) {
    var localFlat = ''; // Function scoped variable
    for (var count = 0; count < size; count++) {
      localFlat += "_";
    }
    return localFlat; // Return function scoped variable
  };
  
  var mountain = function(size) {
    var localMountain = "/"; // Function scoped variable
    for (var count = 0; count < size; count++) {
      localMountain += "'";
    }
    localMountain += "\\";
    return localMountain; // Return function scoped variable
  };

  result = flat(3) + mountain(4) + flat(6) + mountain(1) + flat(1); // Concatenate the results of each function

  return result;
};

console.log(landscape());

Answer №2

Your sub-functions play a crucial role in influencing the overall outcome by altering the global landscape variable known as "result". This demonstrates how global variables can be manipulated within sub-functions to achieve desired results.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transforming a THREE.js shader into a PIXI.js shader

I am currently exploring the world of PIXI.js and custom Shaders, and I must admit, it's a bit overwhelming for me. I came across a GLSL Shader (created by DonKarlssonSan) that I would like to convert to PIXI.js in order to compare performance. Any as ...

It is not possible to assign a unique name to the custom attr() method

The code provided by someone else is working perfectly fine. However, when I try to rename the attr method, for example to attrx, I encounter an error. The error message I receive after renaming the method is: TypeError: arg.attrx is not a function Below ...

Tips for swapping out a JavaScript variable for a JSON file

I'm currently in the process of developing a website and I'm relatively new to website coding. My aim is to have a rotating text feature that switches between words, similar to a splash text seen in games like Minecraft. I understand that it woul ...

I must create a dropdown and lift up feature similar to the one provided in the example

I am looking to implement a drop-down navigation bar on the top right and a pop-up button/links on the top left. The drop-down menu should appear when the screen size reaches a certain pixel width. If you can't see the drop-down navigation (NAV), adju ...

The webview is in the process of loading, but it is failing

<!DOCTYPE html> <html> <body> <canvas id="myCanvas" width="300" height="150"> Your browser does not support the HTML5 canvas tag.</canvas> <script src='https://code.jquery.com/jquery-2.1.3.js'></script> ...

Accessing nested values in JavaScript objects can be achieved using JSON

Imagine you have this JavaScript object retrieved from a Firebase query. { "player": { "player:616320": { "skills": { "main": { "attack": 1, "defence": 1 } ...

What causes a React Native wrapped component to re-render consistently?

I have a functional component in React native (expo) that is displaying a page using the stack navigator. On this page, there is a simple color picker (react-native-wheel-color-picker), which is a native component, and a button that updates the state. I&a ...

Creating an object efficiently by defining a pattern

As a newcomer to Typescript (and Javascript), I've been experimenting with classes. My goal is to create an object that can be filled with similar entries while maintaining type safety in a concise manner. Here is the code snippet I came up with: le ...

What is the best way to manipulate arrays using React hooks?

Struggling with updating arrays using hooks for state management has been quite a challenge for me. I've experimented with various solutions, but the useReducer method paired with dispatch on onClick handlers seems to be the most effective for perform ...

When using the npm command, errors may occur that are directly related to the lifecycle and initialization

Currently, I am delving into the world of OpenLayers and JavaScript. I came across a helpful tutorial that provides step-by-step guidance on creating a simple OpenLayers project using JavaScript. I followed the instructions diligently but encountered an er ...

acquire data from a JSON array

Attempting to extract the SKU from a URL www.mbsmfg.co/shop/coles-grey/?format=json-pretty in JSON format, and display available values under variants for that specific product to users. For example, when a user visits www.mbsmfg.co/shop/coles-grey/, th ...

Creating a dynamic bar chart using PHP variables

Is there a way I can dynamically display values on a flot bar chart using my PHP variables? For instance, instead of hardcoding the values like this: var data = [ [0, 11], //London, UK [1, 15], //New York, USA [2, 25], //New Delhi, India [3, 24], //Ta ...

Menu selection popper JavaScript

Struggling to create a dropdown menu and encountering this error: "Uncaught Error: Bootstrap dropdown require Popper.js (https://popper.js.org) at bootstrap.min.js:6 at bootstrap.min.js:6 at bootstrap.min.js:6" Explored various solutions in f ...

Tips for storing HTML form data in a local JSON file without the need for PHP or Node.js dependencies

I'm interested in saving any information panel in an HTML file to a local JSON file. For example, if there are blocks like this: <div class="panel"> <div> <input type="text" name="producttype" id=&q ...

The function is failing to provide any output

I'm currently working on a coding project to determine whether a given number is a disarium number. A disarium number is one in which each digit, raised to the power of its position, when added together equals the original number. For example, 75 is ...

What is the best method for excluding undefined values from arrays in javascript?

let values = dataSku.map(sku => {return map.skuInfo[sku].description}) If map.skuInfo[sku] can potentially be null or undefined, how can I filter it out? ...

Show real-time data using Angular6 and GoogleChart

In my project, I am utilizing Angular Cli6, angularfire2, and Firebase to create a timeline using GoogleChart. //GoogleChart.service declare var google: any; export class GoogleChartsBaseService { constructor() { google.charts.load('current&apo ...

changing pictures with jquery

Struggling with this code snippet: $('#clicked_package').css({"background-image" : "url(img/head_2.png)"}).fadeOut("slow"); $('#clicked_package').css({"background-image" : "url(img/head_2_normal.png)"}).fadeIn("slow"); No matter which ...

Why is my .map function not functioning in Google App Engine, even though it works perfectly in localhost?

My Node app with a MongoDB database functions perfectly in localhost, but when deployed to Google App Engine, a specific function stops working. This function uses the .map method to retrieve information from the MongoDB by fetching a value into a JavaScri ...

Problem with RadioButton click event not triggering

Among my collection of RadioButton elements, there is an onclick event that should trigger. This event, named SecurityCheckedChanged, will display or hide other div containers (populated with RadioButton elements) based on the selected RadioButton. Howeve ...