Executing a function within a loop

I'm having trouble understanding the output. The first two sets of results (func01 1 and func2 01 - func2 05) make sense to me, but everything else is confusing.

As far as I know, after the first iteration of the for loop in func01(), i becomes 2 and then 3 due to func02(), but still, i <= 3 in func01(). It's puzzling to me why there are no func01 2 and func01 3 outputs displayed.

function func02(){
  for (i = 1; i <= 5; i++){
    document.write("  func02 " + i + "<br>");
  }
}

function func01(){
  for(i = 1; i <= 3; i++){
    document.write("func01 " + i + "<br>");
    func02();
  }
}

func01();

Answer №1

Below is the output presented in a neat format

func01 1
func02 1
func02 2
func02 3
func02 4
func02 5

The function func01 initializes i, a global variable, to 1 and prints a line. It then calls another function named func02. Within func02, i is reset to 1 and lines are printed corresponding to values of i from 1 to 5. After this iteration, control returns to func01, signifying the completion of the loop with i being equal to 5.

Answer №2

When a variable is assigned without the use of var, and it cannot be found in the current scope, it is then searched for in the next outer scope. This process continues until the variable is either found or ends up in the global scope.

If the variable is not located within any scope, it will be placed in the global scope. In this case, both func01 and func02 are referencing and updating the same variable i. Therefore, when func02 finishes running and func01 starts, the value of i is already at 6, preventing the loop from executing again in func01.

To achieve the desired outcome, you can modify the counters to utilize var, which will restrict the scope of i to the specific functions they belong to.

function func02(){
  for (var i = 1; i <= 5; i++){
    document.write("&nbsp;&nbsp;func02 " + i + "<br>");
  }
}

function func01(){
  for(var i = 1; i <= 3; i++){
    document.write("func01 " + i + "<br>");
    func02();
  }
}

func01();

Answer №3

You need to declare the variable i within a local scope using either let or var. Otherwise, it is being treated as a global variable:

 

function func02(){
  for (i = 1; i <= 5; i++){
document.write("&nbsp;&nbsp;func02 " + i + "<br>");
  }
}

function func01(){
  for(i = 1; i <= 3; i++){
document.write("func01 " + i + "<br>");
func02();
  }
}

func01();

Answer №4

According to user202729, in JavaScript, if you fail to declare a variable, it defaults to global scope rather than the function's scope where it is used.

To avoid this issue, make sure to declare your variable i like this:

for(var i = 1;i <= 5 ; i++)

You can also declare the variable at the beginning of the function like so:

var i;

function func02(){

  for (var i = 1; i <= 5; i++){
    document.write("&nbsp;&nbsp;func02 " + i + "<br>");
  }
}

function func01(){
  for(var i = 1; i <= 3; i++){
    document.write("func01 " + i + "<br>");
    func02();
  }
}

func01();

For more information on scoping of JavaScript variables, check out https://www.w3schools.com/js/js_scope.asp.

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

I'm having an issue where I'm trying to post form data using AJAX, but for some reason, the form continues to submit and refresh the page. Can anyone

Recently, I have been working on a small and simple chat application using mainly JQuery and AJAX technologies. Below is the HTML form I have created for this chat application: <form class="chat_form" method="post" id="chat_form" autocomplete="off"> ...

What is the significance of declaring a constant array in JavaScript?

