1
function test(){
    input = document.getElementById("input").value;
    array = [];
    result = array.push(input);
    console.log(typeof(result)) //returns number
}

So when i tries to add the user input into an array it keeps returning numbers, did i do something wrong?

1
  • please consider putting the full code. make it so that we can run it directly from your question and help you. Commented Sep 20, 2020 at 10:26

3 Answers 3

0

You were using typeof(result) which returns the type of your variable result. The type is your case number.

To see what is inside of result, simle use console.log(result);.

More about the typeof operator

Sign up to request clarification or add additional context in comments.

Comments

0

You’re doing it right; you’re just logging the wrong thing. Array.push mutates the array by adding an element to it and returns the length of the array, not the array itself. You can get rid of the result variable. After array.push(input), console.log(array) should give you the result you want.

Comments

0

You have done it the right way but you're not logging the right thing to the browser console. Try console.log(result) instead. Maybe you can try doing it like this and see the behavior. Hope it helps!

let btn = document.getElementById('btn');
btn.addEventListener('click', add); 
function add() {
    const array = [];
    let val = document.getElementById('inp').value;
    array.push(val);
    console.log('The array is = ', array);
}
 <div>
   <button id="btn">add</button>
   <input id="inp" type="text"/>
 </div>

2 Comments

Thanks! it helps a lot (for a beginner)!
Glad it helped!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.