Intro to JS question

I guess technically that should have been “You did something mathy with not-numbers”, but… you get the point.

1 Like

thank you :slight_smile:

functions i will do later

having trouble with

kindly go through it slow and clear for me… a bit of a head scratcher for me :slight_smile:

So its analogy time again.

This time, you’re working in a tax office. Your job is to sum up a person’s income and figure out how much tax they owe. Nice and simple.

You get a big fat folder, as you usually do, with a bunch of financial records. Wonderful. You start adding things up.

First piece of paper says 13. You start your total with 13.
Next piece of paper says 24. You add 24 and come to 37.
The next piece of paper says potato.

… okay, is your total 37? What’s the value of “potato”? It was on a financial form, so it must be something, but… you dont know what.

undefined is your potato.

You can’t go back and ask the customer what it means, and the company expects you to generate SOMETHING from this result…so you write down “There is a problem here” and send the folder to your supervisor.

NaN is your “there is a problem here.”

2 Likes

It’s wider than that. Zero divided by zero is also NaN.

So maybe it’s “you asked me to do something that I should should result in a Number, but I don’t know how to make it into a number. Instead I’ll say that whatever the result is, it’s Not A Number (NaN)”

2 Likes

There are definitely more ways to generate NaN (parseInt("potato") will do so as well. I seem to have a potato thing going on this morning. shrug). The relationship of coercion with undefined is this particular circumstance, but there are many others.

2 Likes

And just because I can, to tie the analogy back to the rest of the current inquiry…

Same situation. New folder. Excellent. Hopefully no potatoes this time, just lots of numbers. Let’s see.

First piece of paper says 7. You start your total with 7.
Next piece of paper says 15. You add 15 and come to 22.
The next piece of paper says goose egg.

You chuckle to yourself a little bit, probably make a little note on a sticky that someone should tell the customer that’s not a proper way to fill out the form (noone reads your sticky notes, but you feel better about yourself), add a 0 to your total, because thats what goose egg means in this context, and go on in your summing up.

null is your goose egg.

1 Like

ok

is my potato undefined because it has not been give a value yet?

is that correct for your analogy…

is there another lesson / theme you are trying to get across to me? what?

if i am right, let me now and congratulate my skills :slight_smile:

if not, kindly explain :frowning:

null basically means 0, yes? absence of value?

BTW

its funny! i had potato French fries today!

Pretty much.
it’s undefined because you dont know if it has a value. Or if it ever will; or if it does, you dont know what it is.

A function that returns nothing (often called a void function in other languages) will actually ‘return’ undefined in Javascript. So will any sort of variable declaration (give it a try - put let x = 1 into your console, hit enter, and see what the console returns to you). What it’s saying is “I’ve done what you’ve asked but have nothing to give you in response”.

undefined can crop up in unexpected places. Thats why Javascript says that it wont make undefined become 0 in math - it could be giving you false information if it did.

null, on the other hand, is a keyword that means “no value”. Javascript will never generate null itself, so it’s safe for it to assume that the user created it to mean no value, which, when used as a number, is 0.

null is intentional. undefined might not be (and usually isn’t if you’re looking for a value).

(and for any javascript nerds that are reading this, yes, there are a LOT more nerdy specifics about the differences between null and undefined, but those are things most expert programmers never need to think about, let alone a newcomer.)

1 Like

i am not at functions and returns yet

should i wait to learn that first?

if not… i am having trouble here, now :frowning:

i have seen another resource

The undefined property indicates that a variable has not been assigned a value, or not declared at all.

so sorry if this sounds stupid, how does the above quote work with what your telling me?

yes, i ran let x = 1 and it came back undefined

why?

i appreciate your patience

So… a few things to unpack there.

For the moment, leave it simply at the following: Whenever you call a function, whether it be one of your own design or one of Javascript’s own (alert, console.log, etc), something has to tell the browser “I’m done with that now.”, so that the engine can continue on. Optionally, the function can return a value - if you call Math.min, you expect a value - the minimum value of whatever you called it with. But for those functions that DONT have an obvious return value, the browser still needs to be told i’m done. And so, when there’s nothing to return, the engine will return undefined in the slot where the value would be - because, quite literally, there was no return defined.

I… dont like that definition. If a variable has not been declared at all, you won’t get undefined, you’ll get an Error on your code, because you’re trying to Reference an undeclared variable. (Which is why it’s a ReferenceError).

That said, if you declare a variable without a value, which you can do:
let x
x has the “value” undefined until you give it a value.

Because that’s Javascript telling you “Okay, i’ve done that. It didnt give me a value to give back to you. Now what?”

Maybe in this whole discussion the most important point was never mentioned.

