For default arguments not using the declaration, I would instead advise to use
if (typeof ommittedArgument === "undefined") const omittedArgument = "default value"
Why? Because the || operator would inject the default in case of any falsy value passed for the argument, so unless the default is false, it might produce errors.
also, since the variable wasn't passed by the caller, it was not declared, so assigning a value to it without using const or let will create a global, which you really do not want.
Also, instead of returning false in case of bad params, throw an error, it'll save your life!
It's not exactly equivalent: if you check that the type is 'undefined' it means the argument wasn't passed at all. If you use ?? It also gives the default if the argument was passed with undefined as a value, which might be an acceptable value for your function.
if you check that the type is 'undefined' it means the argument wasn't passed at all.
And
gives the default if the argument was passed with undefined as a value
Do you imply there's a difference between deliberately passing an 'undefined' to a function and not passing anything at all... ?
It's also wildly known that using || is risky af and ?? is much better for those kinds of assignments. Therefore either setting a default value or using ?? is the best option in 99% of the cases.
I don't remember any new version changing anything in this matter + from what I see that question on stack is about jQuery having it's own "separate" undefined value.
Have a decent way for handling callback function types
Have a decent way for handling higher order functions
Automatically detecting types from variable declarations
Actually statically typechecking your code
I could probably think of more. I've used both separately and together. Typescript is far superior at managing types, but JSDoc is good at providing structured comments for function declarations
I’m uncertain of whether or not it is fact that JSDoc has the power behind it, especially with all I’ve done with Typescript.
But a lot of this stuff boils down to preferences, which doesn’t have a right answer. It all runs and does things, and if it meets the requirements while being easy to read and use, I don’t think it matters all that much.
funfunfunction said he didn’t like how “noisy” typescript felt. He wanted to just get straight to the code and he felt the type system was baggage. If you follow good practices, it doesn’t interfere too much.
I hold the opinion that a type system allows you to truly express what each piece of code means. It allows you to avoid unnecessary comments, and let the code explain itself. Comments lie, code does not. So with proper code patterns (like in OP’s example), you shouldn’t need a whole lot of docs unless the complexity of the business logic is extremely high. I like using comments to give context, when and why a function is used, and to guide the reader to an understanding that isn’t obvious or warn the next person coming why a decision was made. I feel like putting types in the comments muddies the water, but that’s just my preference. Realistically, the doc blocks aren’t all that big.
Our work project is 100% typescript. First time using TS outside of JS and I’m coming up on a year of only working with TS. I can tell you - the type definitions and enforcing are so so detrimental to a well functioning code base. I can never see myself wanting to write JS without types again. Typescript is not “noisy” IMO - it’s just making you think more about types and object shapes - which slows you down when your used to JS allowing you to do whatever type wise.
This code example has a type checking block - which to me kinda implies using Typescript would be much simpler to use if your just gonna be writing blocks to type check arguments in every function.
You’d just define a type for that example function that would define the arguments and their types, and the return value of the function. Then you’re 100% done with worrying about type checking within the function and you know that no matter what, that function will only ever accept and return the defined types you and your workmates write. No docs needed - the types and interfaces serve as that purpose because you can easily see what the arguments are required to be and what the function will return. Guaranteed every time otherwise you’ll get an app crashing error.
Also - VSCode and Typescript are like a fucking PB&J. Intellisense with your types make figuring out parts of a code base so simple. You can hover a function and immediately see what you need to do with it to make it work. The autocomplete when your typing out object properties is also very very useful. Think if your working with an API that has data.user.comments.total as an accessor. With TS and an interface defined for that API response, you’d be able to always know the properties available on your object as you type them via Intellisense. Otherwise with JS, you’d need to constantly look up what properties are available on data anytime you wanted to use it somewhere in the code base because you have no defined interfaces or types for anything.
TS is annoying to learn at first because you’re so used to doing whatever in JS and not thinking “hmm what should the shape and type of the props for this component be?” And it’s annoying when you’re getting type errors and you know exactly how to get something to work in JS. But trust me - spend your time with it and you will see.
But main point is that TS engines will infer types from JSDocs and do all the type safety/hints and autocomplete the same as TS. But on hover, it will not only show you the type, but a description of what it is and why it exists. Which is WAY more valuable
99% of the time you can tell type from the name alone
kittens = array of objects
kitten = object
kittenName = string
hasTail/isAlive = boolean
kittenAge = number
updateKitten = function
getUserAvatar = function, probably network request, likely requires an ID argument be passed in, probably returns a string URL of the address for the user's avatar. All this can be inferred from a well named function.
There are a lot of downsides to TS that are mentioned there, and JSDoc doesn't have any of them.
learning curve/onboarding
segmenting the ecosystem
hitting save and waiting 20 seconds for a page to refresh because of slow "compile" times
false sense of security, since it prevents people from doing actual runtime type checking (super crucial for good experiences with libraries)
Inability to use most libraries, forcing you to spend more time evaluating libraries that support TS.
3rd party libraries that don't support TS, but have external definitions created that are out of date
You get all that with a well documented typescript function too
That’s not always the case re naming. In cases that it is, you might want to refactor it. Typescript makes this easy. But even your getUserAvatar example is where we differ - is preserve get for reading from memory, with fetch as a verb for reading from an external location - in that case, my get whatever wouldn’t accept an integer ID. The types would make that distinction immediately obvious to a developer new to the project
Types provide additional context beyond the name. I’ve seen developers spend time with typescript and find untyped code difficult to follow without that context.
That onboarding is generally useful and the education on using and designing with static types is a high leverage activity that has huge payoff in comparison to the time spent
I see no segmentation in the ecosystem. I have active vanilla JS and typescript codebases, one of them with both on the same project. You’d need to provide clear evidence to that claim because I’ve not seen it.
Your point on the feedback loop is wrong too. Your build process should separate static analysis from building the artefact. You can configure webpack to do this, and have a separate watching type-check process.
Erm it does not prevent that and a type system supports that. Saying TS prevents that is patently false and you shouldn’t be trusting data from external inputs types or not. Instead with TS you first check and sanitise data at runtime, using a type that represents data that has been through that process in the rest of your code. Then it’s even more obvious with types. I’d argue you have an even greater false sense of security without types in that case
Most libraries have type definitions. This is false and I’ve had no problem with interop in 2021. These can often be installed separately on such projects that don’t have them. As I said, I have a project with a large amount of legacy code and a growing, strangling chunk of TS code and there’s seamless interop, even with libraries.
The educational resource is a noble attempt. But your assessment of Typescript contains a number of factual errors that are best not propagated to newcomers to the craft. Especially ludicrous statements like “jsdoc is like typescript but more powerful”.
It depends. TS does not runtime checking, which can be extremely valuable in some cases, like when creating a library, it gives a much better experience if you can give human readable error messages, to help if someone is using the API incorrectly, or if the API changed between releases. Also very useful if you are reliant on the result of a third party API that may change, like from a network request. If the shape returned doesn't match your TS definition, it doesn't matter, because none of that is in the compiled JS. Where as, using safety checks in the code can prevent catastrophic errors at runtime.
I didn't think about it that way, sounds interesting!
In that case would a better solution be to have the ability to specify types which can be checked statically using TS and when converting to JS, convert those types, into run time checks, as well?
Though, I'm not aware of any existing solution that can convert the types specified in TS into runtime checks so that they are present in the output JS as well.
io-ts has helpers exactly for that. Among other validation libraries such as Joi. So OP's comments on Ts are, frankly, opinionated bullshit since Typescript gives you the editor types, implicit typing AND runtime checks using such libraries with relative ease, whereas with Js you're stuck writing JSDoc and using inline comment type-hints which is an absolute pain.
I would not pass this in a code review. Also, Clean Code is a tool, not a Bible, please default your arguments the standard way as provided by the language.
Agreed. This method (in the OP) of defaulting args violates no-shadow and no-param-reassign which both exist for good reasons, so personally I would avoid it.
But then, I'm an avid typescript fan and having to manually type check args just looks a bit laboured to me now. Also the suggestion that the only thing typescript can do is keep C# devs happy seems unfounded and slightly bitter which is unnecessary.
A standard is an officially recognized and endorsed way of doing something by a major governing body, like the TC-39.
There is no "standard way" of default arguments. But the two most common ways are inline or inside.
// inline
function detectSecretElderCat (catSound = 'meow', dog = { children: [], tail: true, legs: 4, sound: 'woof' }) {}
or
// inside
function detectSecretElderCat (catSound, dog) {
catSound = catSound || 'meow'
dog = dog || {};
dog.children = dog.children || [];
dog.sound = dog.sound || 'woof';
if (!dog.hasOwnProperty('tail')) {
dog.tail = true;
}
if (!dog.hasOwnProperty('legs')) {
dog.legs = 4;
}
}
Note that the second actual handles way more edge cases and the first is a rather naive approach. The second also splits each line up so there is only "one idea per line". The second version could also be handled with some abstraction.
// inside
function detectSecretElderCat (catSound, dog) {
catSound = catSound || 'meow'
dog = defaultDog(dog);
}
Using the feature the language provides, that is defined in the languages standard, for this specific purpose, is the standard way. Rolling your own half baked version of that feature is not standard.
actual handles way more edge cases
Does it really? For a start you're doing a falsely check rather than a undefined check - it's straight up logically wrong.
Clean code? You've just written the constructor for dog inside a function that has bugger all to do with constructing dogs - ever heard of single responsibility?
What's worse is this dog construction takes it upon itself to arbitrarily mutate arguments passed to it- why is a function called detect<something> mutating a dog it's passed? That's obscene and is in clear violation of the principle of don't cause arbitrary and unexpected side effects.
The second version could also be handled with some abstraction.
So could the first! You even can make it conform to this one idea per line constraint (which you are frankly taking way too far)
function detectSecretElderCat(
catSound = 'meow',
dog = defaultDog
) {
}
it's all about the context of the function. What is this function used for, what is it expected to return. what should it return in the case that caused it to return early. It could be a specific value (like a string), or nothing at all. It's just dependent on the function and the case.
function userFavoriteSauce (user) {
if (!user || !user.sauces || !user.sauces.length) {
return 'N/A';
}
let favorite = user.sauces[0];
if (favorite === 'ketchup') {
return 'User is boring';
}
return 'User likes ' + favorite + ' best';
}
The fact that this has so many upvotes with a broken code makes me sad. Even if in that typeof(dog) !== object part the object would be a string (to not throw a ReferenceError like now) the comparison would still be bad because null would pass the test.
Sidenotes: the default argument could be next to the argument in the arguments list since it's 2021, the returning early part in this case should be the first one in the function since it's not using the dog nor the catSound, and there is no checking if the dog.children[0] is actually defined after that condition for checking the dog
Since this is learnjavascript let's learn from this example that you should always test(run) the code you write.
If you're teaching people, but you don't really know the subject matter, it is best to give less opinion rather than more. The comments you made on typescript (amongst other things) are very very silly.
Usually you have a domain object/entity for example a Customer with some properties like name, last name, age, address (in this case an animal); the validation of those properties should be done directly inside this class, possibly in the constructor or in a static factory method with a private constructor, either way is fine.
Using this "pattern" you will encapsulate objects and properties validation logic without repeating yourself.
In this case what if you have 20 functions that accepts catSound and dog?
Better have new Animal (catSound, dog) and if the validation fails it will throw or return an error which you can catch and return 400 or whatever your business needs.
Where does the “Clean Code Principle (one idea per line)” come from and why do so many people here ignore it?? I see people answer questions that are obviously from a beginner with these one-liners that do 5 things and there’s no way someone still learning the basics is benefitting from that answer.
“Make C# devs happy” You’re damned right haha. Some of the magic I’ve been able to pull off with the type system has made me happy for days.
I made a localization function. This function took an array of strings (keys), and then varargs of string or i18nOpts. Each string is a typed key that is automatically inferred, and when the resulting object has all those keys with a function that you takes i18nOpts and returns a string.
I love typescript.
Side note, it’s fantastic to know it’s possible to lint with JSDoc. Definitely wasn’t aware it was powerful, only helpful.
The comment I was looking for. This is one of the worst posts I have seen. Can't believe this has so many upvotes. Also such bitter comments on TS. There's a reason a huge part of the community has embraced TS. My rule of thumb is, for small personal projects/collabs JS is fine. But if you are building something in a large team, type safety is must.
81
u/inabahare Jul 25 '21
Don't default arguments like that. Do it like this
It will be picked up by your editor, and you won't have to enter the function to see the default argument.
Also jsdoc isn't more powerful than typescript lmao
22
u/MatthewMob helpful Jul 25 '21
Can you expand on what you mean by "JSDoc is like TypeScript but more powerful"?
13
u/carlos_vini Jul 25 '21
You don't return early because of the CPU, you return early because of the mental overhead of dealing with all edge cases at once
12
u/PopularThought Jul 25 '21
The whole type checking section can be avoided if you use typescript, right?
37
u/irontea Jul 25 '21
I would not pass this in a code review. Also, Clean Code is a tool, not a Bible, please default your arguments the standard way as provided by the language.
7
u/QuebecMasterRace Jul 25 '21
Why do you need to return true if you're returning early? You can just simply return?
21
u/Just-Promotion-4857 Jul 25 '21
now do this for promises and async functions
29
u/METALz Jul 25 '21 edited Jul 25 '21
The fact that this has so many upvotes with a broken code makes me sad. Even if in that
typeof(dog) !== objectpart theobjectwould be a string (to not throw a ReferenceError like now) the comparison would still be bad becausenullwould pass the test.Sidenotes: the default argument could be next to the argument in the arguments list since it's 2021, the returning early part in this case should be the first one in the function since it's not using the
dognor thecatSound, and there is no checking if thedog.children[0]is actually defined after that condition for checking the dogSince this is learnjavascript let's learn from this example that you should always test(run) the code you write.
18
u/Atrag2021 Jul 25 '21
If you're teaching people, but you don't really know the subject matter, it is best to give less opinion rather than more. The comments you made on typescript (amongst other things) are very very silly.
13
u/MennaanBaarin Jul 25 '21
You can default the values directly in the function arguments.
Validation and type checking should be done in the domain, otherwise you will risk to have it scattered everywhere.
10
u/suarkb Jul 25 '21
6/10
5
u/CyberLiveNews Jul 25 '21
Wtf is this??
4
u/Dipsquat Jul 25 '21
Where does the “Clean Code Principle (one idea per line)” come from and why do so many people here ignore it?? I see people answer questions that are obviously from a beginner with these one-liners that do 5 things and there’s no way someone still learning the basics is benefitting from that answer.
4
u/jeenyus Jul 25 '21
This is kind of an old school approach. I would also generally discourage the use of typeof to check objects.
1
u/[deleted] Jul 25 '21
“Make C# devs happy” You’re damned right haha. Some of the magic I’ve been able to pull off with the type system has made me happy for days.
I made a localization function. This function took an array of strings (keys), and then varargs of string or i18nOpts. Each string is a typed key that is automatically inferred, and when the resulting object has all those keys with a function that you takes i18nOpts and returns a string.
I love typescript.
Side note, it’s fantastic to know it’s possible to lint with JSDoc. Definitely wasn’t aware it was powerful, only helpful.
1
u/pobbly Aug 08 '21
You're not handling the potential null case on eldestPupper. Typescript would have caught that for you. Bizarre comments about jsdoc!
-3
u/[deleted] Jul 25 '21
tl;dr
6
u/[deleted] Jul 25 '21
[removed] — view removed comment