Jump to content

Douglas Crockford video question


Recommended Posts

Hello everyone,I was just watching the Douglas Crockford JavasScript videos on yahoo(http://developer.yahoo.com/yui/theater/), specifically the ones labeled 'Douglas Crockford — The JavaScript Programming Language'. In the first video, near the end, around the 28:23 time mark, he talks about the logical && operator. He says, "If the first operand is truthy then the result is the second operand, else the result is the first operand." He lost me there. Can anyone tell me what He mean't?Is he referring to a basic if else statment like this:

if (a == 5 && b == 2) { execute code}else {execute code}

If I'm not mistaken, does the above mean that BOTH have to be true in order to get into the 'if' and if both aren't true, then it will go into the 'else'? Is He talking about this?ORIs He talking about:

variable = a==5 && b==2;

which I gather would mean: If a is equal to 5 and b is qual to 2, only if BOTH are true, variable will then be set to the second operand, which is 2? Is this what he mean't? If the above were OR ( || ), variable will then be set to ONE that is true, correct?Any input on this would greatly be appreciated! Thank you! :)

Link to post
Share on other sites

If the first operand is truthy, evaluation passes to the second operand, and it is the Boolean value of the second operand (true or false) that becomes the value of the whole expression.If the first operand is not truthy, the second operand is never evaluated. The Boolean value of the first operand (which of course is false) becomes the value of the whole expression.

Edited by Deirdre's Dad
Link to post
Share on other sites

because with &&, both conditions have to evaluate to true. If they are both true, it doesn't really matter which one you get the truthiness back from... but! If the second one is false, then the whole condition fails and you want the false value to be returned so you can handle your conditional appropriately. And just to clarify, only boolean values are being returned.

Link to post
Share on other sites

I can't figure out which video you mean, but I can imagine a context where you might NEED to know the way logical operators cause things to happen or not happen.Say you have 2 functions. Each one changes the state of the app, and each one returns a value that can be evaluated true or false. The functions are called orcEatsPoison and incrementArmorPoints. You could write a statement like this:

if (orcEatsPoison() && incrementArmorPoints() ) { . . .

One thing you need to know is that if orcEatsPoison returns false, incrementArmorPoints will not be executed. It doesn't matter what value incrementArmorPoints might have returned. It just won't run.It it absolutely HAS to run, you'll need to execute it separately before evaluating its return value:

var orcAtePoison = orcEatsPoison();var newArmorPoints = incrementArmorPoints();if (orcAtePoison && newArmorPoints ) { . . .

This makes sure that both functions get executed.

Edited by Deirdre's Dad
Link to post
Share on other sites
If the first operand is not truthy, the second operand is never evaluated. The Boolean value of the first operand (which of course is false) becomes the value of the whole expression.
That's referred to as short-circuiting the condition. As soon as the first expression that will make the entire condition either true or false is found, evaluation of the rest of the condition stops. Not all languages support that, some languages always evaluate every expression in the condition. For an OR condition, if the first expression is true then the condition is short-circuited and the rest of the condition is not evaluated, since the first expression is true then even if all of the other ones are false the condition will still be true. With AND, instead of true short-circuiting the condition, false does. In an AND condition, if any false value is found the condition stops being processed, even if all of the others are true the condition will still be false.PHP also supports that, which is why things like this work:mysql_query($sql) or exit(mysql_error())If that was not short-circuited, the exit would always execute regardless of the return value of mysql_query. Since PHP supports short-circuiting conditions, the exit will only be executed if mysql_query returns false.
Link to post
Share on other sites

Deirdre's Dad: If you go to this link http://developer.yahoo.com/yui/theater/ and scroll down til you see "Douglas Crockford — The JavaScript Programming Language", it is the first video out of 4. It's near the end of the video. I think I got it now and always basically understood the && operator, but what confused me is this expression:variable = a==5 && b==2;In JavaScript, I wasn't aware you're able to do this. Is this somewhat of a short-hand way to assign true or false to variable? So to clarify, BOTH operands have to be TRUE in order for variable to be set to TRUE. But if the first operand is TRUE and the second one is not, then variable will be set to false, correct?I have seen this kind of expression in many JavaScript tutorials and it always confused me. I just wasn't aware you can assign true or false to a variable like that in JavaScript.

Link to post
Share on other sites

Start with this:a==5 && b==2It's a logical expression. Because each side of the expression uses a comparison operator, the expression as a whole will be evaluated as true or false. The context doesn't really matter. You are accustomed to seeing it look like this:if (a==5 && b==2) . . .But the expression still is being evaluated as true or false. Because the program can make that happen, it can also assign the true or false value to a variable:var myBool = a==5 && b==2;Sometimes I write that like this to make it easier to read:var myBool = (a==5 && b==2);The parentheses change nothing.

Edited by Deirdre's Dad
Link to post
Share on other sites

Okay, I read the transcript of the video. He's talking about some cool shortcuts you can use. Here's a very common example. We'll create an event handler. Standards-compliant browsers pass an event handler an event object. Old versions of IE don't. The event object is global. So we have to figure out what we've got. Most of my event handlers look like this:

element.onclick = function (e) {   e = e || window.event;   // other statements}

A Standards-compliant browser will pass an event object into the local variable e. Old versions of IE won't. So e will be undefined (falsey). What the first statement is saying is thisIf e is truthy, assign the value of e to e (the equivalent of doing nothing). If e is falsey, assign the value of window.event to e.So that's one cool use of a logical operator. Here's another.

function func (param) {   param && goFish();}

Which is a shortcut way of doing this:

function func (param) {   if (param) {	  goFish();   }}

You see a lot of this stuff in Perl, and it's beginning to get more popular in JavaScript.

Link to post
Share on other sites

You can also assign default values to parameters a similar way:

function func (param) {   param = param || {};}

You may look at that and assume that param will end up being true or false, but that works because of what Crockford explains:

If the first operand is truthy then the result is the second operand, else the result is the first operand.
"The result is the second operand". If param is false or undefined, then it will get set to an empty object, or else it will keep whatever value it has.
Link to post
Share on other sites
If param is false or undefined, then it will get set to an empty object, or else it will keep whatever value it has.
You mean if param evaluates to false. It will be set to an empty object if param is an empty string, 0, false, null, or undefined.
Link to post
Share on other sites

Thanks everyone and especially to Deirdre's Dad for the responses! :)You were right, I am/was accustomed to see it like this: if (a==5 && b==2) . . .There is something you brought up that I also questioned before and it's this:

element.onclick = function (e) {   e = e || window.event;   // other statements}

For standards-compliant browser, is the letter 'e' the standard way to pass the event? Could we also have passed it as the word 'event' too?So for the above, what it's doing is checking if it's a browser like firefox OR Internet Explorer(window.event), and then assigning the event to 'e'?Again, thanks!

Link to post
Share on other sites

The variable does not have to be named e. But a lot of developers do that. Like using i as the counter variable in a for-loop.The function expects an argument to be passed into the variable e. Firefox and all the standards-compliant browsers will do this. It will be an event object.e || window.event first tests to see if e is "truthy," which in this context means "is it defined." In a standards-compliant browser, it will be. In that case, the value of e is assigned to e. That may sound inefficient, but the interpreter understands that nothing is really happening. In old IE versions, e will not be defined. (IE will not pass an argument.) So e will NOT be "truthy." Since the logical operator is an OR, evaluation passes to the next operand, which is window.event. If window.event is undefined, we are SOL. Fortunately, there is a little order to the universe, so it will be defined. The expression returns the value of window.event and assigns it to e.Let's make this real easy.

var x = false || 7;

The right side of the statement is evaluated first. The first operand of the logical expression is evaluated first. It is false. Since the operator is OR, evaluation passes to the second operand. The value of the second operand (doesn't matter what it is) becomes the value of the expression, so 7 is assigned to the left side of the statement.

Link to post
Share on other sites
Like using i as the counter variable in a for-loop.
Just out of curiosity, what is the logic behind that? Is there a reason most developers use i? I tend to use x...
Link to post
Share on other sites
I've always assumed it stood for something like "iterate."
actually, since for loops are most commonly used when working with array's, I would assume it stands for index
Link to post
Share on other sites

Too much time on my hands. I've been wading through ancient manuals for BASIC (1964), IAL/ALGOL (1958), and FORTRAN (1956).One thing to note in all these languages is that the elements of an array (and its equivalents; BASIC calls it a list) are referenced by a "subscript." I never saw the word index used in a discussion of an array.BASIC uses i in some for-loop examples, x in other examples.The IAL and FORTRAN manuals use i frequently when identifying an integer.IAL has a sophisticated for-loop, a lot like C. Several variables are used in the examples, especially x and i. Words that might suggest an i are not present. BUT the abstract of the whole document refers to "iterative procedures." This seems suggestive, but not definitive.FORTRAN, the oldest of the 3, has a DO loop that works like a for-loop (not like a C-style do-while loop). The description uses i for the counter variable, consistent with earlier examples. It also makes it clear that the counter variable is a fixed-point number (integer). So integer is an excellent candidate here. BUT in discussing the parts of a DO-loop initializing statement, the counter variable is referred to as the index, and it is called that several times. If i were not used throughout the manual to reference integers generally, I'd call that pretty definitive.I'm not researching back any further today. :) I make the commonplace assumption that languages build on each other. So far, it's tempting to say that i in discussions of for-loops does refer to index. This would be a counting index, though, not an array index. But the pervasive use of i to mean an integer leads me to think it happened this way:1. i was chosen because the first counters were integers, and i was the commonly used as an identifier for an integer2. the continuing use of i was reinforced by the idea that i was a counting index3. it may also have been reinforced in later years by the growing tendency to use the word index in place of subscript when referring to arrays, and the close association of arrays with for-loops.I'm sure I've missed something, but these sound like reasonable hypotheses to begin with.

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...