If you work with undefined, you do something wrong. Undefined is nothing you have to deal with. In 99% of the cases when you get an undefined, this is caused by a programming error.

So if you are really new to programming, don’t bother about undefined too much. It’s good to know that there is something like that but it is not necessary to understand the whole background.

i read it, slept on it, and now get it!

many thanks!

backing up a bit

let a = 0; // declare the variable a and assign the value of 0<< 0
false && (a = 1); // (a = 1) is truthy, but it won't be evaluated, since the first operand is false<< false
a // the value of a is still 0<< 0
false || (a = 1); // this will evaluate both operands, so a will be assigned the value of 1, which is returned<< 1


please walk me through each step of this concept

So this is demonstrating what is called short-circuiting. Its based off logical principles.

In general, code evaluates left-to-right, while following order of precedence (like you do for math; multiplication before addition, etc).

&& means a logical AND; if both the thing on the left and the right are true, then the answer is true, otherwise, its false.

short-circuiting is a byproduct of efficiency that can be manipulated by programmers. It follows this logic (for AND):
Evaluate the thing on the left.
It was false.
No matter what is on the right, I already know the answer to my AND is false, so i can skip the right side and just return false.

(the same, unsurprisingly, can be followed for logical OR (||), just replace false with true.)

So lets look at the code, line by line. Theres at least one error in there too… so if this codeblock came out of the sitepoint book, please lets us know where so it can get corrected :wink:

let a = 0; // declare the variable a and assign the value of 0<< 0
So a simple variable declaration. Pretty self explanitory, but heres where the error exists - as we have seen above, variable declarations return undefined, not the value of the variable. This line should have said
let a = 0; // declare the variable a and assign the value of 0<< undefined
A simple mistake to make, but worth noting, given our earlier discussion, and a good example of where undefined can pop up where a programmer isn’t suspecting if they’re not super careful.

false && (a = 1); // (a = 1) is truthy, but it won't be evaluated, since the first operand is false<< false
Okay so here’s the meat and potatoes of the short circuit.
The left side of the operand is false. Nice and simple to evaluate that. Javascript then knows it can skip the right side, and move on, returning false.
If it had evaluated the right side, it would have set a to 1, but it didnt.

a // the value of a is still 0<< 0
This is just proving the above by printing out the value of a again.

false || (a = 1); // this will evaluate both operands, so a will be assigned the value of 1, which is returned<< 1
So… for contradiction-example reasons, they switch to an OR. probably not the example i would have lead with (true && (a = 1) would have been better IMHO), but we’ll roll with it.
OR returns true if either of its operands is true. Otherwise it returns false.
Well, the left side of the operand is false. What does that tell us about our OR…? nothing yet. The right side could be true, in which case the result is true, or it could be false, in which case the result is false.
So we have to evaluate the right hand side, because the outcome is still unknown.
We evaluate the right side, and set a to 1. Note that when you’re setting the value of an already declared variable, it returns the new value of the variable, so we get a 1 on the right hand side.
1 (or in fact, any number that isnt 0 or NaN), when coerced to a boolean, is “truthy” - meaning it counts as true, even though its not a boolean true. This “truthyness” is applied to many things - a string is truthy as long as its not the empty string, etc.

IMO, the example should also have echoed the value of the variable out one last time to prove itself completely, but it’s shown it sort of with the output of the last line.

So the OR is now true. But it returned a 1, not true. Why?
While you might think that a logical comparator like AND or OR should return a boolean, what it actually returns is the last value it evaluated that satisfied the operand. So;

2 && 1 << 1
0 && 3 << 0
0 && false << 0 //(Because the 0 short circuited the logic, the false was never evaluated)
"pie" && 1 << 1 //You can mix types in a logical check, but the result will be the type of the last value evaluated.

One of the most common uses of this is using OR for checking for empty values:

"" || "defaultstring" << "defaultstring"

consider if the left side was a variable that had been generated by a user.

myinputvar || "defaultstring" << ???

It might be empty or otherwise false-y. That could be bad for our code. So we use the return principle to set a default value to prevent bad things happening. Conversely, if the user HAS entered a value, then the left side of the OR is truthy, and we shortcircuit, preventing the default from overwriting what the user has input.

wow!

a lot there…

i am happy to say i understand!

i get lost at

kindly re-phrase or clarify (or both)

i appreciate you going through it slow!

Truthyness - the quality of any given thing - a string, a number, an object, etc. when evaluated as a boolean (true/false).

0 is considered “falsey” - it’s treated as a false.
1 is considered “truthy” - it’s treated as a true.
“” is falsey
“pie” is truthy
null, undefined, and NaN are all considered falsey.

Oddballs are an empty array ([]) or an empty object ({}). In many languages, those would be considered falsey. Javascript considers them truthy.

