3
\$\begingroup\$

This is just playing around and practicing javascript. I am learning JavaScript from Codecademy and I practice coding everyday so I can learn much as possible. I have a lot of if statements, prompt boxes, some alert boxes. I just got finished learning about functions and returns. I just don't know how to use the return in a browser for like document.write or even an alert box.

function prompter() {
    var toc = prompt("What do you prefer? Tea or Coffee");
    if ((toc == "tea") || (toc == "Tea")) {

    } else if ((toc == "coffee") || (toc == "Coffee")) {

    }
    var foc = prompt("What do you prefer? Facebook or MySpace");
    if ((foc == "facebook") || (foc == "Facebook")) {

    } else if ((foc == "myspace") || (foc == "Myspace")) {

    }
    document.write("<center><h2>So you like " + toc + " and " + foc + " that is awesome.</h2></center>");
}

function pickAColour() {
    var fun = prompt("What is your favorite colour? , mine is red.");
    document.write("<center><h2>You like the colour " + fun + " that is a nice colour</h2></center>");
}

function pickANumber() {
    alert("Lets do some math, do you like Math?");
    var pan = prompt("Please pick a number");
    var nap = prompt("Please pick another number");
    var symbol = prompt("Please pick one of the following symbols +  -  *  /");
    pan = parseInt(pan); //The parseInt() function parses a string and returns an integer.
    nap = parseInt(nap); //The parseInt() function parses a string and returns an integer.
    if (symbol == "+") {
        alert("You picked the Add symbol");
        alert("Lets add both these numbers together. " + pan + " " + symbol + " " + nap);
        document.write("<center>Your number is " + (pan + nap) + "</center>");
    }
    if (symbol == "-") {
        alert("You picked the Minus symbol");
        alert("Lets Minus both of these numbers. " + pan + " " + symbol + " " + nap);
        document.write("<center>Your number is " + (pan - nap) + "</center>");
    }
    if (symbol == "*") {
        alert("You picked the Multiply symbol");
        alert("Lets Multiply both these numbers. " + pan + " " + symbol + " " + nap);
        document.write("<center>Your number is " + (pan * nap) + "</center>");
    }
    if (symbol == "/") {
        alert("You picked the Divide symbol");
        alert("Lets Divide both these numbers. " + pan + " " + symbol + " " + nap);
        document.write("<center>Your number is " + (pan / nap) + "</center>");
    }
}

function run() {
    var name = prompt("What is your name?");
    document.write("<h1><center>Welcome to this special JavaScript page " + name + "</center></h1>");
    prompter();
    pickAColour();
    pickANumber();
    document.write("<center>Thank You for visting this page</center>");
}

run();
\$\endgroup\$
3
  • 1
    \$\begingroup\$ ... good going! I'd suggest making friends with JSHint if you have not already. It picks up a lot of piddly stuff that if you learn to avoid early on, will help develop clarity and adherence to best practices. When practicable that is ;-) \$\endgroup\$
    – vector
    Commented Jul 18, 2012 at 22:30
  • 3
    \$\begingroup\$ Any learning resource that teaches you to use document.write should be shunned and avoided. \$\endgroup\$
    – Corbin
    Commented Jul 18, 2012 at 22:40
  • \$\begingroup\$ You should definitely try codeschool.com/courses/jquery-air-first-flight for learning about much better ways of manipulating your web pages. It's like Code Academy on steroids. \$\endgroup\$ Commented Aug 3, 2012 at 11:23

3 Answers 3

6
\$\begingroup\$

You seem to be on the right track, at least with grasping how to do some basic coding.

Right now, I only see one major issue: document.write()

document.write() is used to build pages out of javascript, something that is both impractical and ill-advised (in almost every situation). Moving forward, you should start building your pages in HTML and use javascript to tweak the page from that point.

To do this, you will want to replace document.write() with document.getElementById(). Lets look at an example:

