Search code examples
javascriptvariablesdeclare

Declare JavaScript variable only with ' ' marks


I saw one of the masters doing this:

var example = '';

Then later he continued with this:

example += '<div>just a div</div>';

I wanna know if there's any difference from doing this:

var example;

example += '<div>just a div</div>';

I don't really know if by doing the second method I'm doing wrong and I have to code like shown if the first example.


Updated!

Thank you so much for your answers, Ok I got it I need to define my variable to be able to work woth it, but then another question came... This master also is doing this:

var guess;

and then he does:

guess += myfunction( upper );

where myfunction was declared as follows:

function myFunction( upper ){
    return Math.floor( Math.random() * upper ) + 1;
}

So, why here is different? Can any of you answer this please?

Thank you!


Second update!

Again Thanks!

I decided to post the whole code the JS master was doing, at this point I don't understand, so probably you'll be able to clear my doubts.

var randomNumber = myFunction( 10 );
var guess;
var attempts = 0;
var answer = false;

function myFunction( upper ){
    return Math.floor( Math.random() * upper ) + 1;
}

do{
    guess = prompt( "I created a number from 1 till 10, can you guess it?");
    attempts += 1;
    if( parseInt( guess ) === randomNumber ){
        answer = true;
    }
}while( ! answer )
    document.write( "Took you " + attempts + " attempts to guess the number " + randomNumber);

Please have a look at:

var guess;

and how later is being declared, so why here works perfectly but in my first example I have to put the '' when declaring my variable?

I hope my question is clear enough for you!

Thank you for your time and patient!


Solution

  • When you do:

    var example;
    
    example += '<div>just a div</div>';
    

    You end up with:

    `"undefined<div>just a div</div>"`
    

    This is because when you don't initialize a variable, it is undefined, which can be converted to a sensible string "undefined" when you try to add it to another string.

    When you do:

    var guess;
    
    guess += myfunction( upper );
    
    function myFunction( upper ){
        return Math.floor( Math.random() * upper ) + 1;
    }
    

    You are adding a number to undefined. This results in NaN (not a number) because undefined cannot be converted into a sensible number.

    You can check this yourself next time by opening up your browser's developer tools and running the code in the console.

    Edit:

    When you do:

    var guess;
    
    guess = prompt( "I created a number from 1 till 10, can you guess it?");
    

    There's no issue because you are simply assigning a string to the guess variable. In the previous examples you were adding something to a variable, which means if they are different types then JavaScript has to try to do something sensible.