skip to Main Content

I’m a beginner at JavaScript and I need help solving a problem. The assignment is:

**
/*
Arrays & Loops
Step 1
Create an empty array and assign it to a variable called "numberList".
*/

/*
Step 2
Using a for loop, place the numbers from 0 to 5 into the "numberList" array.
console.log the numberList array.
*/

/*
Step 3
Remove the last number in the array and console.log the array.
/*

Here’s the code I have so far:

var numberList = [];
for (let numberList = 0; numberList = 5; numberList++) {
    console.log(numberList);
};

var number = numberList.pop()
console.log(number);

When I run this in VSCode, it doesn’t perform what the assignment is asking for. I’ve tried a lot of different options over and over again and I’m not sure what I’m doing wrong.

I’m expecting the sequence [0, 1, 2, 3, 4, 5] to appear in an array, and then for the pop function to remove 5 from the array, but no matter what I do it’s not working.

2

Answers


  1. You almost got it right!

    I recommend you to check how for loops work and what the index i in the code I provide you below does.

    Also you might need to check how to place values into an array.

    In JavaScript and in most languages we do

    array[position] = desiredValue;
    

    And then to access the desired value we just need to do array[position].

    Feel free to ask any other question! We are here to learn.

    ** /* Arrays & Loops Step 1 Create an empty array and assign it to a variable called "numberList". */
    
    const numberList = [];
    
    /* Step 2 Using a for loop, place the numbers from 0 to 5 into the "numberList" array. console.log the numberList array. */
    
    for (let i = 0; i <= 5; i++) {
      console.log(i)
      numberList.push(i);
    }
    
    console.log(numberList);
    
    /* Step 3 Remove the last number in the array and console.log the array. */
    let number = numberList.pop();
    console.log(numberList);
    
    Login or Signup to reply.
  2. The push() method is missing.

    So please follow the below steps:

    let arr = []; // Assigned the empty array to 'arr' variable.
    
    for(let i=0; i<=5; i++) {
        arr.push(i); // Just push the looping values to 'arr' variable. 
    }
    
    console.log(arr) // Output: [0, 1, 2, 3, 4, 5]
    
    arr.pop() // Removed the last index value 
    
    console.log(arr) // Output: [0, 1, 2, 3, 4]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search