You have the following HTML block:

<h1 id='welcome'></h1>

Now, to insert text into this block, we would do something like this:

var welcomeElement = document.getElementById('welcome');
welcomeElement.innerHTML = "This is my welcome message!";

There's many things you can do with elements once you have gotten them, but I'll leave that for a later experiment.


At this point, I'll leave you to learn how to update your code. If you get confused or stuck however, you can view my rendition of your code here:

http://jsfiddle.net/danthegoodman/v7gLE/

\$\endgroup\$
2
\$\begingroup\$
  1. variables names that are three letter abbreviations aren't helpful when you come back. Don't be concerned about the number of characters (within reason) for your names.

    teaOrCoffeeAnswer is easier to read or even drinkAnswer

  2. I'm surprised no-one has pointed this out but "somestring".toLowerCase() can help you heaps. (or .toUpperCase()) Its a good thing to try and find some built in functions if it seems like something that would be common.

    turns 
    
    if ((toc == "tea") || (toc == "Tea")) {
    
    } else if ((toc == "coffee") || (toc == "Coffee")) {
    
    }
    

    into

    if (toc == "tea"){
    
    } else if (toc == "coffee") {
    
    }
    

    I'd suggest something like:

    var drinkAnswer = prompt("What do you prefer? Tea or Coffee");
    drinkAnswer = (drinkAnswer || "").toLowerCase();
    if (drinkAnswer == "tea") {
    
    } else if (drinkAnswer == "coffee") {
    
    }
    

    (the drinkAnswer || "" means that you won't get a null reference exception.)

  3. parseInt() has a "hidden" feature. it turns any string beginning with "0" into an octal number (base 8). Assume your user always enters a decimal number and instead force the method to parse in decimal (base 10)

    parseInt(numberAsString, 10); 
    

    this will save a lot of headaches later.

\$\endgroup\$
3
  • \$\begingroup\$ On 3, I would in the end suggest using + to coerce an integer value instead of sending the base-10 into parseInt: var number = +inputFromUser; \$\endgroup\$
    – ANeves
    Commented Aug 2, 2012 at 9:00
  • 1
    \$\begingroup\$ @ANeves I personally don't find that very intuitive for a JavaScript learner to put in their "toolkit". It doesn't always act the way you expect. (e.g. +" ") \$\endgroup\$ Commented Aug 2, 2012 at 9:28
  • \$\begingroup\$ Oh. Scratch that, then, and back to parseInt(foo, 10). \$\endgroup\$
    – ANeves
    Commented Aug 2, 2012 at 9:30
0
\$\begingroup\$

Take a look at this - I modified and left a couple of comments. You're on the right path :)

function stristr (haystack, needle) {
    var pos = 0
    haystack += ''

    pos = haystack.toLowerCase().indexOf((needle + '').toLowerCase())
    if (pos >= 0) return haystack.substr(0, pos)
}

function prompter() {
    var toc, foc /* Define your variables up here, not in body */

    /* No need for empty if/else statements - if you need them in the future, 
     * use (stristr(toc) == "tea") for example. */
    toc = prompt("What do you prefer? Tea or Coffee")
    foc = prompt("What do you prefer? Facebook or MySpace")

    /* Let's add some really basic error checking */
    toc != "" ? toc = "like " + toc : toc = "don't like tea or coffee "
    foc != "" ? foc = " you like " + foc : foc = " you don't like Facebook or MySpace"

    /* <center> is deprecated :) */
    document.write("<h2 style='text-align:center'>So you " + toc + " and " + foc + ". That is awesome.</h2>")
}

function pickAColour() {
    /* 'fun' is not an appropriate descriptive variable name, lets change it to 'color' */
    var color = prompt("My favorite color is red. What is your favorite colour?")

    /* <center> is deprecated :) */
    document.write("<h2 style='text-align:center'>You like the colour " + color + " that is a nice colour</h2>")
}

function pickANumber() {
    var firstNumber, secondNumber, symbol, problem, answer

    /* Don't ask 'Do you like math?" as the user will then expect an input to answer that question */
    alert("Lets do some math.")
    pan = prompt("Please pick a number")
    nap = prompt("Please pick a second number")
    symbol = prompt("Please pick one of the following symbols +  -  *  /")

    /* Get rid of the parseInt calls and re-store and just set a problem string for later usage */
    problem = parseInt(pan) + " " + symbol + " " + parseInt(nap)

    /* Let's get an answer while we're at it */
    answer = eval(problem)

    /* Let's make life easier and get the symbol name via a switch statement */
    switch(symbol){
        case "+" : symbolWord = "addition"
            break
        case "-" : symbolWord = "subtraction"
            break
        case "*" : symbolWord = "multiplication"
            break
        case "/" : symbolWord = "division"
            break
    }

    alert ("You picked the " + symbolWord + " symbol")
    alert ("The math problem you chose was: " + problem)
    alert ("The answer to the problem you chose is " + answer)
}

function run() {
    var name = prompt("What is your name?")
    document.write("<h1><center>Welcome to this special JavaScript page " + name + "</center></h1>")
    prompter()
    pickAColour()
    pickANumber()
    document.write("<center>Thank You for visting this page</center>")
}

run()

.

                         ==--==--==--== EDIT EDIT EDIT ==--==--==--==

To answer a comment below - true - semicolons should be used as they are in many other languages. I guess I've been spending too much time with python lately :)

As Danny said - it is indeed a Ternary Operator (http://en.wikipedia.org/wiki/Ternary_operation) and its basically a short hand if/else statement. Like this:

trueOrFalseStatementHere ? ifTrueDoThis : ifFalseDoThis 

example:

(1 + 1 == 2) ? print "1 plus 1 is 2" : print "1 plus 1 is not 2" 

For your question on the stristr function - its basically a replica of the PHP stristr function.

function stristr (haystack, needle) {
    var pos = 0
    haystack += ''

    pos = haystack.toLowerCase().indexOf((needle + '').toLowerCase())
    if (pos >= 0) return haystack.substr(0, pos)
}

It does indeed turn everything to lower case - that way you don't have to check the user input for every single case...for example, with your old method, if the user entered "coFFee", it would not pick it up since you were only checking for "Coffee" and "coffee"...but with this stristr function, the user input "coFFee" would become "coffee" and you only have to check for 1 case: "coffee". See the PHP manual's definition of stristr for a more accurate explanation http://php.net/manual/en/function.stristr.php.

With your method, you would have to check for 9 variations of "tea"

\$\endgroup\$
15
  • 4
    \$\begingroup\$ I personally find better to use semicolons always as it has a big impression on many languages like Java or C# etc. \$\endgroup\$ Commented Jul 18, 2012 at 20:28
  • 1
    \$\begingroup\$ That's called the Terenary Operator and is common for short conditional statements. That section could be expanded to this: if (toc != "") { toc = "like " + toc } else { toc = "don't like tea or coffee " } \$\endgroup\$ Commented Jul 19, 2012 at 6:23
  • 3
    \$\begingroup\$ @YasinOkumus Even in JavaScript, if you don't use semicolons, some statements won't get parsed the way you expected. I think you should always use semicolons because of that (one less pitfall to worry about). \$\endgroup\$
    – svick
    Commented Jul 19, 2012 at 7:55
  • 1
    \$\begingroup\$ @svick Thank you very much. I'll keep it in mind. \$\endgroup\$ Commented Jul 19, 2012 at 9:57
  • 1
    \$\begingroup\$ Generally, it's good practice to avoid using the ternary operator unless assigning a value. There's a lot of debate about this, but see this StackOverflow thread for some interesting arguments. \$\endgroup\$ Commented Jul 19, 2012 at 20:18

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.