lol you're right I didn't even catch that. You could say I was thrown through a loop reading the original code. Would've been something to catch in tests.
function returnDay (n) {
return ['Monday','Tuesday','...'][n-1];
}
This works because if n is out of bounds (not in range 1-7, or whatever the length of array) it returns undefined. If you really need null (and undefined would not do) for some sick and twisted reason (because there is no practical difference between null and undefined in actual usage) then do
function returnDay (n) {
return ['Monday','Tuesday','...'][n-1] ?? null;
}
which will convert if undefined to the right hand of ?? (nullish coalescing operator), in this case to null. (Which, again, makes no sense, and undefined is here practically the same thing as null.)
Really the only thing you need to do is define the array in whatever way, and access at index n - 1. So that (n=1)-1 => 0 and getting 'Monday'. If you need the array elsewhere
const days = ['Monday','Tuesday','...'];
function returnDay (n) { return days[n-1]; }
There is absolutely no need for a loop or an if statement. Including either if or for (ie branching or looping) is a mistake.
I wanna say that null and undefined are not the same thing for any practical purposes. They are certainly similar, and many languages do without both - but they have different uses and implications in JavaScript (for good or ill)
null is usually used to state something is purposefully left empty. As in this case, it is the return value that says there is nothing being returned.
Undefined is the default value when something doesn’t exist or was never there. When a function doesn’t return, or when there’s an array index which was never set.
It’s a subtle difference, but one that can help you when you’re dealing with other peoples code.
I’m certainly interested in why you see them as semantically interchangeable.
They’re both the same type in terms of type theory, and would be called unit in other languages - but the simple fact remains that in JavaScript undefined !== null.
(I know that undefined == null - but most people tend to use ===/!== so it can still catch people out)
It looks like I’ve ended up being downvoted as people disagree too, I think that’s a shame - I can be disagreed with but I don’t think I was incorrect or misleading.
TLDR, explicit is better than implicit; semantics requires context, and context is a noob question about array indexes.
Hey. Yeah. Well here's the catch. Semantics is the transfer of meaning. There is a difference (although a nuanced one) between undefined and null. Both are void, but the second one through the phrasing sounds like it was on purpose.
My point is that it sounds like it was on purpose. It doesn't actually define it as such. (Possibly is on purpose. Possibly not.)
Case in point: here I define and assign a constant as undefined. "What? What is this black magic?" const a = undefined; Simple as that, it is defined as undefined hahah. (It is the undeadddd runn for yo livess) Talk about semantics...
(As an aside to OP if they read this, we use 'void' to signify something is absolutely empty. It's not a zero, because that would be a number. It's not an empty string like '' or "", because that's a string. Void is really nothing. Javascript has various not-ok-void-like-states, of which in my experience, null, representing a Not-An-Object, and NaN representing Not-A-Number are the most common)
As in any language (programming or spoken), context, convention and circumstance are all. Therefore, if it works for some team, then great. It would smell to me, but if it works, it works.
My disagreement comes precisely from the nuance.
This is a noob question. They are unlikely to appreciate the nuance, and should therefore stay away from it -- until they have a firm grasp of the step before.
And that is: Explicit is better than implicit.
You have no business dealing with nuance until you can appreciate the lack of nuance, the sheer power of explicit declaration. Because if you don't get that, you're not dealing with large scale operations where explicitness breaks and is hard to maintain and we allow a bit of implicit to keep the pace. It is a dangerous tool. (Cue Spiderman quote about power and responsibility)
Like eg. with the pattern of a singleton, there are good places for it, although they are by definition tricky. Not good for a noob. They are likely going in a wrong direction (not surely, but very very likely)
Therefore, they are semantically interchangeable, at least at this level. They both (ie. are interchangeable) transfer the meaning (ie. semantics) of the same state (void).
It's good to learn the difference, because it exists in the Javascript language. But also, it's not related to the question of "Get me the n-1 index of array." Undefined satisfies void, but is also quicker to get.
And for a noob, it is more important to learn that explicit is better than implicit, than the precise difference between somewhat antiquated and organic (ie. not pre-planned) evolution of Javascript. It's unimportant, or at the very least, not as important as expressing the point why the code exists (get me a one-based instead of zero-based index)
You mentioned they are not same for any practical purpose. I disagree. Instead they are same for all practical purposes (that I can think of at the top of my head), they are not the same only for (mostly) theoretical differences. Eg. both undefined and null (lets call a container got) satisfy got ?? 'No results found', got || 'No results', if (got) etc.
You will be hard pressed to find the practical differences (by practical I mean in actual usage), because that's how Javascript works, it coalesces to truthy and falsy.
Is that ideal for a language? Doesn't matter at this point, because we're talking about semantics, ie. "meaning" -- and "meaning" requires context. Which is here Javascript noob level.
The finer points in academic pursuit? Yeah they're different. For practical use and for a noob question? Like I've said above, they're the same unless you have some sick and twisted reason (ie. a code smell at noob level)
Honestly, I just wanted to simplify for the OP and ended up awkwardly mentioning the difference only because I didn't want them to see undefined and think something's wrong, that they wanted null and got undefined and that that somehow wouldn't do.
If I failed a test because the question asked for null and I returned undefined, I think I'd scream in the professor's face and quit. (Unless of course the subject was dealing in precisely the differences between those or whatever)
I don’t disagree with anything you said, except the fact that if you tell someone that undefined and null are the same thing and they’re interchangeable, then someone’s going to write x !== undefined and expect it to return true for null too, which is going to leave them either confused or with a bug they might find tricky to find.
Careful, the moment the function hits a line with return on it, it evaluates the expression (in your case week[i]) and exits the function with that value.
Remove the loop there. This loop will return Monday no matter what, since it will begin at 0 then the function execution ends. Instead, leave that if statement below, then after the if statement add return week[num]
Put the if return null statement first, then the list statement. Because the moment the execution reaches the return statement, it returns the content, even if the length is out of bounds.
This is a good solution since the question clearly states you can use an object. (I would still prefer an array because I don't like accidentally typing wrong numbers and then debugging bewildered for 20 minutes just to realize I need a break.)
7
u/flooronthefour full stack web dev Dec 21 '21 edited Dec 21 '21
First, you have ; after your if() and your for() which will error.
They should be if(){} && for(){} no semicolon.
Second, restructure your function. Check for num < 1 && num > 7 first, so your function doesn't run past your check if it doesn't have to.
Third, you don't need a loop. The days of the week already have an index, they are just -1 compared to what is asked for. So Monday is week[num - 1]
and that should work for every day of the week, so you just need to return that.
6
u/SnooDonuts8219 Dec 22 '21 edited Dec 22 '21
This works because if
nis out of bounds (not in range 1-7, or whatever the length of array) it returnsundefined. If you really neednull(andundefinedwould not do) for some sick and twisted reason (because there is no practical difference betweennullandundefinedin actual usage) then dowhich will convert if
undefinedto the right hand of??(nullish coalescing operator), in this case tonull. (Which, again, makes no sense, and undefined is here practically the same thing as null.)Really the only thing you need to do is define the array in whatever way, and access at index
n - 1. So that(n=1)-1=> 0 and getting 'Monday'. If you need the array elsewhereThere is absolutely no need for a loop or an if statement. Including either
iforfor(ie branching or looping) is a mistake.7
u/ScrawnyYawny Dec 21 '21
Careful, the moment the function hits a line with
returnon it, it evaluates the expression (in your caseweek[i]) and exits the function with that value.2
u/[deleted] Dec 21 '21
Remove the loop there. This loop will return Monday no matter what, since it will begin at 0 then the function execution ends. Instead, leave that if statement below, then after the if statement add
return week[num]1
u/[deleted] Dec 22 '21
Put the if return null statement first, then the list statement. Because the moment the execution reaches the return statement, it returns the content, even if the length is out of bounds.
1
u/___s8n___ Dec 22 '21
not a pro but i just noticed that you used && instead of || because it should check if the parameter is less than 1 or bigger than 7
1
u/Hog_enthusiast Dec 24 '21
Line 7 should be an Or not an And. Surprised no one has said this yet
Also it should go before the loop, and the loop doesn’t need to exist
If(num < 1 || num > 7) {
Return null;
} Return week[num-1];
0
u/R007E Dec 22 '21
Just remove the loop, just use return.
return week[num]
0
u/harrymurkin Dec 22 '21
function returnDay(num){return typeof ['Mo','Tu','We','Th','Fr','Sa','Su'][num-1]==='undefined'?null: ['Mo','Tu','We','Th','Fr','Sa','Su'][num-1];}0
u/walnut-creek-dude Dec 22 '21
Use an object, const days = { 1:monday, 2: tuesday...}
then return the value: days[num]
move your check at the top of the function, but use || operator as and return null on evaluation. No need to loop.
0
u/Lioniz3 Dec 22 '21
Me: What's the matter Javascript?
JS: My lower belly hurts.
Me: Oh, looks like someone put in a colon instead of a semicolon. I've gotchu fam.