1

I have the below code in JavaScript (not showing the HTML Part, but it works).

var textboxnumber1 = document.querySelector('.number1');
var textboxnumber2 = document.querySelector('.number2');
var calcbutton = document.querySelector('.calcbutton');

var num1 = Number(textboxnumber1.value);
var num2 = Number(textboxnumber2.value);

function writenumbers() 
{
    window.alert(num1);
}

calcbutton.addEventListener('click', writenumbers);

This returns me 0 as the num1 value,

However, If i replace window.alert(num1); with window.alert(Number(textboxnumber1.value)); i get it's value correctly.

Why num1 is not showing the value?

2
  • Remember that Javascript is not Haskell - evaluations are not lazy. Commented Jan 19, 2018 at 13:36
  • Use your browser's debugger. Place breakpoints outside of the function where you set a value to num1 and inside the function where you display the value. What do you notice about the order of events? Commented Jan 19, 2018 at 13:37

3 Answers 3

4

Your code to retrieve the text box value is OUTSIDE of your function, so it will only run once at load. At page load the value is 0.

Move this code to inside the function:

function writenumbers() 
{
    var num1 = Number(textboxnumber1.value);
    var num2 = Number(textboxnumber2.value);

    window.alert(num1);
}
Sign up to request clarification or add additional context in comments.

Comments

1

When you call your function on click, the num1 variable is not assigned, but if you declare it inside the alert method it work so try this :

   function writenumbers() 
    {
        var num1 = Number(textboxnumber1.value);
        var num2 = Number(textboxnumber2.value);
        window.alert(num1);
    }

    calcbutton.addEventListener('click', writenumbers);

Comments

1

@UncleDave's answer is correct, but why?
Because this code:

var num1 = Number(textboxnumber1.value);

Will be evaluated first thing when page loads, and set the initial value of textboxnumber1 in variable num1.
Now wherever you used num1 in your code it'll always be the same (the initial value of textboxnumber1) it's assigned by value not by reference.

Comments

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.