Does declaring an array as a constant in JavaScript prevent it from changing size, or does it mean that the values inside the array cannot be modified? handleClick(i) { const squares = this.state.squares.slice(); squares[i] = 'X'; this.setState( ...

How can one achieve an explosion effect using jQuery?

Hey there! Here's a question to ponder... Let's assume we have a JavaScript variable set up like this: let myString = 'x,y,z'; let separated = myString.split(','); Now, imagine we have an HTML element like this: <ul id= ...

Angular is the best method for properly loading a webpage

Struggling to solve this issue. I have a webpage where I need to load another webpage, specifically a page from a different site, into a div. Essentially, it's like a news ticker that I want to showcase. The problem is that the URL is stored in a Mon ...

Encountered an issue with the Mongoose Schema method: The model method is not recognized as a

Here are two Mongoose model schemas that I am working with. The LabReport model includes an array that references the SoilLab model. Within the SoilLab model, there is a static method that was initially used to choose which fields to display when retrievin ...

Unable to transform Symbol data into a string - Error when making a React AJAX delete call

I'm encountering an issue where I am getting a Cannot convert a Symbol value to a string error in the console. My tech stack includes React v15 and jQuery v3. https://i.stack.imgur.com/qMOQ8.png This is my React code snippet: var CommentList = Reac ...

Using JavaScript to assign function arguments based on arbitrary object values

I am facing a challenge with a collection of arbitrary functions and a method that takes a function name along with an object or array of parameters to call the respective function. The issue arises from the varying number of inputs in these functions, som ...

Discover the method for retrieving the value of a toggle-style checkbox

I am currently working with a toggle switch checkbox and I need to extract its value using JavaScript or jQuery when the state changes. Based on this value, I aim to highlight the text of the label associated with the toggle switch, whether it's opti ...

The amazingly efficient Chrome quick find feature, accessible by pressing the powerful combination of Ctrl + F, ingeniously

Currently using Google Chrome version 29.0.1547.62 m. I've employed the CSS attribute overflow set to hidden on the parent element, which renders some of my DIV elements hidden from view. Additionally, these concealed DIV elements are adjusted in pos ...

retrieve the preferred item data from the local storage

Having trouble retrieving favorite items from my list item app using Ionic 4. Although my JSON data is added to local storage, I am unable to retrieve the data properly. favourite.service.ts getAllFavoriteItems(){ return this.storage.get("object"); ...

d3.js attempting to animate data, but each time the data is altered it is always perceived as new

I have a JSON dataset that consists of an array of frames, with each frame containing an array of 10 nodes. Each node is represented as a dictionary with the node id and x,y coordinates. My objective is to devise a d3 animation that smoothly transitions be ...

An error popped up out of the blue while attempting to execute Webpack

Looking to deploy my React website on IIS but encountering an error when running npm run build:prod. The error message states: index.js Line 1: Unexpected reserved word. You may need an appropriate loader to handle this file type. Below is the snippet fro ...

Utilizing the array result obtained from the fetch function

Seeking assistance with a coding issue. I am puzzled as to why I am unable to utilize the data returned from an API call outside of its function, even though there are no errors occurring. The fetchUser function successfully retrieves the data from the API ...

Issue arises when attempting to incorporate a SET statement into a DO loop for an array

My computer runs on Windows 10 64 bit and I am attempting to create a BAT file. The code I have is not functioning properly. @Echo off SETLOCAL enabledelayedexpansion SET value1=2020_01_19_17_00_01 SET Arr1[0]=_f104.sql SET Arr1[1]=_f105.sql SET Arr1[2]=_ ...

What is the best way to include the toast component in my button?

I am brand new to working with Next.js and React. I have a button in my project that triggers an external JavaScript file (query.js). After the script finishes executing, I would like to display a toast notification indicating whether it was successful or ...

Organize JSON information in a tabular layout

After resolving my previous issue, I am now attempting to store JSON data in cookies and then retrieve it to organize the variables in tabular form. However, I am uncertain about how to go about arranging it. View the demonstration here ...

In order to display the new component upon the first click in React, my button requires a double click

I have a project that utilizes the open Trivia API to fetch data. I've completed the development and everything appears to be working well so far. However, there's a bug where upon initially rendering the app, the first time I click the button to ...

What is the best way to prevent the chaining of promises and catches in JavaScript?

I am currently developing an API using node and express to create users. However, I find myself struggling with error handling due to the asynchronous nature of MongoDB functions, which makes me feel like I'm trapped in a "promise hell." I anticipate ...

Is there a way to have the user input data into a Firebase database directly from a Vue.js component?

Any assistance for a beginner like me would be greatly appreciated. I am currently working with vuejs and firebase to write data into the database from a vue component. I have successfully implemented authentication and writing functionality, but now I wan ...

Using Angular.JS to iterate over a nested JSON array using ng-repeat

I am currently working on a People service that utilizes $resource. I make a call to this service from a PeopleCtrl using People.query() in order to retrieve a list of users from a json api. The returned data looks like this: [ { "usr_id" : "1" ...