Which part of the second block are you having trouble with?

i get a Boolean (true / false)

how is a string, a number, an object “evaluated” as a Boolean

got it

this helped

“coerced” means making a type the same to another type, yes?

how does a Boolean count as true, even though its not a boolean true. help here

why is the OR now true?

how is OR working here?

2 && 1 << 1
0 && 3 << 0
0 && false << 0 //(Because the 0 short circuited the logic, the false was never evaluated)
“pie” && 1 << 1 //You can mix types in a logical check, but the result will be the type of the last value evaluated.

ok.

lost here

so sorry… i dont get this

0 is a falsey which negates the && at the start

and the final “pie” example is <<1 because 1is the last type… so it evaluates a value of 1

please, what does “evaluate” mean here?

lost here.

why?

what bad things may happen here?

what “value” are we talking about? what is being described here?

THANK YOU!

So i think this is a case where there’s just a couple of key concepts that once they breakthrough, the rest of this sort of drops into place.

So when you tell your code you want to AND or OR something, the code needs to be able to understand whether things are true or false. Because Booleans exist in a world of true and false, nothing else. If you go back to our previous analogy for undefined and null, we had no idea what the value of “potato” was as a number, but we could translate “goose egg” into a 0, because we understood that it was another way of saying 0. In programming speak, we coerced the string “goose egg” into the number 0.

coercion is the (usually implicit) behavior of converting a value of one data type into another when it’s needed for an operation to work. It’s why "2" + 2 will get you a “22” - the engine coerces the number 2 into a string so that it can concatenate them. Note that implicit coercion does not change the original thing - if you coerce a variable holding a number into a string to do some concatenation, on the next line, that variable is still holding a number.

Of course, in order to do coercion, the engine must have some sort of rules for defining “When coercing from typeA to typeB, do the following…”. Javascript does have that, though for booleans it tends to be more a case of “these specific things are false, everything else is true”

So we’re concerned about AND or OR. Both sides of the operand must be boolean-able - or have a value in boolean that can be coerced to. It doesnt matter that it’s not ACTUALLY a boolean, and we’re not changing any variables to do this, we just need, for that specific moment, to understand the boolean nature (“truthyness”) of whatever’s on the left, and potentially what’s on the right.

https://dorey.github.io/JavaScript-Equality-Table/#if-statement

This page shows nicely some values of things that evaluate/coerce as true (green boxes) and false (white boxes).

So the left side of the OR is false. Simple. But because its an OR, we dont know what the overall result is yet. So we evaluate the right side.

The right side is a statement: (a = 1). Javascript will execute the statement, because it needs to know the result (imagine if the statement was doThisIncrediblyComplexFunction() - you wouldnt know the value of it until you’d… run the function).
So it runs a = 1. If you stick that into your console (after declaring a), you’ll see that a = 1 << 1 - it returned the new value of the variable.
Effectively then, the OR now reads as false || 1 . This is our actual values going into the OR.

We now can evaluate the OR. To do so, we must coerce our values for the comparison.
false is already a boolean. Nothing to do there.
1, when coerced to a boolean, is truthy.
So in our coerced world, the OR is false || true(thy), which is an overall true.
Javascript then determines that it should return one of the values that was true (because the result was true). It only has one option in this case - the value on the right. Which, when we look at the actual values, we return a 1.

If you get the concept of truthy and coercion, go back and look at the previous post and see if it makes more sense now.

ok. now my turn to be slow :slight_smile:

this is because when i code AND it needs to know both sides are true and when i code OR it needs to know one side is true

and Booleans are only true or false…

so AND depends on a Boolean and OR depends on a Boolean

am i correct?

before i progress, i will take a look back at he code you mentioned… potatoes and goose eggs

now, first

assuming this is appropriate, why is a potato undefined and goose egg null?

yes, i looked at this discussion prior

* ***undefined*** is a variable that refers to something that doesn't exist, and the variable isn't defined to be anything.
* ***null*** is a variable that is *defined* but is missing a value.

potato is undefined because it has not been assigned a value

goose egg is null because you gave its value as 0… some where i thought i saw null is given into the code by the coder… JavaScript doesn’t do that itself

Yes. AND and OR are Logical operators. Logical operators operate on True and False (aka Boolean).

Yeah, i’m trying really not to dive too deeply, but there is a certain amount of depth that is needed to answer the question.

A potato is undefined because you cant look at it and say “Oh, thats a 7.” or “That’s a 1” when trying to put it into a number context (when you are coercing it to a number. See how all the concepts blend together?). A goose egg, colloquial as it is, can be looked at and said “That’s a 0.” in a number context. (This example may not be as clear if you’re not aware that “goose egg” is a colloquial term for a 0. I apologise if there’s confusion.)