Embedding a for loop within a function

My goal is to halt a for loop once it reaches a specific input value. I managed to accomplish this task when executing the loop outside of a function. For instance, if I set the input variable to 'not leak', I want the loop to stop at 'not' and combine it with the keyword variable, which is 'leak', to display 'not leak'. However, when I tried integrating the loop into a function, it did not perform as expected and generated multiple results until the input variable matched the text variable. Instead, I only want it to output 'not leak'.

I experimented with different function formats, such as assigning the function as a variable, passing parameters to the function, and placing variables inside and outside the function without making any progress. It appears that the break if statement fails to work correctly once placed within a function. Any insights on why this happens and how to resolve it?

Here is the code inside a function:

function negKeyword() {

var keyword = 'leak'; 
var input = 'not leak'; 
var text = ''; 
var arr = ['no', 'not', 'checked', '']; 

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

if (text == input) { break; }
text = arr[i] + ' ' + keyword;
console.log(text);

}

}

negKeyword();

Below is the code executed outside a function:

var keyword = 'leak'; 

var input = 'no leak'; 

var text = ""; 

var arr = ['no', 'not', 'checked', '']; 

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

if (text===input) {break;}
text = arr[i] + ' ' + keyword;

}

console.log(text);

Answer №1

It appears that you have placed the console.log statement inside the loop, which means it gets executed multiple times. The code below demonstrates how to move the console.log statement outside the loop for correct functionality:

function negKeyword() {

var keyword = 'leak'; 
var input = 'not leak'; 
var text = ''; 
var arr = ['no', 'not', 'checked', '']; 

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

if (text == input) { break; }
text = arr[i] + ' ' + keyword;

}
console.log(text);//Place this here (outside the for loop)

}

negKeyword();

Answer №2

Make sure your console.log statement is placed outside of the loop.

function negativeKeywords() {

var keyword = 'leak'; 
var input = 'not leak'; 
var text = ''; 
var arr = ['no', 'not', 'checked', '']; 

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

if (text == input) { break; }
text = arr[i] + ' ' + keyword;
}
return text;
}

console.log( negativeKeywords() );

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

What could be causing my selenium tests to fail on travis-ci even though there have been no code changes, when they are passing successfully

I'm facing a tough challenge trying to troubleshoot a selenium test that passes when run locally but not on travis. Reviewing the travis build logs, I noticed that the test was passing in build #311 but started failing at build #312. It seems like th ...

Basic Search tool, displaying a <div>

Hey there, I've been searching for a solution for a while now and haven't found one yet. So here's my question: I created a simple website to display random recipes for those times when you're not sure what to make for dinner. I also w ...

PHP page Not Refreshing Properly Without Ajax

I am in need of assistance. Could someone please provide me with a code that has been thoroughly reviewed and tested for errors to address my issue? The program, 22.php, consists of a form. The desired functionality is for the user to enter information and ...

Hardware meets imagination. Crazy or genius?

The other day, I discovered a fascinating Verilog trick. Using a shift register to count the number of incrementations when something needs to be done repeatedly is quite clever. Simply shifting a 1 from the LSB to the MSB and once it reaches the MSB, the ...

Place a new button at the bottom of the react-bootstrap-typeahead dropdown menu for additional functionality

Currently, I have successfully implemented the React Bootstrap Typeahead with the desired options which is a good start. Now, my next challenge is to integrate a custom button at the end of the dropdown list for performing a specific action that is not ne ...

`How can I implement a URL change for socket.io users?`

I am currently developing a multiplayer game using node.js, socket.io, and express for TWO players. To ensure that only the intended two players are able to join the game and avoid interference from others, I'd like to generate a unique URL specifica ...

Unable to display individual elements of an array using the map function in React Native

Below is my react-native code that I am using to display a list of array elements using the map function. import React from 'react'; import { createStackNavigator } from '@react-navigation/stack'; import {Card} from 'react-native-e ...

Looking to dissect JSON output containing the object labeled as "@attributes"?

Using JQuery AJAX, I made an HTTP request to a PHP back-end in order to retrieve an XML string parsed into JSON using the json_encode() function. Some of the XML elements contain attributes which are represented as @attributes in the output. However, when ...

jQuery functions failing to target dynamically generated elements

I've encountered an issue while attempting to implement my jQuery functions on dynamically created content using the .on API from jQuery. The main objective of the code is to display a specific set of options only when a user hovers over the ".feed_po ...

The internet explorer browser does not support the keypress event

i have the following code snippet: <input class="any" type="text" id="myId" name="myName" /> this specific input is using a jquery datepicker plugin.. (http://jqueryui.com/datepicker/) Here is my JavaScript for this element: $('#myId'). ...

I have a project where I'm tasked with assembling a collection of images sourced from an Array populated with JSON

For a homework assignment, I am tasked with creating a basic gallery that showcases 4 images. My goal is to store all the images in an array, with each photo represented as a JSON object, and then load these images from the array. Here is my progress so fa ...

Ways to confine the movement of a draggable div in this particular scenario

Exploring the HTML Structure: HTML <div id="outer"> <div id="inner"> <div id="bounds"> <div id="myimage"> </div> </div> </div> </div> Customizing with CSS #ou ...

Is there a way to identify the moment when a dynamically added element has finished loading?

Edit: I've included Handlebar template loading in my code now. I've been attempting to identify when an element that has been dynamically added (from a handlebars template) finishes loading, but unfortunately, the event doesn't seem to trig ...

Issue with redirect after submitting CakePHP form not functioning as expected

I am in the process of developing a button that will submit a form and then redirect to another page. $('#saveApp').click(function() { event.preventDefault(); $("form[id='CustomerSaveForm']").submit(); // using the nati ...

The Body Parser is having trouble reading information from the form

I'm struggling to understand where I'm going wrong in this situation. My issue revolves around rendering a form using a GET request and attempting to then parse the data into a POST request to display it as JSON. app.get('/search', (re ...

How to access a global variable within an Angular application

Using node express and angular, I have set up a route in my express app.js where I pass a variable to the rendered page: app.get('/test', function(req, res){ res.render('test', { user: 12345 }); }); Within my 'test' view, ...

A guide to determining the dimensions (width, height, length) of a mesh using THREE.js

I've been scouring different sources in hopes of finding a way to obtain the width and height of a mesh, but I haven't had any luck. I have imported a collada model into my project, and all I need is to determine its dimensions in Webgl/Three.js ...

Is there a way to programmatically toggle a button's enabled state depending on the content of a text input field?

I want to create a functionality where a button will be enabled if the value in a textbox is 'mypassword'. If it's not equal to 'mypassword', then the button should be disabled. I've attempted the code below, but it doesn&apos ...

JavaScript's ability to utilize local files

Has anyone successfully performed local file manipulation using JavaScript without any installation requirement like Adobe AIR? I am specifically interested in reading the contents of a file and writing them to another file. I am not concerned about permi ...

The ng-grid is failing to update with the most recent data following the asynchronous XMLHttpRequest response

I am facing an issue with my AngularJS web application. I am trying to upload a file to a server and update ng-grid with the last uploaded file's entry once the upload is complete. Below is the HTML for my grid: <div class="gridholder" data-ng-gri ...