variable assignment

Discussion in 'JavaScript' started by askscript, Nov 4, 2008.

  1. #1
    I have question on this Javascript code. i am a basic learner.

    The books says that they need to assign the PurcahsePrice to 0 as they do not know what the purchase price is as they need the customer to key in the purchase price ( that is why the prompt command exist)

    My question is , since the PurchasePrice = 0 is being replace by another value when the customer is keying in a new value to it ( at the prompt), Can i use values other than 0, i mean since the 0 value is gonna be replaced, i can use like 5, 34, or other values. Can i do that? if not, why not?

    Thanks.
     
    askscript, Nov 4, 2008 IP
  2. joxtechnology

    joxtechnology Peon

    Messages:
    146
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    yeah you can definitely assign any number to that variable coz var PurchasePrice = 0; only means that you declare a variable and assign an initial value to it.
     
    joxtechnology, Nov 4, 2008 IP
  3. askscript

    askscript Member

    Messages:
    59
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #3
    That means in order to declare a variable, you MUST assign an initial value to it first. I got to do that for every situation?

    i cannot do this? : ( i have seen in example in books that they do that)

     
    askscript, Nov 4, 2008 IP
  4. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #4
    not it does not.

    javascript is so very versatile... i have seen examples of really bad variable assignment, including in so called tutorials. things like pre-declaring the number of items you will have in an array (eg, var blah = new Array(30); )
    so if you are going to use this within the scope of the same function/context why bother with the extra line and assignment?

    var PurchasePrice = prompt('Please enter your purchase price'. '');

    it only makes sense to declare variables if they need to be accessible throughout from functions / classes as global (or even local to the functions)

    this would all be a valid way in declaring variables:
    var foo, bar, moo = 43, messageUser = function(what) { alert("The answer to "+what+" is "+moo); }, items = [], myobject = {}, myobject2 = { 
        html: "bar",
        styles: {
            border: "1 px solid #000",
            padding: 2
        },
        className: "myWindow",
        className2: "myWindowFocused",
        events: {
            "onmouseover": function() {
                this.className = myobject2.className2;
            },
            "onmouseout": function() {
                this.className = myobject2.className;
            }
        }
    }; // end variable declarations...
    PHP:
     
    dimitar christoff, Nov 4, 2008 IP