There seems to be an issue with the code. I am encountering a runtime error

const cities = ['New York', 'Paris', 'Tokyo'];

for (let j = 0; j < cities.length; j++) {
if (cities[j] === '') {
console.log("Visit New York!");
}
console.log("Enjoy your trip!");
}

// I encountered a runtime error with the code above. Can someone assist me, please?

Answer №1

Why is it that your if statement does not have brackets surrounding the case?

It only executes the first line after it, which is acceptable. However, it is generally considered good practice to enclose your cases in brackets.

Furthermore, within your if statement, you are assigning ' ' to names[i].

You should utilize the double equals operator.

if (names[i] = '')

Change this to:

if (names [i] == ' ')

Answer №2

let cities = ['Cairo', 'Egypt', 'Africa'];

Your code is causing issues for several reasons. You forgot to open your if statement with curly brackets {} and also neglected to close it properly. Additionally, the variable i will never be an empty string ''.

Consider this revised code snippet:

for (let i = 0; i < cities.length; i++) {
    if (i === 0) {
        alert("Go Cairo!");
        alert("You're amazing!");
    }
}

Keep in mind that arrays start indexing from 0, so ensure your loop starts at index 0 rather than 1.

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 looking to convert this typescript function to return an array with strong typing instead of just a plain string[]

I am currently in the process of converting a JavaScript function to TypeScript. Originally, I believed that the type of the variable hi would be ('s'|'bb')[], but it turned out to be string[]. Is there a way for TypeScript to automatic ...

bxSlider adds in an empty slide after deleting an image

Whenever I click a link in my navigation, I want to remove certain images from the page. I tried implementing a solution, but now I have two empty spaces where the images used to be. How can I remove those as well? I searched on Stack Overflow for a soluti ...

Tips for retrying Ajax requests with references and incorporating success and failure handlers

I am currently testing the feasibility of storing a reference to an ajax call upon failure and then retrying the call at a later time. My attempt so far has been the following: $.ajax({ url: "controller/action", data: { params: "here" ...

Having trouble with Npx and npm commands not running in the VSCode terminal?

I am currently facing an issue while attempting to set up a react app in vscode using the command npx create-react-app my-app. It seems like the command is not working properly. Can anyone provide guidance on what steps I should take next? Despite watchin ...

Adjust Leaflet map size when the containing element is resized (Dash Plotly)

I am encountering some difficulties with dash-leaflet, particularly regarding its width when the parent container is resized. I am utilizing dash-resizable-panels to resize certain divs. Allow me to present a Minimal Reproducible Example (MRE) below: # pi ...

Guide to stripping HTTP headers from a REST API request using JavaScript

Hey there! I'm currently working on extracting a specific part of the response from the {}. This information is retrieved from the gemini public database, and my goal is to retrieve only the content within the curly braces and store it as a string in ...

Displaying a div when an ng-repeat directive is devoid of content, incorporating filters in AngularJS

Currently, I am in need of a solution to display a specific div when my ng-repeat list is empty. The scenario involves a list containing various types of ice cream (with search filter functionality). What I aim to achieve is showing a designated div when t ...

How about: "Is there a way to show items in a list without using

I have removed the bullet points from an unordered list, but I am having trouble displaying Log with every message. The code I have doesn't seem to be working as expected. I want users to be able to differentiate between messages easily, without seein ...

Just updated to Angular 10, encountered issue: Unable to modify the read-only property 'listName' of an object

After updating my Angular project from version 8 to version 10, I encountered an error while trying to edit an input field in a Material Dialog. The error message displayed is as follows: ERROR TypeError: Cannot assign to read only property 'listName& ...

Find the Dimensions of Columns in Matrix

I am working on determining the length of each column in a 4x4 matrix. The lengths are counted from the bottom of each column upwards, starting from the initial '1' accessed onward. 1110 0111 0110 0001 To calculate: Column1=1, Column2=3, Col ...

JavaScript is unresponsive and fails to display

I attempted to incorporate my initial Javascript snippet into a browser to observe its functionality. However, upon adding these lines directly into the body of my HTML code (even though I am aware that there are more efficient methods), no visible changes ...

How to use keyboard shortcuts to play audio in HTML using onkeydown event

I'm having trouble getting my function to play the audio when triggered. Any advice or suggestions would be greatly appreciated. tags$div( tags$audio(id = 'targetAudio',src = sprintf("audioResources/%s.wav", trialName), type ...

Deliver a binary reply using Node.js from a PhantomJS subprocess

Recently, I developed a node endpoint that generates rasterised versions of my svg charts. app.post('/dxexport', function(req, res){ node2Phantom.createPhantomProcess(req,res); }); To achieve this, my node to phantom function utilizes spawn ...

Can you tell me the locations of the src/js and build/js directories?

Just starting out and seeking guidance. I am currently working with Node v4.2.1 and Gulp 3.9.0 on a Windows 7 machine, following along with a tutorial to familiarize myself with the task runner Gulp. I'm attempting to concatenate tasks but I seem to ...

Display a progress bar on the index page of the grid view

Seeking assistance in displaying a progress bar on the grid view page index. Currently, I have successfully implemented a progress bar on button click and would like to replicate this functionality when the user switches from 1 to 2. Here is the modal pop- ...

Weird behavior observed in loop through 2D Array (FCC)

I'm currently engaged in a learning exercise and I am attempting to comprehend the code provided. While I believed I had a solid grasp of arrays and loops, this particular piece of code has left me feeling quite puzzled. The code snippet below: fun ...

The combination of Socket.io and the Redis adapter is failing to save any data to Redis

I am currently utilizing the most recent version of Socket.io and require it to be compatible with the Redis adapter in order to function properly across multiple Pods/Servers. The functionality of Socket.io is working as expected; messages are being emitt ...

Disappearing Image on Hover in JavaScript and HTML

I'm encountering an issue with my JavaScript hover effect on two images. When a user hovers over the arrow image, it should change to a hover version of that image. Additionally, if the user clicks on the arrow, it should trigger another JavaScript fu ...

Does ECMAScript differentiate between uppercase and lowercase letters?

It has come to my attention that JavaScript (the programming language that adheres to the specification) is sensitive to case. For instance, variable names: let myVar = 1 let MyVar = 2 // distinct :) I have not found any evidence in the official specific ...

Seeking assistance with basic Javascript/Jquery for Ajax on Rails 3 - can anyone help?

I've been diving into JavaScript and hit a roadblock. At the moment, I have a very basic gallery/image application. My goal is to create a functionality where clicking on an image will lead the user to a URL stored in my model data using AJAX. Additi ...