JavaScript: What is the best way to increase the size of an array by adding new elements

I am attempting to generate an array containing the first 100 prime numbers. Here is the code I have written:

var primeArray= [];
var num= primeArray.length;

function checkIfPrime(n)
{
    if(n < 2)
    {
        return false;
    }

    for(i=2; i<Math.sqrt(n); i++)
    {
        if(n%i===0)
        {
            return false;
        }
    }
    return true
};

while(num<100)
{
    var j=2
    if(checkIfPrime(j)==true)
    {
        primeArray.push(j);
    }
    j=j+1
}

As a beginner in Javascript, I have verified that the checkIfPrime function works well even with large numbers.

However, upon running the program, I encounter the following error:

FATAL ERROR: JS Allocation failed - process out of memory

I suspect there might be an issue with this part of the code:

while(num<100)
{
    var j=2
    if(checkIfPrime(j)=true)
    {
        primeArray.push(j);
    }
    j=j+1
}
console.log(primeArray)

But I cannot pinpoint the exact problem.

Answer №1

Each time the loop runs, you are consistently assigning the value j=2, and the variable nombre remains unchanged, causing the loop to run indefinitely. Remember that in JavaScript, literal values are set by value, not reference, so simply writing nombre = premier.length will not dynamically update.

In addition, be cautious of statements like if( x = true) as this will actually assign the truthy value to x and always pass the condition automatically. If x is a function call in this context, it results in invalid syntax.

Perhaps you intended for this code instead:

var j = 2;
while(premier.length < 100) {
    if( isPrime(j)) premier.push(j);
    j++;
}

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

Invoke the forEach method within a lambda function and assign the output to a variable

In order to achieve my goal, I am looking for a way to take an array as input and save the result for future use. Unfortunately, I do not have permission to create additional functions. As a result, the code must accurately reflect what result should be. l ...

Is it possible to integrate a JavaScript library into the Vue prototype?

I've recently integrated ProgressBar.js library into my app, which is built using vue and laravel with laravel mix. After installing ProgressBar.js via npm install, I am unsure how to incorporate it into my .vue files. I'm considering adding it t ...

Generating a dynamic drop-down menu in Django using database values

My goal is to create a Django app that includes dynamic drop-down lists for vehicle makes and models. When selecting a specific make, the models list should update to display only the models that fall under that make. I believe this can be achieved using j ...

performing asynchronous iteration with HTTP PUT requests

I'm attempting to send multiple HTTP PUT requests to my server, but I am only able to successfully send one JSON object to the database. What could be missing in my code? var data1 = JSON.stringify(require('./abc.json')), data2 = JSON ...

What is the best method for sending variables to the `script.` block in Pug?

I am encountering an issue with the code in my index.pug file doctype html html head title= title body script(src=`${source}`) script. for (var event of events){ VClient.Event.subscribe(event, createDiv); } This is how ...

Deleting all JSON files in a directory using NodeJs

Is there a way to delete only the json files within a directory (multiple levels) without specifying each file name individually? I thought fs-unlinkSync(path) might work, but I haven't found that solution yet. I attempted to use the following method ...

Developing several sliders and ensuring they operate independently of each other

I am currently in the process of developing multiple sliders for a website that I am building. As I reach the halfway point, I have encountered a problem that has stumped me. With several sliders involved, I have successfully obtained the length or count ...

Apply CSS styling (or class) to each element of a React array of objects within a Component

One issue I'm facing involves adding specific properties to every object in an array based on another value within that same object. One such property is the background color. To illustrate, consider an array of objects: let myObj = { name: "myO ...

Basic jQuery request for JSON data

In an effort to send user data to a PHP script and display the results in an element, I am utilizing JSON. The process works smoothly until reaching the response stage. Despite receiving the correct results when logging to the console, attempting to append ...

Looking for a way to automatically load an aspx page when the browser is closing

Hey there, I'm struggling to load an aspx page when the browser is closed. I thought I had the code right, but it's not working. Can someone please lend a hand? Thanks! var clicked = false; function CheckBrowser() { ...

Leveraging code behind and serialized JSON in an ASP.NET web application

I've recently created an array using a LINQ query: var aTimeResultQuery = (from fct in context.fct_testautomation join dr in context.dim_driver on fct.driver_key equals dr.driver_key join tc in context.dim_test_case on fct.test_case_ ...

TinyMCE generates HTML code with embedded tags

Hey there, I'm currently facing an issue with TinyMCE that I just can't seem to solve. I've browsed through some related posts but haven't found a solution that works for me... For example: When I input something in my back office, ...

Unable to modify the state of data in Vue.js

After developing a weather app, I implemented some components with fields in the data section. However, when I changed the value of these fields in the methods section and attempted to access them in another method, I discovered that the old values were be ...

Adding ngChange programmatically in Angular without using attributes is a common challenge faced

I am attempting to replicate the functionality of the ng-change attribute within a directive without making changes to the HTML (thus excluding the use of the ng-change property). After examining the Angular source code for the ngChange directive, I have ...

What is the method for extracting CSS class names and storing them in an array using PHP?

Hey there, I have a bunch of CSS code and I'm looking for a way to extract only the names of the CSS classes without the unnecessary characters and values, and then store them in an array using PHP. For Example: .dungarees { content: "\ef ...

What is the best way to display a series of PHP arrays within a string using echo in a loop

Having this particular string: print_r($elements); This is the output: Array ( [1] => Array ( [1] => USA [2] => CANADA [3] => BRAZIL ) [2] => Array ( [1 ...

guide on launching react with pure javascript

Is it feasible to operate react "straight out of the box" using only JavaScript? In essence, I am seeking a way to utilize react by simply utilizing notepad to create the page (without needing to install and configure node etc.). More specifically - 1) ...

What could be causing my dropdown menu code to malfunction?

Having trouble with the drop-down menu! I used "display: none;" in CSS to hide the list, but I'm not sure if it's the best way. This idea was borrowed from a Codecademy project. I know there may be some cringe-worthy code here, but please bear w ...

Formatting a datetime string in Angular to display as yyyy-MM-dd HH:mm

I'm facing an issue with datetime formatting in angularJS. I'm trying to convert the datetime "1990-11-25 14:35:00" into the format 25/11/1990 14:35, without using a Date object in the controller. It seems like angular can only handle proper da ...

Modify the elements of a matrix by analyzing their surrounding neighbors

I'm working on a script that will transform my matrix A (1x25) into B (1x24) A = [1 1 1 1 0 0 1 1 1 1 0 0 1 1 1 1 0 0 1 0 1 1 1 1 1]; The transformation rule I want to apply is as follows: Two consecutive 1s should be replaced with 1. Two consecut ...