Entries:
Comments:
Posts:

Loading User Information from Channel 9

Something went wrong getting user information from Channel 9

Latest Achievement:

Loading User Information from MSDN

Something went wrong getting user information from MSDN

Visual Studio Achievements

Latest Achievement:

Loading Visual Studio Achievements

Something went wrong getting the Visual Studio Achievements

Conditional Logic in JavaScript - 06

Download

Right click “Save as…”

In this lesson, Bob demonstrates the use of the if ... else if statement, the ternary (or conditional) operator, and the case ... select statements. Along the way, we learn about the && and || operators as well as the Date object in JavaScript.

Tag:

Follow the Discussion

  • PeterNLPeterNL

    Nice psychedelic shirt Bob!

  • @PeterNL: Yeah, bad choice.  I'll never wear that one again on camera.  Sad

  • riclfriclf

    in my current language Objective-C the logical And operator in an If statement is a single &

    You showed it as a && which was a surprise. Is the single & never used? Thanks. Great videos!

    -Ric

  • @riclf: The single & is not used often -- at least not in the type of coding *I* do often ... 

    http://msdn.microsoft.com/en-us/library/sbf85k1c(v=vs.80).aspx

  • David HartiganDavid Hartigan

    Hi Bob,

    Thanks for making these videos! They are very easy to follow along with :) I did find the switch statement was a little bit unexplained at first but after re-watching it I've found it was rather simple.

    I am looking at making a start with writing Windows 8 Store Apps using Visual Studio Express 2012 and found that JavaScript is supported and with your help, easy to learn :)

    I have shared a link to these videos to a few of my friends.

    Thanks for the awesome videos, I look forward to watching the rest of this series!

  • @David Hartigan: Thanks David!  Glad they help!

  • If you look into the shirt long enough, you'll see a sailboat!

  • Congrats!  That is the single funniest comment we've received on any of these videos.  Smiley

    In retrospect, the wardrobe choice was ill-fated.

  • washerguy1washerguy1

    Hi Bob tanks again for the lessons. I had a problem when I pasted the code onto the validator page it spread out all over how do you word wrap it the way you did when you hit Ctrl c , Ctrl v into the validator.nu/sorry if this is a dumb question. John

  • @washerguy1: Hmm ... I don't think I did anything special.  Have you made sure to turn auto-wrap OFF in Notepad?  Are you using tabs or spaces?  Those are the only things I can think of that would affect it.

  • ThomasThomas

    @riclf In a c based languages (c, c++, java, objective-c, c#) & is the 'bitwise and' and && is the 'logical and', so condA & condB will also work, but the important difference is that there is no short circuit logic in the bitwise operators.

    @BobTaylor Actually most script languages support some notion of 'falsey' or 'truthey'. For example in python an empty list will evaluate as a false condition. In a sense so do most of the c based languages because a lot of things implicitly convert to bool. The messed up part with the '==' operator in javascript is that the conversion is done before the comparison.

  • KyleKyle

    I would first like to say thank you for putting these videos together. I am inching my way towards taking my first crack at some freelance work and these videos have helped out a lot with connecting the dots.

    I just wanted to see if you and/or anyone else was having an issue with the progress bar on the videos. It is not a big deal, but mine seem to stop progressing after multiple pause/restart actions.

  • @Kyle: Thanks Kyle.  As far as the player ... yeah, I noticed that too.  That would be good feedback for Microsoft -- and they don't monitor these threads like I do ... you may want to click the Feedback link (below, footer) and tell them so they can look into it.  Best wishes!

  • Robin GrossRobin Gross

    Okay, this is where it starts to not make sense to me. In the last example, where you're trying to determine the time of day and write a message to the html page -- I have a bunch of questions about this:
    1) Just to verify -- the Date function grabs the date and time stamp at any given moment, right? So the value that comes back from the Date function is put into the rightNow variable? Then you have to parse that value to find just the value of the hour, which is then put into the currentHour variable?
    2) Why do you do the "switch" on the value "true"? Why wouldn't you do the switch on currentHour? Isn't that what you're testing the value of?

  • Hi Robin ... sorry for the delay.

    re: Date() ... Yes:

    var rightNow = new Date();
    var currentHour = rightNow.getHours();

    In that code snippet, Date() grabs the current date and time in the form of a Date object.  See this for details, including reference about the getHours() (and other similar methods):

    https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date

    re: switch ... this is a trickier one ... honestly?  I probably should have chosen an if statement instead.  I think I wanted to explain the switch statement and show and advanced case.  As I wrote to you in our email exchange (that others didn't see) it's a stylistic choice.  

    In this advanced (perhaps even absurd) example, I'm testing the value of true to find a match.  It's a backwards notion ... again, "just because you can doesn't mean you should".  I probably shouldn't have done that if it confuses people ... but you obviously CAN do it.  In this case, prefer if.

  • Mr. Tabor,

       Been writing code for 6 years. First in high school and now in college. NEVER through to do a switch statement on "true". Blew my mind. Fantastic idea!

       These videos are amazing by the way. Been helping me out a ton with my capstone graduation project.

     

    -Zack

  • @zwarburg: Hi Zack, thanks ... I don't know if I would recommend that little trick other than to learn what is possible.  Smiley  I'd stick with an if..else.  Good luck on your project!

  • LutyaLutya

    Hi Bob,

    New to JS, thanks for doing these. I was using code academy before but this is more my pace. Two quick questions:

    1. Why do you use the break in the switch statement?
    2. I can't seem to get my code to work, even though it seems to match yours perfectly. Any suggections?

    <!DOCTYPE html>
    <html>
    <head>
    <title>6. Conditional Logic in JavaScript</title>
    <script type="text/javascript">
    var rightNow = new Date();
    var currentHour = rightNow.getHours();
    switch(true) {
    case (currentHour > 8 && currentHour < 12):
    document.write("Morning, sunshine.");
    break;
    case (currentHour === 12):
    document.write("Lunch Time!");
    break;
    case (currentHour > 12 && currentHour < 18):
    document.write("Fight the urge to nap!");
    break;
    deafault:
    document.write("You better go to bed soon!");
    break;
    }
    </script>
    </head>
    <body>
    <h1>6. Conditional Logic in JavaScript</h1>
    </body>
    </html>

  • @Lutya: You spelled default as deafault  Smiley

  • RachidRachid

    I just wanna thank you for your lessons, they make javascript look so easy and also wanna thank you for your time doing this. I feel like I knew javascript for along time.

  • @BobTabor
    Sir You are great... !
    I'm following along this series and I hope I'd surprise my class mates with my new JS , HTML5 & CSS3 Skills Smiley
    I'd even try to give MCP test for html5 !
    Thank You... your videos helps me alot...
    TBH the words arent enough to Thank You !

  • AndrewAndrew

    Hi, Bob! I have a question. What's the main difference between "==" and "===". Is the only difference is checking for the veriable type? I guess you spoke about that in a video, but I just missed that point. Thanks in advance!

  • baerspectivebaerspective

    how my code see below is working? i thought it was a fluke so tested first: === 24 to get an alert of "equal" then tested with === 22 to receive alert "not equal" yet i am not using: var myResult = '': myResult ...etc



    this is how i did mine:
    var myResult = (someValue === 22) ? "equal" : "not equal";
    alert(myResult);

  • Thanks from me too. Any Red Dwarf fan is alright with me.

    I'm off to play pool with planets.

  • Hi, first of all, thank you for the videos.
    I have just a question related to the developer tool. When I run the webpage, I see a warning of type:

    HTML1512

    "Unmatched end tag."

    and other

    HTML1514

    "Extra "<body>" tag found. Only one "<body>" tag should exist per document."

     

    It is the same warning when I run the code you provide. I could find that it only appears (in this case) if I use de "default" section in the switch.

    Why does this happen?


    Thank you, again Smiley

     

  • Clint RutkasClint I'm a "developer"

    @insanespeech: I would need to see your full mark-up

  • @Clint: Thank you Smiley
    Here you can find the code http://pastebin.com/jiArPetn

    As I said, after removing the "default" case in the switch, this warning doesn't appear. It's quite confusing ...

    In addition, I'm using IE 10.

  • Clint RutkasClint I'm a "developer"

    @insanespeech: In IE 10, i'm not seeing a warning being thrown from what you put on paste bin.  The code there looks fine.

  • @Clint:Thank you for the answer. 
    I don't know then, why I see the warnings...
    http://img843.imageshack.us/img843/6343/n9w2.jpg

    But ok, the code is really simpe, so maybe it is a strange behaviour of ie10 :m

  • Clint RutkasClint I'm a "developer"

    @insanespeech: ok, so what is happening is you are injecting HTML into the webpage RIGHT at that line since this isn't happening at onload or document ready.  IE and other modern web browsers are resilient enough to know that "hey, something isn't right here, lets go try to correct this" and that is why the DOM looks correct when you inspect it but in reality, you injected the line at the wrong spot.  Moving the script tag outside of the head tag will correct that warning.

    JavaScript and HTML can get tricky at times with stuff like that.

  • @Clint:Thank you very much. I could test it, and of course you're right. If I write the script inside a different tag, I see no warnings.

    So the problem seems to be I shouldn't use "document.write" inside the head tag ... ok ok Smiley

  • Hi gentlemen and ladies. Thanks Bob for valuable videos.
    I'm about to become a developer and this my first programming language.

    So far, I understand pretty much everything. However I luck the knowledge in CSS/HTML.
    Should I start with lessons CSS/HTML5 first?

  • @Asenchuk: Yes, if not all of them, then at least the first several.  Ultimately, you will want to watch them all, but only the basics of HTML / CSS are required for this JavaScript course.  Good luck!  You can do it!

  • I get interesting results in Console tab of IE 10.

    When I execute the code according to an example in the lesson:

    myResult = (false) ? "truthy" : "falsey"; 
    "falsey"
    //but if I switch "truthy" with "falsey"
    
    myResult = (false) ? "falsey" : "truthy"; 
    "truthy"
     

    The same with a rest of examples.

    It looks like what you write at the end of statement eventually returns as a result?

    Did I miss anything?

  • @Asenchuk: Unfortunately, I think you did miss something.  "truthy" and "falsey" are just literal string values.  I could have used "Bob" and "Clint" instead.  The important thing here is that this is a short cut for an if statement.  The expression between the opening and closing parenthesis ( ) is evaluated.  If the expression evaluates to true, then the first value (to the left of the colon : ) will be returned.  If the expression evaluates to false, then the second value (to the right of the colon : ) will be returned.  In this case, as you wrote "It looks like what you write at the end of statement eventually returns as a result?" ... because the expression is hard coded to FALSE!  If we hard code that to true:

    myResult = (true) ? "truthy" : "falsey";

    ... the first value (in this case, "truthy") would always be returned.  Perhaps the example is so mundane that it is easy to miss the point.  I would recommend re-watching that part of the video and listening to what I say there.  Good luck!

  • Thanks a lot! Now after your explanation everything makes sense to me in this video.

  • BDMerzBDMerz

    Love your videos. I have viewed all of the C# fundamentals and HTML fundamentals and they are really helping me with my new job. i am commenting now though because i am so delighted to see the Red Dwarf reference. That really made my afternoon.

    keep up the good work.

  • @BDMerz: Smeggin' awesome.   Tongue Out

  • DavidDavidDilley Keepin' On

    I am sure you have heard it all about the shirt, but I have to add that having grown up in the 60s, and I was certain I was having a flashback!

  • @DavidDilley: Yeah, poor fashion choice on that video.  Solid colors only from now on.  Big Smile

  • Amjath ShariefAmjath Sharief

    One example for understanding the difference between the conditional operators.

    var i=2;
    var j=3;
    var info_i=false;
    var info_j=false;

    if((info_i=i<20) || (info_j=j<20)) {
    alert("hi" + info_i + " " + info_j);
    }

    info_i=false;
    info_j=false;

    if((info_i=i<20) | (info_j=j<20)) {
    alert("hi" + info_i + " " + info_j);
    }

    info_i=false;
    info_j=false;

    if((info_i=i>20) && (info_j=j<20)) {
    alert("hi" + info_i + " " + info_j);
    }else {
    alert("hi_1" + info_i + " " + info_j);
    }

    info_i=false;
    info_j=false;

    if((info_i=i>20) & (info_j=j<20)) {
    alert("hi" + info_i + " " + info_j);
    }else {
    alert("hi_1" + info_i + " " + info_j);
    }

  • Clint RutkasClint I'm a "developer"

    @Amjath Sharief: while valid code, my opinion of setting variables inside of an if statement adds to poor readability.  It is too easy to glance at it and think it is doing check for equals rather than setting.

    Think long term when you or someone else looks at that code in 6 months after working on other things.  It is hard to instantly go "ok, I know what is going on"

  • ThaicarrotThaicarrot

    Hi,

    Thanks for great series but with HTML 5 you don't need to add type="text/javascript"

    It is optional

  • MadogMadog

    Love the videos Bob. You are one of the best educators on the net.
    I wish I had found this series sooner. It would have saved a lot of headaches.

  • Do you by any chance have a series on Google Script?

  • @chriswong: Probably not on a Microsoft website.  Wink

  • Hi Bob,

    The tutorial was too good.

    When I am trying to execute the if () code.

    I am getting exceptional error.

    var someValue = 24;
    var otherValue = 23;
    if (someValue > 30) {
    alert("first case");
    }
    else if (someValue === 30) {
    alert("second case");
    }
    else if (someValue === 25) {
    alert("third case");
    }
    else{
    alert("fourth case");
    }

    The Error is "Unable to attach to the process.  Another debugger might be attached to the process". After that I am getting the alert as fourth case.

    Please do the needful.

    Thanks & Regards

    Mahadevan

     

     

  • @Bob The above issue was solved.  I closed VisualStudio Express for web and again restarted it was working fine.

    Thanks & Regards

    Mahadevan

  • @karthicsrinika: Ok, good ... I was scratching my head on that one.  Smiley

  • Hi Bob,

    As I am new to javascript. Now I am creating login page with the current video.

    But I am not getting the result what I except.

    Here is my Code

    function chkpas() {
    var usrname = document.getElementById("txtUsername").value;
    var passwd = document.getElementById("txtpassword").value;
    if (usrname.length === 0 && passwd.length === 0) {
    alert("Please enter valid text");
    }
    else {
    usrname.value === "maha" && passwd.value ==="pass"
    alert("success");
    }
    }

    <div>
    <input type="text" id="txtUsername" placeholder="username" /><br/>
    <input type="password" id="txtpassword" placeholder="password" />
    </div>
    <div>
    <input type="button" id="btn" onclick="chkpas()" value="Submit" />
    <label id="sucsmsg">Messages</label>
    </div>

    I want to display success in the label.

    Please guide me whether the above code was correct.

    Thanks & Regards

    Mahadevan

     

  • Hi Bob,

    Again for this also I found the way.  Below is the code

    function chkpas() {
    var usrvalue = "maha";
    var usrpass = "pass";
    var usrname = document.getElementById("txtUsername").value;
    var passwd = document.getElementById("txtpassword").value;
    if (usrname.length == 0 && passwd.length == 0) {
    alert("Please enter valid text");
    return;
    }else if (txtUsername.value != usrvalue && txtpassword.value != usrpass)
    {
    alert("invalid");
    document.getElementById("sucsmsg").style.color = "red";
    return;
    } else (txtUsername.value == usrvalue && txtpassword.value == usrpass)
    {
    alert("Valid");
    document.getElementById("sucsmsg").style.color = "green";
    }
    }

    is that possible to reduce the number of line of the above code.

    Please guide me.

    Thanks & Regards

    Mahadevan

     

     

  • Hi bob,

    I am waiting for your reply.

    Please do the needful.

    Thanks & Regards

    Mahadevan

     

  • @karthicsrinika: Is there a way to shorten this?  Two answers ... first HTML5 has some of this built in and you can just set declarative properties of form elements to get it to work.  However, for more control you will want to use JavaScript.  The thing is ... you will probably, in practice, use a JavaScript library.  Most of them are based on jQuery (which you learn in an upcoming lesson).  Here's a good article about JavaScript libraries that make what you're trying to do really easy:

    https://www.codefellows.org/blogs/the-ten-best-javascript-libraries-for-form-validation-and-formatting

    So, to answer your question ... yes, you can make it shorter.  In practice, few people use "just JavaScript" ... I realize some do, but that's a small group.  Most rely on code written for others to take care of common things like what you're trying to do to save time and frustration.

    Good luck!

  • RabiaRabia

    its really enjoyable learning via your smile....

  • NajamNajam

    what is the difference between Null and undefined?

Remove this comment

Remove this thread

close

Comment on the Post

Already have a Channel 9 account? Please sign in