For the first one, just use default assignment for the arguments (e.g. `calculate(taxes = 0.05, description = "Default item")` - This only uses the default value if the value is `undefined` and not for `null`, which may be want you want for most cases, given the difference of meaning that they have, rather than treating them the same. This avoids a lot of unexpected behaviors and is more likely to throw type errors or invalid values at you so you can find and correct it quicker. You can also use object destructuring in arguments with default values, like `calculate({ price = 0.05, description = "Default item" } = {})`. Default assignment makes it more readable and behave more consistent with ECMAScript norms with regards to undefined/null values.
The problem with the first way is that, according to the ECMAScript spec, a SyntaxError will be thrown if the function body has a "use strict" directive.
I am still surprised at how underused destructuring is everywhere in javascript today in favour of dot notation. I never understood why it never caught on. product.title, product.price? does that help with the readability or is it useless repetition.
As dangerous as using 'goto' in a high level language. Almost all of these will cause hard to debug bugs sooner or later . Just use a strongly typed alternative.
13:40 it's striking through "name" because it assumes you're writing for a browser and the "name" property exists in the global scope (on the "window" object). It's trying to save you from confusion, although AFAIK this doesn't in fact create any problems.
Project C# was designed to mimic Java. Over the years the language evolved so much that I see almost every modern language is using many C# ideas, like: 1. Lambda expressions = Arrow functions; 2. WPF Grid ~= CSS Grid; 3. TPL Lib/Async = Async/Await in JS; 3. Syntactic sugar = the stuff mentioned in your blog and more. Now, in my opinion, is time to add another ultimate C# technique - pattern matching, like: if (kyle is Person person && person.address != null){ //we have the assign and check in one expression person.print(); printPersonStreet(person); }
Even when I think I already know this stuff, I always learn something new. Had no idea you could use optional chaining with functions and arrays, though I'm not a huge fan of how it looks 😅
I'm surprised he didn't put it in the video, but console.dir() is another great feature. Makes it super easy to see heavily nested JSON in the terminal
@@SirusStarTV execution function by "function()" is just a sugar syntax for "function.call(thisArg, args)" so it's quite the same as with object properties "function?.call(thisArg, args)" -> "function?.()"
U can't imagine how happy I am knowing that I already know and use all these features except the console styling thank you so much I have learned a lot from ur channel
Same boat. I was aware of it though because many sites like discord will spam styled logs to get people from not using the devtools if they're not tech savvy.
If you're a React developer, note that Babel 7.8.0+ supports the new ECMAScript 2020 features by default, which includes nullish coalescing (??) and optional chaining (?.). So you can use them in your project without worrying about legacy browser support.
Actually semicolons are fkng redundant trash. By using them you do the machines work. If you write all your code on one line you MAY write them so the code work but then you probably shouldn't write any code at all.
@@Glendragon still different i think cause in ternary, 0 is count as falsy const a = 0 ? 1 : 0 // a = 0 const a = 0 ?? 1 // a = 0 const a = null ? 1 : 0 // a = 0 const a = null ?? 1 // a = 1
"name" is a javascript keyword. That's why you shouldn't use it as a name ("identifier") for a variable. It is an attribute of functions which holds (Surprise, surprise!) the name of this function. So the command Func1.name will give you Func1 if Func1 is a function... Also it can be useful when used aside set, get, bind or classes.
@@j0code Yes and how you write it is said by a table of stone. In germany we write names and things in upper case (which is in english by the way not written upper case itself). I know we are not the entire world but it is the natural behavior all around me. And surprise again: Func1 will work. It worked in Netscape Navigator, Mozilla Browser, Firefox and now in Chrome. We can make things complicated or use the time for the better good, shouldn't we?
It's not really a keyword. It's just a property of the function. The reason it's crossed out is because it's a global variable in the browser that's a property of the window object.
@@yksnidog Because it's a global variable that's used by the window object. When you assign something to the variable 'name' it assigns it to window.name. It's not a keyword, it's not reserved. It's just an identifier.
One more thing that you forgot to mentioned is the shorthand for casting string to number. let price = '0.05'; price = +price; now price has number type. It's useful sometimes.
There are at least 2 errors in the video: - ?.() doesn't check if is a function - ?.[] don't check if is an Array. The ?. operator only checks null and undefined
@Michał Kasprzak this is because until JS3/4 (I'm not sure of the version name) there was no difference between array and object. Array was only object with numeric index, and not a different type
@@noctislupo93 aren't they still very similar? you can still access an object attribute using brackets [], like it was an array of key => value, keys being string. I use that a lot to access object attribute dynamically through the use of a string function parameter
13:30 This is really good to use if you need to build deeply nested complex objects (maybe to turn into JSON). You can build it inside out by building the inner most objects, then just including them in their parent, all the way up to the root element. Much more readable and flexible as every sub-object has a reference, and you avoid the Xmas tree of deep nesting.
If you are worried about browser support. Nullish coalescing and optional chaining can be compiled away using babel. a?.b gets transpiled into more or less (a === null) || (a === undefined) ? undefined : a.b a ?? b gets transpilled into (a !== null) || (a !== undefined) ? a : b (with a couple of temp variables thrown in in order to prevent evaluating your code multiple times) So you write nice clean code using the nullish goodies, and compile it into code that will run even in prehistoric browsers.
In this nullish coalescing example - it is indeed good example to clearly show how does it work, but people please - in situations like this one, in commercial non-personal projects use default argument values instead. It will work completely the same, it's more readable and also provides you better developer experience by allowing you to check what the default value is by mouseover on function name in some IDE's like VSCode or WebStorm/PHPStorm, without needing to jump into the source code and analyzing where the heck the default value assign is
I have to admit, I thought it would be mostly things I was familiar with but I wanted to make sure so I gave it a watch. All five items were new to me! Teaching me both ES and to not make assumptions about my current knowledge. Thank you!
I thought it was going to be a useless video with stuff I already know. But it turns out most of the features in the video it could have helped me solve problems right yesterday. Thank you so much.
Thanks for showing those! Optional chaining looks really interesting to me however I have so many question on what are the caveats like How does it affect debugging? Because previously JS would tell you what went wrong and throw an error, and now it'd just go through and you might not even know something went wrong. I can see this being a huge debugging issue How does it work under the hood? Does it just do a regular if(!null && !undefined) check for you right in place where you did ?. or does it work somehow differently? What are performance hits on this? Does it slow down our code and if yes then how bad? What are the benefits of using this with TypeScript if there are? Would be great to have answers on those, I'm going to research
default assignments are "undefined"... And if you do set a default value yourself, VSCode will let you know what type is expected if you arent using typescript. so if you create something like function test ( arg = [] ) {}; VSCode will tell you that arg is expected to be an array.
@AngryJoeIsRacist Super Racist Typescript is not an easier version of JavaScript. It's a superset of JavaScript, meaning all JavaScript is valid Typescript. I'd argue you shouldn't use Typescript until you have understood why you are using it and how vanilla JavaScript approaches the same issues. Because otherwise you're adding a lot of complexity and overhead for no reason.
@AngryJoeIsRacist Super Racist You said - and stop me if I quote you incorrectly here - "you can make life harder on yourself" in response to my statement to "perhaps [not use Typescript]". Implying - and I will use simple deduction here, stop me if you have trouble following - that somehow there is an added cost to using Vanilla JS. I made arguments as to why that isn't the case. 1) JavaScript is easier. Which you just agreed on. So that's not the added cost. 2) JavaScript is valid TypeScript. A vast majority of issues you encounter in Vanilla JS you encounter in TypeScript. That's why it's relevant that TypeScript is a superset. (And comparing programming languages that literally contain the exact same vocabulary and grammar to spoken languages that do not is a false equivalent. But I'm guessing you know that.) So more issues in Vanilla JS is also not the added cost. 3) Typescript adds overhead and complexity, because it adds additional grammar (that's the complexity part) and requires you to use a lot of the additional grammar to get a use out of Typescript (that's the overhead part). That would mean Vanilla JS is both lower in complexity and lower in overhead. So that's not the added cost. Now that I have cleared that up for you, since apparently that was necessary, please, enlighten us as to why Typescript is supposed to "make life easier" instead of flailing at my comment line by line but provide no arguments of your own.
Two thoughts on the first example: 1. If you want to set default values, you can do that in the parameter function foo(str = "default"). 2. If you have undefineds or nulls going into your function, you propably have a bigger problem in your overall design. Google design by contract
@@aashiqahmed5273 Which I'd argue is a good thing. Null shouldn't be treated as `undefined`. They are inherently different things and should often be treated as such. Passing null into places will show you that something is incorrect much faster than replacing it with a default value.
Why dont use parameters default value on function signature?, I mean is like python kwargs but in javascript you can assign a default value if not passed
@@can_pacis That's not what @vmalvoq meant. He meant why not just use default parameter values. function calculateCost( itemCost, taxRate = 0.05, itemName = 'unknown item' ) { const totalCost = itemCost * (1 + taxRate); console.log(itemName + ' costs $' + totalCost); } The main difference is that the default parameter value is only used if the parameter value is undefined. In my above example function, if the taxRate or itemName are null, the default value on the parameter will not be used. > calculateCost(100, 0.07, 'my item'); > my item costs $107 > > calculateCost(100, undefined, undefined); > unknown item costs $105 > > calculateCost(100, undefined, ''); > costs $105 > > calculateCost(100, null, null); > null costs $100
@@MatthewWeiler1984 I can't exactly remember what I was talking about and I just don't want to rewatch this video but it looks like you are right, I'm not sure. If so, thanks for correcting and have a good day
I never finshed a project because of all the different cases the api would spit at me with json. this optional chaining thing is gonna finally let me finish it. Thanks alot for the video!
For the one with the default argument values, did you know you could just pass them like this? function calculatePrice(price, taxes = 0.5, description = "Default item") { ... } This will do the exact same but it will allow you to not even have to specify the last two arguments, as it will take the default value. For example, you could do this: calculatePrice(10); // which is valid but calculatePrice(10, 0.75); is also valid!
We can handle the undefined case for calculate Price @1:40 by using default values for the function params function calculatePrice(price, taxes = 0.05, description = 'Default item') {}
As an FYI, from the Mozilla docs: "If there is a property with such a name and which is not a function, using ?. will still raise a TypeError exception" - basically if you do kyle.print?.() and print exists in the object but is not a function it will throw an error.
I'm not even going to watch this. I liked it, and I thank you, for not making clickbaity titles like "No one knows these 5 js tricks!" or "5 tricks you NEED in 2021". Other channels have more subscribers than yours, and others have content that is more urgently relevant to what I do, but I really admire the way you run this channel, above many other youtubers. Top level stuff.
The default value tip is very cool, just a note for the example: >You could accidentally pass in a variable, the variable value is set to undefined and inside your code you need to make sure you handle that I think this is not a valid use-case for default values, in this case(a variable is accidentally undefined) your code should blow up ASAP... So if this is your only reason to do default values, just don't.
You could just function(val1='something') {} / const myfunction = (val1='something') => {} and defaults something if val1 comes undefined, nice video, you got me with consolelog styles haha
Wow the console log styling is going to be helpful, and adding that '?' check before accessing a variable of something really saved me. Thanks so much Kyle!!
@@KinSlay1337 unfortunately it creates less readable and maintainable code for the person that might need to update something in the future :( So even if it technically works, it's not acceptable for maintainability.
@@Hearrok you can always keep the untranspiled code to be maintained but I guess people where you work are too set on old practices if it's not an option
@@KinSlay1337 It's not the people it's the system engine interpreters that can't handle higher versions. Also having two copies of the same code but in different versions would add even more complexity to everything. It's not that hard to just write code with older styles. It's just that it would be nice to have things like arrow functions x)
I think the safest way is function myfunction(param1){ if(typeof param1 == "undefined"){param1 = 0.05} console.log(param1) } myfunction(); for 2 reasons 1) null can be a passed value 2) if you don't pass a param it is "undefined" not "null" 3) this method is even supported by internet explorer!!!
1) Nullish Coalescing It's a nice feature but in terms of overriding a parameter, it's a very bad practice. For parameters, you could do (taxes = 0.25) => { .. } and achieve the same result. 2) Styling Console It's nice for debugging but not every logger supports it. Can be painful in some instances. 3) Optional Chaining It's a nice feature but the support is still scary for production without a back-end that can inject support for older browsers. 4) Object Shorthand This one is very useful in the back-end with nodeJS. It's indeed a very clean solution. 5) Defer / Async Loading Careful with this!! The behavior of Defer is very inconsistent. It's only implemented since 2011 and it originally had a lot of problems with async. Defer also doesn't allow inline scripts which makes it scary in development areas. In some instances, the code still loads but acts like async or even triggers errors that should never have occurred. Defer doesn't really add much to your code expect more logical errors.
These are great tips that a lot of experienced devs are very familiar with, so it’s great to present them to those that are newer to JS. I will say though that I’ve watched a few of you videos, and the fact that you don’t terminate your lines with a semicolon drives me absolutely up a wall.
I'm using nullish coalescing, optional chaining and object shorthand. But I was not knowing these features name. Always Somthing to learn from your videos
That optional chaining thing has been something that I have been trying to use, but ran into syntax issues. And this video showed me what I was doing wrong and I am definitely going to be fixing my code to use this now. Thanks!
Didn't know the console styling, or the 'defer' for script tags. Thanks! For people that don't know, you can also set default function parameters like this, which I believe works the the same way as the ?? approach (checks for null or undefined): function calculatePrice(price, taxes = 0.05, description = "Default Item") { const total = price * (1 + taxes); console.log(`${description} With Tax: $${total}`); }
All of these tricks were incredible... hats off! Thanks for spreading a little wisdom over us all! These were all pretty neat tricks I can see myself using in the future. Can't wait for more!
Part of me thinks the Optional Chaining is really cool, but I personally prefer getting an error "can't read undefined of x" because I immediately know which specific value is undefined (in the given example, all values could be undefined (Person, address or street).
For added fun, use the null coalescing with the optional chaining. let x = Person?.foo?.bar.?() ?? 'hey something went wrong'; For bonus crazy, throw in the tertiary operator :) let x = a.?b ?? 0 ? 'lol' : 'wtf'
I watched this video few months ago and made am mental note of all the cool things you showed. Well today I had to use the Optional Chaining and it absolutely saved me big time! Thank you very much!!!
Been a web dev for nearely 20 years and most of these are new to me. (Granted most of them are newish features.) Real good to know and will save me a lot of time and effort. Going to sub for sure. The only one I knew was when I first used developer tools on Facebook. They used the console css feature to produce a very visible warning against copy and pasting third party code.
You know, I’ve been avoiding this video for a while because I was thinking “there’s no JavaScript tricks I haven’t learned from MDN!” Well, after your very first example I had to drop this video a like. On the second example I had to unlike the video just so I could like it again. I’m about to watch the third example now. Basically, thanks Kyle! Sorry I doubted you, you’ve never steered me wrong before.
For the first one, just use default assignment for the arguments (e.g. `calculate(taxes = 0.05, description = "Default item")` - This only uses the default value if the value is `undefined` and not for `null`, which may be want you want for most cases, given the difference of meaning that they have, rather than treating them the same. This avoids a lot of unexpected behaviors and is more likely to throw type errors or invalid values at you so you can find and correct it quicker.
You can also use object destructuring in arguments with default values, like `calculate({ price = 0.05, description = "Default item" } = {})`. Default assignment makes it more readable and behave more consistent with ECMAScript norms with regards to undefined/null values.
The problem with the first way is that, according to the ECMAScript spec, a SyntaxError will be thrown if the function body has a "use strict" directive.
I am still surprised at how underused destructuring is everywhere in javascript today in favour of dot notation. I never understood why it never caught on. product.title, product.price? does that help with the readability or is it useless repetition.
The person?.address?.street is going to save me SO MUCH time in React
Or you could just use your classes and datatypes correctly.
@@neuralwarp yeah why use a feature that saves times
Yea for me also
I love you `?.`
As dangerous as using 'goto' in a high level language. Almost all of these will cause hard to debug bugs sooner or later . Just use a strongly typed alternative.
Summary:
Nullish Coalescing: c = a || b; /=>/ c = a ?? b;
Styling Console Log: console.log(var, CSS_1, CSS_2 ); // CSS_1: 'font-weight: bold; color: red', CSS_2: 'color: green'
Optional Chaining: console.log(obj?.existMethodOrProp);
Object Shorthand: a=1; b=2; const obj = {a, b}; console.log(obj) // {a:1, b:2}
Defer/Async Loading: // download js, awaiting download html and execute js
13:40 it's striking through "name" because it assumes you're writing for a browser and the "name" property exists in the global scope (on the "window" object). It's trying to save you from confusion, although AFAIK this doesn't in fact create any problems.
thank you :)
The console log styling blew my mind. You learn something new every day I guess...
I found out when I opened devtools in facebook, they had a warning not to paste any malicious code into the console.
@@MrBroady02 Same with discord but I didn't know how it was done
Does he have a full JavaScript course on udemy? If so can someone pls help me with a link or his name on udemy?
@@Manny-mc3rx I don't think so but on fireship.io
Another cool thing you can look up is that you can put images in the chrome console
Project C# was designed to mimic Java. Over the years the language evolved so much that I see almost every modern language is using many C# ideas, like:
1. Lambda expressions = Arrow functions;
2. WPF Grid ~= CSS Grid;
3. TPL Lib/Async = Async/Await in JS;
3. Syntactic sugar = the stuff mentioned in your blog and more.
Now, in my opinion, is time to add another ultimate C# technique - pattern matching, like:
if (kyle is Person person && person.address != null){ //we have the assign and check in one expression
person.print();
printPersonStreet(person);
}
Even when I think I already know this stuff, I always learn something new. Had no idea you could use optional chaining with functions and arrays, though I'm not a huge fan of how it looks 😅
I'm surprised he didn't put it in the video, but console.dir() is another great feature. Makes it super easy to see heavily nested JSON in the terminal
@@Rogue_Art Oh interesting, I'll be giving that a go!
Lol, same thoughts. I thought there would be some new syntax for function call like that:
function?()
or array index
array?[571]
And I don't like private property syntax like #privateProp, "private" keyword or _privateProp would be much better
@@SirusStarTV execution function by "function()" is just a sugar syntax for "function.call(thisArg, args)" so it's quite the same as with object properties "function?.call(thisArg, args)" -> "function?.()"
U can't imagine how happy I am knowing that I already know and use all these features except the console styling thank you so much I have learned a lot from ur channel
Felt the same thing. Console.log styling was jaw dropping.
same
I have to add that I still haven't used it :P
Same boat. I was aware of it though because many sites like discord will spam styled logs to get people from not using the devtools if they're not tech savvy.
If you're a React developer, note that Babel 7.8.0+ supports the new ECMAScript 2020 features by default, which includes nullish coalescing (??) and optional chaining (?.). So you can use them in your project without worrying about legacy browser support.
For someone who comes from C++ & Java:
You skipping semicolon hurts me deeply.
It still hurts me even though I started with js
Javascript has automatic semicolon insertion, not foolproof.
@@TheNewton That's the code editor extension, JS totally works without the semi
Actually semicolons are fkng redundant trash. By using them you do the machines work.
If you write all your code on one line you MAY write them so the code work but then you probably shouldn't write any code at all.
Look at Golang. Even Ken Thompson realized this deep truth ;)
03:05
Kyle: you're not use to see question marks in javaScript
Ternary operators: are we jokes to you?
:D
X = (assert something) ? Val1 : (assertion 2) ? Val2 : val3;
yes,,, so true!
and its basically a ternary operation.
object ?? val1
looks very similar to
object? (as in, does it exist) ? val1 : val2
language = 'Python' if is_readable else 'Javascript'
@@Glendragon still different i think
cause in ternary, 0 is count as falsy
const a = 0 ? 1 : 0 // a = 0
const a = 0 ?? 1 // a = 0
const a = null ? 1 : 0 // a = 0
const a = null ?? 1 // a = 1
"name" is a javascript keyword. That's why you shouldn't use it as a name ("identifier") for a variable.
It is an attribute of functions which holds (Surprise, surprise!) the name of this function.
So the command Func1.name will give you Func1 if Func1 is a function...
Also it can be useful when used aside set, get, bind or classes.
function names are written in lower case, not Upper Case. (unless it's an object constructor)
@@j0code Yes and how you write it is said by a table of stone. In germany we write names and things in upper case (which is in english by the way not written upper case itself). I know we are not the entire world but it is the natural behavior all around me. And surprise again: Func1 will work. It worked in Netscape Navigator, Mozilla Browser, Firefox and now in Chrome. We can make things complicated or use the time for the better good, shouldn't we?
It's not really a keyword. It's just a property of the function.
The reason it's crossed out is because it's a global variable in the browser that's a property of the window object.
@@SealedKiller a keyword is a word crossed out because it is used. So why exactly is a property identifier not a keyword? 8-)
@@yksnidog Because it's a global variable that's used by the window object. When you assign something to the variable 'name' it assigns it to window.name. It's not a keyword, it's not reserved. It's just an identifier.
When I discovered optional chaining in Ruby a few years ago it literally changed my life. So happy to see it eventually made it to JS
Optional chaining saved my life numerous times.
I'm proud to say that I knew and use these features nearly every day. Great video Kyle, I really like your channel!
Same here!
never seen or heard styling console log before. you are gem.
useless but ok
@@ricko13 color coding
@@ricko13 vbvlhbbvvbbvkbgvphvbbbb)))?:-::;::?--?-;;:::;::::-::;;::::?-?-::-:;::;:::?(-?0:?)-)-??);::(;;:--:-:;-;:;;::;-?::/;;:-;:;-:?:?-)!?;??;?)?))????-?:;-:-)-:-:);;--::-:!:;::::::::::(;--:;)--:!:
Vmlbvbbvvmgggklgbgvvvvbhgvvgbnbbvvvvkvvvg
Gggvkvvvvphglbgvlbmmmmmvlhvvlvkmjvvvbmbbvvgvvhkvvgvhvgbggbbvvbvbbgvvvmvvklmmkvkggbgvgvvgvvbpvvgvghvvv
Bvmvgjvggkggvhhh
Bbvbvvvvb
CclvnmgvgvvvpvvgvgggmvvvvbggvvvgpmkgvvbkkvbmmllmnblkglhbbvkvvvvvmgggvvvvvgbvngvvbgvvvbxvmvmkmbvvlvvbvvbvvvgvgbvgbvvbvvhvbvvvhgvvbvvpvgvbvgbvbbvvlfkkmmmmllkmmhbgvbhbbvmvbvgbgvvbvhggvvbbvvbbgvgvvmghmbvmbggmmHvlkklhmvhvjvvbbbbvvvgvmvbvhvggvvgvvpbvgpbvmvgvvmgmbmkvgkmmmmkmvvhbvvbcvvggvgvvvbvvvvvvbvbbgvcvvvvvvvvvvmvvbgvvbvmvblmlmhmkmmmvlmmkmmmlvvvgmgvhvvkvbvvbghvbvvvvmggvbvbvgvvvvbvvggvvvmpvvmvvhvvvgkmhlkbmmmmxpmkmclbgggg
Gbvvvvvnbbgvbvvgbgvvvvvvvgvgvhkgvvmvpvpvbbmkbmmvvmmmlmlmmmmlvlhbvvhvbvkgvvvvbhvgppvvbvggpvbvbgbvmhggckvbvmvmvvvkgvpmvvgvvhkckkkvmmvkvmmkvvmvbvvvvvgbvnbgvvggvvhbbgvbvvvbhmlbbvbghvkvggpgvbvkgvpgbhbghbhmlgmlmmlvvvgvvvvbvhvvvvvvvvhvvgv bvbvvvvvpkvmgvmmlmvhhbvvhbbvVgbvvbvvvbbvvbbvbbbmhvgbvvvbbmhbpmlglkgmvvbvbbvvvgbbvbbvvbvvhvvmbvvhpvbbkg
Gbmvhvhgkmmmmlklgvbvvlgvvbvbvvvvvvvvvvvvmpvgvvcbbnjkmkmkhbmmmmmbvkvvnmbvvvvvvggvggvvvvvppbbbcvhmmmmlkbbbbvbhbgvmvbmvvvhvbbvmvkbmmmmvbpvvlggvvvvvvvvbvgvm bvmvmvpbknkvmbmmmlmmmmccbvhvbbvvbmvb
Bgvvpvvbpgvvpbbvv
Hmv
Mkbmvvglcmvpgvph
Gvv
Ggvbvvvvgmvvvvgvgvvvjvpvgpvgvvgvvvgmhg lkmvmlmvgvbvv bb bb bb bb bb bb bb v
Vgbvggkvvvbvpv
ive seen it, if you load pixi js in your project you will see a cool box in your console
@@spartaboss8387 ??????
One more thing that you forgot to mentioned is the shorthand for casting string to number.
let price = '0.05'; price = +price; now price has number type. It's useful sometimes.
I use price = Number(price)
this also works :P price = '0.05' * 1. Because you can not multiply a string, JS now it must be integer
There are at least 2 errors in the video:
- ?.() doesn't check if is a function
- ?.[] don't check if is an Array.
The ?. operator only checks null and undefined
Nice catch. You have a sharp mind!
Yep. It's a nullish coalescing operator for methods
@Michał Kasprzak this is because until JS3/4 (I'm not sure of the version name) there was no difference between array and object. Array was only object with numeric index, and not a different type
CoffeeScript did this back in the day
@@noctislupo93 aren't they still very similar? you can still access an object attribute using brackets [], like it was an array of key => value, keys being string. I use that a lot to access object attribute dynamically through the use of a string function parameter
13:30 This is really good to use if you need to build deeply nested complex objects (maybe to turn into JSON).
You can build it inside out by building the inner most objects, then just including them in their parent, all the way up to the root element.
Much more readable and flexible as every sub-object has a reference, and you avoid the Xmas tree of deep nesting.
If you are worried about browser support. Nullish coalescing and optional chaining can be compiled away using babel.
a?.b gets transpiled into more or less
(a === null) || (a === undefined) ? undefined : a.b
a ?? b gets transpilled into
(a !== null) || (a !== undefined) ? a : b
(with a couple of temp variables thrown in in order to prevent evaluating your code multiple times)
So you write nice clean code using the nullish goodies, and compile it into code that will run even in prehistoric browsers.
Am I the only one who is this excited every time he release new videos
Maybe...
here same from Korea
Keydi, you need something, something you got the illusion you r getting with each video
Ese like what?
@@keydib8913 Yes, because you are girl and we are not gays =)
Came for optional chaining and ended up staying for the full suite. All super valuable, great work and thank you!
I'm going to have the most beautiful console logs from here on out
In this nullish coalescing example - it is indeed good example to clearly show how does it work, but people please - in situations like this one, in commercial non-personal projects use default argument values instead.
It will work completely the same, it's more readable and also provides you better developer experience by allowing you to check what the default value is by mouseover on function name in some IDE's like VSCode or WebStorm/PHPStorm, without needing to jump into the source code and analyzing where the heck the default value assign is
I have to admit, I thought it would be mostly things I was familiar with but I wanted to make sure so I gave it a watch. All five items were new to me! Teaching me both ES and to not make assumptions about my current knowledge. Thank you!
I thought it was going to be a useless video with stuff I already know. But it turns out most of the features in the video it could have helped me solve problems right yesterday. Thank you so much.
You might run into some "Edge" cases... Nice one!
🤣
One of the best puns I've heard in a long time...
It's been so long since i have actually learnt new things regarding Javascript
Thanks for showing those!
Optional chaining looks really interesting to me however I have so many question on what are the caveats like
How does it affect debugging? Because previously JS would tell you what went wrong and throw an error, and now it'd just go through and you might not even know something went wrong. I can see this being a huge debugging issue
How does it work under the hood? Does it just do a regular if(!null && !undefined) check for you right in place where you did ?. or does it work somehow differently?
What are performance hits on this? Does it slow down our code and if yes then how bad?
What are the benefits of using this with TypeScript if there are?
Would be great to have answers on those, I'm going to research
Oh dang, I got stumped on a coding challenge a week ago, and Nullish Coalescing literally solves the exact roadblock I ran in into.
You could just do a default assignment with the first example. That's the cleanest way.
But that won't do a check I guess
Default assignment will only assign for undefined, not nulls
@@Champagnerushi I know. But he is not using null.
default assignments are "undefined"...
And if you do set a default value yourself, VSCode will let you know what type is expected if you arent using typescript.
so if you create something like function test ( arg = [] ) {};
VSCode will tell you that arg is expected to be an array.
omg. optional chaining is going to be so SO SO SO incredibly helpful
oh damn
optional chaining is finally out
tbh just use typescript
Or maybe don't.
@AngryJoeIsRacist Super Racist Typescript is not an easier version of JavaScript. It's a superset of JavaScript, meaning all JavaScript is valid Typescript.
I'd argue you shouldn't use Typescript until you have understood why you are using it and how vanilla JavaScript approaches the same issues. Because otherwise you're adding a lot of complexity and overhead for no reason.
@AngryJoeIsRacist Super Racist You said - and stop me if I quote you incorrectly here - "you can make life harder on yourself" in response to my statement to "perhaps [not use Typescript]". Implying - and I will use simple deduction here, stop me if you have trouble following - that somehow there is an added cost to using Vanilla JS.
I made arguments as to why that isn't the case.
1) JavaScript is easier. Which you just agreed on. So that's not the added cost.
2) JavaScript is valid TypeScript. A vast majority of issues you encounter in Vanilla JS you encounter in TypeScript. That's why it's relevant that TypeScript is a superset. (And comparing programming languages that literally contain the exact same vocabulary and grammar to spoken languages that do not is a false equivalent. But I'm guessing you know that.) So more issues in Vanilla JS is also not the added cost.
3) Typescript adds overhead and complexity, because it adds additional grammar (that's the complexity part) and requires you to use a lot of the additional grammar to get a use out of Typescript (that's the overhead part). That would mean Vanilla JS is both lower in complexity and lower in overhead. So that's not the added cost.
Now that I have cleared that up for you, since apparently that was necessary, please, enlighten us as to why Typescript is supposed to "make life easier" instead of flailing at my comment line by line but provide no arguments of your own.
@AngryJoeIsRacist Super Racist See, now you're actually making arguments. Thank you. That's all I wanted.
Dude the optional chaining will save me so many headaches. I run into this problem daily and have never heard of this syntax!
Dude this is amazing. This helps make me write clean, error-free code with so much more confidence. Thanks for such great content.
Two thoughts on the first example:
1. If you want to set default values, you can do that in the parameter function foo(str = "default").
2. If you have undefineds or nulls going into your function, you propably have a bigger problem in your overall design. Google design by contract
I saw the thumbnail of isCrazy() and I was fully prepared to see a function called that. Nothing surprises me in JS anymore.
simple, consise , straight to the point, why all web tutorials on youtube arent like that?
function calculatePrice(price, taxes = 0.05, description = "Default item") {
yup, default props,but it does not works for null or empty values
@@aashiqahmed5273 Which I'd argue is a good thing. Null shouldn't be treated as `undefined`. They are inherently different things and should often be treated as such. Passing null into places will show you that something is incorrect much faster than replacing it with a default value.
@@aashiqahmed5273 they are not props they are parameters
I’m a beginner in JavaScript and enrolled in boot camp so watching your videos are super awesome and cool! Subscribed!
All features are same as in C#
i miss linq
You mean “stolen from c#”.
In next js edition: “this” is “this” and not some random sh**.
wow optional chaining has absolutely blown my mind, that is a massive problem solver.
This is great, but absence of semicolons bothers me deeply xD
Semicolons are trash
Nullish coalescing and Optional chaining are just Killer-features. This video is a blessing. Thank you !
I recently discovered optional chaining and my God my life is so easy now.
I love the nullish coalescing operator. I already used it in production multiple times to replace pretty much all of the "workaround code".
Why dont use parameters default value on function signature?, I mean is like python kwargs but in javascript you can assign a default value if not passed
That's just the way he presented it, you can use it anywhere with any variable not just function parameters.
@@can_pacis That's not what @vmalvoq meant.
He meant why not just use default parameter values.
function calculateCost(
itemCost,
taxRate = 0.05,
itemName = 'unknown item'
) {
const totalCost = itemCost * (1 + taxRate);
console.log(itemName + ' costs $' + totalCost);
}
The main difference is that the default parameter value is only used if the parameter value is undefined.
In my above example function, if the taxRate or itemName are null, the default value on the parameter will not be used.
> calculateCost(100, 0.07, 'my item');
> my item costs $107
>
> calculateCost(100, undefined, undefined);
> unknown item costs $105
>
> calculateCost(100, undefined, '');
> costs $105
>
> calculateCost(100, null, null);
> null costs $100
@@MatthewWeiler1984 I can't exactly remember what I was talking about and I just don't want to rewatch this video but it looks like you are right, I'm not sure. If so, thanks for correcting and have a good day
I never finshed a project because of all the different cases the api would spit at me with json. this optional chaining thing is gonna finally let me finish it. Thanks alot for the video!
For the one with the default argument values, did you know you could just pass them like this?
function calculatePrice(price, taxes = 0.5, description = "Default item") {
...
}
This will do the exact same but it will allow you to not even have to specify the last two arguments, as it will take the default value.
For example, you could do this: calculatePrice(10); // which is valid but calculatePrice(10, 0.75); is also valid!
That's what I was thinking! His way is inefficient.
We can handle the undefined case for calculate Price @1:40 by using default values for the function params
function calculatePrice(price, taxes = 0.05, description = 'Default item') {}
As an FYI, from the Mozilla docs:
"If there is a property with such a name and which is not a function, using ?. will still raise a TypeError exception" - basically if you do kyle.print?.() and print exists in the object but is not a function it will throw an error.
٠
Empty lol
I'm not even going to watch this. I liked it, and I thank you, for not making clickbaity titles like "No one knows these 5 js tricks!" or "5 tricks you NEED in 2021". Other channels have more subscribers than yours, and others have content that is more urgently relevant to what I do, but I really admire the way you run this channel, above many other youtubers. Top level stuff.
Thank you!
What I understood was if you run into errors in javascript just throw in a '?'
Optional chaining is exactly what I needed. Been struggling with a desktop app breaking because we were getting unexpected nulls. Thank you!
Can you add the information about the ECMAScript versions when each of the mentioned possibilities became available please?
The default value tip is very cool, just a note for the example:
>You could accidentally pass in a variable, the variable value is set to undefined and inside your code you need to make sure you handle that
I think this is not a valid use-case for default values, in this case(a variable is accidentally undefined) your code should blow up ASAP... So if this is your only reason to do default values, just don't.
Woah, I knew all of those! 🎉
You could just function(val1='something') {} / const myfunction = (val1='something') => {} and defaults something if val1 comes undefined, nice video, you got me with consolelog styles haha
Can't you just define default values in the function definition like this: calculatePrice(price, taxes=0.05, description="Default item") {....?
No
@@reinieltredes8306 ok thanks for that detailed explanation
I'm a beginner. I tried your sample and... It works. Thanks dude
@@KalmeMarqTG tried on pure js. It works too
Wow the console log styling is going to be helpful, and adding that '?' check before accessing a variable of something really saved me.
Thanks so much Kyle!!
So we handle "undefined" by writing code that doesn't throw error for it... :D
we really know a comprehensive video to show us all the hacks tips and features that will make our js code short clean and robust.
Great Video!
Video: "New features in JS..."
Me: Yeah... I'm stuck in working with ES5 in corporations :/
Transpile with babel
@@KinSlay1337 unfortunately it creates less readable and maintainable code for the person that might need to update something in the future :(
So even if it technically works, it's not acceptable for maintainability.
@@Hearrok you can always keep the untranspiled code to be maintained but I guess people where you work are too set on old practices if it's not an option
@@KinSlay1337 It's not the people it's the system engine interpreters that can't handle higher versions. Also having two copies of the same code but in different versions would add even more complexity to everything. It's not that hard to just write code with older styles. It's just that it would be nice to have things like arrow functions x)
A lot of information in 18 mins. Truly Web Dev Simplified.
6:45 Probably shouldn't have used your real address, Kyle...
My head literally just exploded. This video is recommended to save and watch again and again! Thanks for the tips!
I hate the && and || sintax because for me that should return a boolean like *taxes || 0.5* should return true or false
I feel lucky that I got you on RUclips. Love from Bangladesh♥
Instead of console.log(), I ofter use console.table().
So much cleaner.
Or console.dir to extract info
These "tricks" are awesome. I knew all of them, except...
- Console Log Styling!
... This feature was really surprise for me. Thank u!
Stealing solutions from C# I see. :D
I was about to say the same thing
When you thought you couldn't get surprised, this guy strikes again and amazes you once again.
We've had these newer syntaxes in C# for a while, it's nice to see JavaScript has it too.
I think the safest way is
function myfunction(param1){
if(typeof param1 == "undefined"){param1 = 0.05}
console.log(param1)
}
myfunction();
for 2 reasons
1) null can be a passed value
2) if you don't pass a param it is "undefined" not "null"
3) this method is even supported by internet explorer!!!
1) Nullish Coalescing
It's a nice feature but in terms of overriding a parameter, it's a very bad practice. For parameters, you could do (taxes = 0.25) => { .. } and achieve the same result.
2) Styling Console
It's nice for debugging but not every logger supports it. Can be painful in some instances.
3) Optional Chaining
It's a nice feature but the support is still scary for production without a back-end that can inject support for older browsers.
4) Object Shorthand
This one is very useful in the back-end with nodeJS. It's indeed a very clean solution.
5) Defer / Async Loading
Careful with this!! The behavior of Defer is very inconsistent. It's only implemented since 2011 and it originally had a lot of problems with async. Defer also doesn't allow inline scripts which makes it scary in development areas. In some instances, the code still loads but acts like async or even triggers errors that should never have occurred. Defer doesn't really add much to your code expect more logical errors.
defer -- wow! Worth an entire video. How did I not know this? Thank you!! time to go delete a lot of load functions...🤦♂
These are great tips that a lot of experienced devs are very familiar with, so it’s great to present them to those that are newer to JS. I will say though that I’ve watched a few of you videos, and the fact that you don’t terminate your lines with a semicolon drives me absolutely up a wall.
nice video! Am I the first to say?: calculatePrice = function(price=0,taxes=0.5,description="no description"){ ... }
I'm using nullish coalescing, optional chaining and object shorthand. But I was not knowing these features name. Always Somthing to learn from your videos
Nice to see, that all the nice features of c# finally got ported to JavaScript as well.
I've seen object shorthand almost everywhere
I didn't know nullish coalsescing, that's pretty useful
Very clear explanation! Thank you.
Nullish Coalescing and Optional Chaining, my 2 new tools ✌🏼
That optional chaining thing has been something that I have been trying to use, but ran into syntax issues. And this video showed me what I was doing wrong and I am definitely going to be fixing my code to use this now. Thanks!
Didn't know the console styling, or the 'defer' for script tags. Thanks!
For people that don't know, you can also set default function parameters like this, which I believe works the the same way as the ?? approach (checks for null or undefined):
function calculatePrice(price, taxes = 0.05, description = "Default Item") {
const total = price * (1 + taxes);
console.log(`${description} With Tax: $${total}`);
}
All of these tricks were incredible... hats off!
Thanks for spreading a little wisdom over us all!
These were all pretty neat tricks I can see myself using in the future.
Can't wait for more!
Optional Chaining is GOLD!
Part of me thinks the Optional Chaining is really cool, but I personally prefer getting an error "can't read undefined of x" because I immediately know which specific value is undefined (in the given example, all values could be undefined (Person, address or street).
Really cool to see the optional chaining operator out of the box with JavaScript now, very useful
You always surprises me but this time i already knows all these features. By the way your content is just awesome.
your channel is money. learning so many new, useful things.
For added fun, use the null coalescing with the optional chaining.
let x = Person?.foo?.bar.?() ?? 'hey something went wrong';
For bonus crazy, throw in the tertiary operator :)
let x = a.?b ?? 0 ? 'lol' : 'wtf'
I watched this video few months ago and made am mental note of all the cool things you showed. Well today I had to use the Optional Chaining and it absolutely saved me big time! Thank you very much!!!
C# says "Hi!". You're right about defer, it's pretty awesome.
I really needed that Optional Chaining for a React project I'm doing. Blew my mind.
Thanks for spoiling it, now 36K people know.
Been a web dev for nearely 20 years and most of these are new to me. (Granted most of them are newish features.) Real good to know and will save me a lot of time and effort. Going to sub for sure. The only one I knew was when I first used developer tools on Facebook. They used the console css feature to produce a very visible warning against copy and pasting third party code.
defer was the mindblowing for me, thank you!
I am grateful that you decided to teach web development. I learn something new and cool every time.
Thank you and God bless.
As a novice to Javascript, these tips are amazing. I'm especially fond of being able to apply css to console logs!
You know, I’ve been avoiding this video for a while because I was thinking “there’s no JavaScript tricks I haven’t learned from MDN!”
Well, after your very first example I had to drop this video a like. On the second example I had to unlike the video just so I could like it again. I’m about to watch the third example now. Basically, thanks Kyle! Sorry I doubted you, you’ve never steered me wrong before.