Learn Ternary Operators In 9 Minutes

  Рет қаралды 51,070

Web Dev Simplified

Web Dev Simplified

Күн бұрын

Пікірлер: 124
@TylerR909
@TylerR909 4 жыл бұрын
Yeah I've been telling Jr Devs on my team lately to "Be less clever, be more clear." Being clever just to collapse some expression down to 1 line is only good if that line is extremely readable. Otherwise, make it dumber and cleaner.
@fmonel
@fmonel 4 жыл бұрын
Well said
@BloodyScythe666
@BloodyScythe666 4 жыл бұрын
definitely agree on what this video covers. ternaries can be amazing, if you know when to use them. readability goes over "smart code", especially if you're working with others (or even if you have to look at your code a couple months later). it might not be obvious at first but readability saves you a ton of overhead in the long term.
@nsharma4981
@nsharma4981 4 жыл бұрын
Nice to see you going back to the roots of your channel with short yet comprehensive videos on a single concept. These are the types that initially drew me to WDS. Also, awesome thumbnail! 😄
@WebDevSimplified
@WebDevSimplified 4 жыл бұрын
Thanks! I really enjoy making these types of videos since I find them to be the most helpful for learning.
@nsharma4981
@nsharma4981 4 жыл бұрын
@@WebDevSimplified Exactly! These are the types of videos I look for whenever I'm stuck
@_.sunnyraj._
@_.sunnyraj._ 4 жыл бұрын
His project video will make u watch tons of other tutorials 😂
@jessicaalvarez2314
@jessicaalvarez2314 2 жыл бұрын
so TO are ok if its no more than two results for the if statement
@EmadElSammad
@EmadElSammad 3 жыл бұрын
Exactly what I feel about arrow functions too. I prefer “function” to be written out.
@YaroLord
@YaroLord 3 жыл бұрын
you my friend are in the wrong side of history while you're at it, do you still use var and callback hell instead of promises?
@abdullahihagi7092
@abdullahihagi7092 3 жыл бұрын
@@YaroLord YES!
@zaurs0
@zaurs0 3 жыл бұрын
@@YaroLord Totally agree!!
@NotPastelDreams
@NotPastelDreams 4 жыл бұрын
Superb.. You are the only one who make tutorial with explaining downside of it so we can be aware especially as new developers.
@thedevcristian
@thedevcristian 3 жыл бұрын
SUCH A GREAT MENTOR!!! I am learning JS for a year and now, I understand this from your lectures. Thank you, Kyle!
@LukED87
@LukED87 4 жыл бұрын
4:54 Hmm, I think this is debatable. Personally I find this ternary use case quite simple to read & understand. And imagine if this 'if/else' block that you would use instead is nested inside another if, I believe it would be a lot more difficult to read than a simple ternary. As for other comments in video I totally agree! Keep up the great work and effort on making those really useful videos. :)
@silencedogood5173
@silencedogood5173 Жыл бұрын
Contrarian take: complicated ternaries can be easy to read, depending on how you handle linebreaks & indentation. For example, in a use case where stacked if/else if/else statements is often used, you can achieve something in JS close to what a when statement in Kotlin does: const result = isTruthyCheck ? result1 : isTruthyCheck 2 ? result2 : result3 When statement example in Kotlin: val objectType = when { fileType === UnixFileType.L -> "l" fileType2 === UnixFileType.HYPHEN_MINUS -> "-" fileType3 === UnixFileType.D -> "d" else -> "unknown file type" } A switch statement is often not possible in this context if the truthy checks don't inspect the same argument/variable. Plus, the need to explicitly break can be clunky at times. I often use this JS ternary approach and don't find it problematic. To each his own, though. Read-ability is important.
@soyilastore4399
@soyilastore4399 2 жыл бұрын
this is superb, i have been trying to understand what my lecturer wrote for and hour now. but thanks once more... now i understand the downside of tanary operator very well
@psilovechai
@psilovechai Жыл бұрын
Not what I was looking for, but this is the best explanation I have run across for if:else shorthand! Merci beaucoup ~!
@趙偉-o8v
@趙偉-o8v 4 жыл бұрын
Readability is a subjective matter. As long as only one variable is to be set, nested ternary operators are no worse than not nested ones. That only depends on whether you are used to it or not.
@arcadeduo7101
@arcadeduo7101 2 жыл бұрын
I am just a kid but I think readability does matters especially if you are working in a team. As I said, I am just a kid, this is just my opinion...
@intoTheEther1
@intoTheEther1 3 жыл бұрын
@ 6:00 In the spirit of doing things just to do them, I decided to turn this into a switch case statement instead. Would be cool if it was possible to make multiple evaluations in a single case const number = 0; let result; switch (number) { case 0: result = "You have nothing"; break; case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: result = "You have very little"; break; default: result = "You have a lot"; break; } console.log(result);
@DieterPrivate
@DieterPrivate 4 жыл бұрын
I always require to put the ? and : on a new line for readability. And if you want to execute a function, you can restrict it to resolve which function to use, as this indicates that you do want to do something, but what is calculated. The only thing I agree on is never do nesting. All others are easier to read Imho, as you are more concise in what is intented.
@lalit00716
@lalit00716 4 жыл бұрын
Sir, you are doing great work by providing us not only skill and knowledge but indirectly you are creating job for people's like us whom have hungered to learn new things and using and work on it as professionally. Thanks once again your videos help me in my growing careers
@MagiCityProductions
@MagiCityProductions 2 жыл бұрын
I love how you explain things.
@SirXtC
@SirXtC 3 жыл бұрын
another visual way which i think its still pretty readable if you still want to use ternaries is: let num = 10; let result; result = num === 0 ? "you have nothing" : num < 10 ? "You have very little" : "you have alot";
@Neckhawker
@Neckhawker 3 жыл бұрын
nested ternary can work with very good indentation : console.log('z'); let x = 2; let y = x < 0 ? "fii" : x < 1 ? "fuu" : x < 2 ? "foo" : "faa" ; console.log(y); (but of course youtube will break the indentation).
@Neckhawker
@Neckhawker 3 жыл бұрын
Another example : let x = -1; let y = x < 0 ? x < -2 ? "fii" : "fuu" : x > 2 ? "foo" : "faa" console.log(y); (just imagine everything well aligned)
@boaz.bananas
@boaz.bananas 2 жыл бұрын
Great explanation, very clear and easy to understand.
@OMorningStar
@OMorningStar 4 жыл бұрын
I cut down my use of the ternary a while ago thanks to react error comments. I used to do things like this: condition ? action : null. React complained about null, now I use it if I need another action, but in some rare cases I still use it with empty string.
@misamee
@misamee 4 жыл бұрын
I completely agree with you about not using a ternary when it does not return anything. However, we don't use the same "rule" with Array.map :) In fact, we use Array.map (or any Array method) a lot even when not returning anything.
@rorozoro9703
@rorozoro9703 2 жыл бұрын
ForEach
@MrRawat-yd9dt
@MrRawat-yd9dt 4 жыл бұрын
so i think because of the returning the value nature, ternaries operator can be used inside of return statement of any function, while we can't use if else there..
@fragileglass9622
@fragileglass9622 4 жыл бұрын
I have been on the fence about ternary operator. While it does present cleaner. Depending on code base. It’s easy to miss the logic depending on the developers choice of formatting. If / Else always stands out within the lines of code: but I also recognize the desire to eliminate additional code.
@DieterPrivate
@DieterPrivate 4 жыл бұрын
Though with if/else, you need a variable, while using ternary in a good way, you don't need a variable, and can tell the meaning of the code more clearly. So you can tell the reason better, not how to do the thing.
@cyclox73
@cyclox73 4 жыл бұрын
When I come across one in code I always have to take a second glance at it to understand what is going on (even when used properly). I don’t mind them but would prefer a standard if/else.
@cyclox73
@cyclox73 3 жыл бұрын
@@CodeConstellations agree
@Wakkyguy
@Wakkyguy 4 жыл бұрын
Please make a video on JavaScript Type Coercions clearly stating all the rules that JavaScript follows.
@kaiserdianalan7059
@kaiserdianalan7059 Жыл бұрын
Thank you now im going to stick on If else Es5 hehe
@tilakmadichettitheappdeveloper
@tilakmadichettitheappdeveloper 4 жыл бұрын
day 1 : building ai neural network and ml day 2 : how to use ternary operator 😊 he would hv seen the comments and ben like these kiddos don't deserve shii
@user-hh2is9kg9j
@user-hh2is9kg9j 4 жыл бұрын
especially with our messed up spelling.
@annam6187
@annam6187 Жыл бұрын
This is a really useful video, thank you. Some constructive feedback - highlighting text and wiggling the cursor back and forth quickly makes it very difficult to focus for some viewers
@thembelssengwayo6896
@thembelssengwayo6896 Жыл бұрын
Yeah I agree........we want to write code that is easy to read in the future
@sridharkatta3461
@sridharkatta3461 4 жыл бұрын
Great Kyle , u make my life easy as web developer.
@gleisonsubzeroKZ
@gleisonsubzeroKZ 4 жыл бұрын
In this second example of the user object I personally would not even use if or ternary, I would do it this way: const user = { } const userFunctionHandler = { true:user.save , false:user.printErros } userFunctionHandler[user.valid]() ======================================================== and for the last case I would do this: const number = 10; const getTextByNumber = (number) => { const cases = [ {key:number === 0,value:'You have nothing'}, {key:number < 10,value:'You have very little'}, {key:true,value:'You have a lot'}] return cases.find(c=> c.key).value; } const result = getTextByNumber(number);
@starseed73
@starseed73 3 жыл бұрын
What do you think of a switch(true) pattern when 3 or more cases ? Like this: switch (true) { case number === 0: result = 'Nothing'; break case number < 10: result = 'Little'; break default: result = 'A lot' }
@NoBrainerLanguages
@NoBrainerLanguages 4 жыл бұрын
What about inline if which uses a single line as well? I tend to use that approach without using ternary (which I hear is a "trend" for many devs). Oh, let's not forget switch cases which would be way better to use than if to check the same value source, even though break extra lines can take up more file bytes. Still an even better way to understand what should happen in every case.
@bobthehuntsman1548
@bobthehuntsman1548 4 жыл бұрын
Awesome explanation...thanks!
@enderger5308
@enderger5308 3 жыл бұрын
Honestly, I use them in cases where I want to use ‘if’ as an expression. If the ‘switch’ statement didn’t suck, it probably would be used in the cases where the ‘ternary’ operator is abused.
@GiovanniCardamone
@GiovanniCardamone 4 жыл бұрын
didnt agree to 6:50 + You don't have to put more parenthesis, just go on next line and put the new condition under the first one
@t3ntube357
@t3ntube357 4 жыл бұрын
This is what called best practice
@avi12
@avi12 4 жыл бұрын
Make a video about optional chaining
@maskman4821
@maskman4821 4 жыл бұрын
thank you Kyle for this fantastic video !!!
@MrSwingbop
@MrSwingbop 3 жыл бұрын
nice advice thank you !
@dynpallomah
@dynpallomah 4 жыл бұрын
There are two types of person: ` if(/**/) { // } else { // } ` AND ` if(/**/) { // } else { // } `
@sriramtorvi7417
@sriramtorvi7417 4 жыл бұрын
It really concerns me when i see somebody else's code with a lot of these if else statements only for variable assignments when it could have been easily done in one line using ternary..
@nobytes2
@nobytes2 4 жыл бұрын
why? It makes code more readable.
@sriramtorvi7417
@sriramtorvi7417 4 жыл бұрын
@@nobytes2 Ternary makes code more clean..
@DieterPrivate
@DieterPrivate 4 жыл бұрын
@@nobytes2 if/else actually makes code harder to process and understand. Sure, it may be easier to read HOW the code does something, but using ternary, it's easier to read WHAT the code is doing. What code is doing is more important when reading it.
@nobytes2
@nobytes2 4 жыл бұрын
@@sriramtorvi7417 Clean isn't the same as more readable, also clean isn't same as less lines. Show a ternary to 100 new software engineer then get back me how many understood it. Not to mention anything more than a simple if/else you would have to write a function then call a function from a ternary. At. that point a ternary becomes useless, since an if or switch case will always be more readable.
@nobytes2
@nobytes2 4 жыл бұрын
@@DieterPrivate You contradicted yourself lmao. I don't understand why your statement that if/else shows HOW but ternary shows WHAT. It makes absolutely no sense. I've been programming for nearly 10 years. Ternary ops are a commodity more than anything. Either way the safest if/else are switches with enums imho.
@juanmejia7747
@juanmejia7747 2 жыл бұрын
wow you're a great teacher
@saitejagatadi9711
@saitejagatadi9711 Жыл бұрын
Web devs be like: Just give us a room + computer + wifi We'll not complain about anything
@babitabisht4563
@babitabisht4563 4 жыл бұрын
Great video, can you create a video on one liners also?
@lowmain9995
@lowmain9995 3 жыл бұрын
7:42 You have it easy if that is a nightmare to read.
@enderger5308
@enderger5308 3 жыл бұрын
If you are going to nest ternaries, do it like this: first ? first : (second) ? second : else
@damnyoubakshi
@damnyoubakshi 2 жыл бұрын
Why I can't use "Break/Continue" in a ternary operation?
@theoneprince777
@theoneprince777 Жыл бұрын
Thank You 😃
@harambetidepod1451
@harambetidepod1451 4 жыл бұрын
Starts 1:20
@mykalimba
@mykalimba 4 жыл бұрын
Ternary operator is the best operator!
@niloofarkeramaati4959
@niloofarkeramaati4959 4 жыл бұрын
Those "oops"s are always there :))
@uncosstory814
@uncosstory814 2 жыл бұрын
Why nested ternary is showing error??
@MrJeszam
@MrJeszam 4 жыл бұрын
Im addicted in ternary. I used it when I am bored or I want to keep my classmate completely confused.
@thecraziestbee
@thecraziestbee 4 жыл бұрын
Nice job. Thanks.
@roycetaylor6529
@roycetaylor6529 3 жыл бұрын
For some reason the ternary is easier for me to understand than the if else statement....
@ishananaguru
@ishananaguru 3 жыл бұрын
lmao
@hwo2023
@hwo2023 3 жыл бұрын
Does it reduce the cognitive complexity of the code when you use a ternary instead of a if/else block ?
@JhonnyYang
@JhonnyYang 4 жыл бұрын
can you share our your launch.json file ?
@AhmedIbrahim-fi2so
@AhmedIbrahim-fi2so 3 жыл бұрын
thnks ❤️❤️
@udaysrivastava1957
@udaysrivastava1957 4 жыл бұрын
Please make a video for chess game in vanilla js
@xesiusprime9360
@xesiusprime9360 3 жыл бұрын
right arm on the farm spinning yarn
@cmdrTremyss
@cmdrTremyss 2 жыл бұрын
Video starts at 1:20 >:(
@conghuyphi945
@conghuyphi945 4 жыл бұрын
thank you so much
@Cryptocurruptions
@Cryptocurruptions 4 ай бұрын
August 9 6grade kid watching at 5:34pm this is cool and easy
@nikmat
@nikmat 4 жыл бұрын
console.log( loveTernary ? "YES" : "NO" )
@liondeluxe3834
@liondeluxe3834 4 жыл бұрын
I like using it :)
@arkham9770
@arkham9770 4 жыл бұрын
Is it true that ternaries are good?
@nicknapoli6345
@nicknapoli6345 4 жыл бұрын
HOLY CRAP!!!! 9 minutes for an operator... Don't do that. At least you added some "Don't do that" of your own.
@soumenkhara5456
@soumenkhara5456 4 жыл бұрын
Bro make video about passport google oautho2.0.
@avishekbarnwal8705
@avishekbarnwal8705 4 жыл бұрын
I like your videos, Web Dev Simplified , It really helps me a lot in my project Kindly do also make videos on OAuth2.0 and using some features of it Guys do like this comment who wants the same
@bobweiram6321
@bobweiram6321 3 жыл бұрын
If you[re really concerned about readability, don't develop in JavaScript. If you need to, then use TypeScript.
@DeepakGupta-hj2dv
@DeepakGupta-hj2dv 4 жыл бұрын
Event loop make video
@vishnukumarkannan3159
@vishnukumarkannan3159 3 жыл бұрын
looking at this code is a nightmare!!! loolllll, i lost it hahahaahhahahahahahaha
@reveluv8851
@reveluv8851 4 жыл бұрын
Please do NOT use ternaries in c and c++. That is branching code which is slow. Instead of (Condition) ? a : b Do a * (condition) + b * !(condition); This is fast because this code does not branch.
@reveluv8851
@reveluv8851 4 жыл бұрын
It works because the logical operators work just like arithmetic operators. They return true or false and since the low levelness of c and c++, true is the same as 1 and false is the same as 0. So when the condition is false,a will be multiplied by 0 and b will be multiplied by the logical not of 0(which is 1).so be will not be added.since a is 0, when added to b,b will not be affected. The process if the condition is true is just like this but b will turn into 0. It is theoretically possible to turn most code,even the ones with complex logic into branchless code(but it will be unreadable).
@a.srobot
@a.srobot 4 жыл бұрын
Hello, I have request for you to make video for responsive web page 0r design for (4k, 8k screen etc) using Bootstrap. Thanks in advance. Bless you
@StoneColdMagic
@StoneColdMagic Жыл бұрын
I have to disagree with your final example. I use nested ternaries all the time. They work better in my brain than the else if branch. Everybody’s brain works differently. To say that nobody should use a technique because your (Kyle’s) brain doesn’t process it doesn’t make any sense. That’s like saying that because lettuce makes me throw up nobody else should eat it ever. I like your videos but I think your reasoning on the nesting of ternaries is faulty logic.
@snansahmarov1524
@snansahmarov1524 4 жыл бұрын
You are amazing ❤️
@nikogolub
@nikogolub 9 ай бұрын
would you go out with me sir
@nikogolub
@nikogolub 9 ай бұрын
your eyes are really pretty and your voice so calming and you can code
@svenvancrombrugge9073
@svenvancrombrugge9073 4 жыл бұрын
I generally don't like ternaries. It feels to me that the syntax differs in different languages in a way that messes up my logical understanding of the code. I always have to check - how does this work in language X again? Working with both Python and JavaScript even in the exact same project isn't special. If you read a code that goes If/Else you can basically read it in the speed of a book (if it's very well written). In these cases I gotta double check and that might cost more time than actually programming the whole function that uses the damned ternary. Please don't use ternaries!
@Zanamo
@Zanamo 4 жыл бұрын
var annoying = "Very"; var res = annoying === "little" ? "not that bad" : (annoying === "medium" ? "Yeah kind of bad" : (annoying === "a lot" ? "bro - _ - bad" : (annoying === "Very" ? "Fired" : "I bet this is hard to write and read lol")));
@DevNegant
@DevNegant 4 жыл бұрын
Saved
@stormsoendergaard3023
@stormsoendergaard3023 4 жыл бұрын
I totally disagree with this, i think ternary operators are as simple to read, if not simpler than a long if/else-if chain.
@ShinAkuma
@ShinAkuma 4 жыл бұрын
I hate that this guy never puts semicolons.
@calebprenger3928
@calebprenger3928 4 жыл бұрын
I think web devs need to focus less on human readability and make things that work. Ternary ops are fantastic and super easy to understand for me
@privatelister2220
@privatelister2220 2 жыл бұрын
This is extremely opinionated and very misleading. Ternaries are not just "smart", they are also "simple". glancing over (code follows...) user.valid ? user.save() : user.printErrors() (...cont) instead of noticing a branch is similar to saying, "oops I did not read that line". Requiring a clunky if-block to grab the dev's attention is scary. The same dev might need a huge comment block of just exclamations before working on a secure piece of code 🤷‍♂ Regarding the nested ternary to replace else-if, there are functional ways to replace however, depends on whether you want to adapt to functional style. Finally, if-blocks are semi-dangerous because operations within these branches could arbitrarily grow. Because of the unseemingness of complicated ternaries, this will be intuitively avoided, the longer if-blocks grow, the further the branching condition is from a given line plus add states in un-functional code, it is a nightmare waiting to peek-a-boo!
@bunnybloods768
@bunnybloods768 4 жыл бұрын
5th view
@averstrum6372
@averstrum6372 3 жыл бұрын
If it works it works, why be so dogmatic, and I don't use semi-colons either. Think about your guitar, if everyone held the same view about music, it would get boring. You can either read code or you learn...
@ishananaguru
@ishananaguru 3 жыл бұрын
code is written once but read by everyone else...
@kawaikaino5277
@kawaikaino5277 4 жыл бұрын
Зачем так издеваться над языком? Это ведь усложняет чтение , особенно в полотне кода... такими темпами js превратится , в нечто подобное : a=B:c-.,? true '"-.,+;? false;~/:\
@bahodirrajabov7964
@bahodirrajabov7964 4 жыл бұрын
fourth
@technicalsankalpa5098
@technicalsankalpa5098 4 жыл бұрын
8th😆
@Kampouse
@Kampouse 4 жыл бұрын
Lol
@rengavasan6245
@rengavasan6245 4 жыл бұрын
198th view
@pranab091
@pranab091 4 жыл бұрын
500th view.
@gamingfury228
@gamingfury228 4 жыл бұрын
third
@OhOk616
@OhOk616 Жыл бұрын
Thanks so much.
Why Signals Are Better Than React Hooks
16:30
Web Dev Simplified
Рет қаралды 491 М.
Learn JavaScript DOM Traversal In 15 Minutes
14:44
Web Dev Simplified
Рет қаралды 228 М.
小丑教训坏蛋 #小丑 #天使 #shorts
00:49
好人小丑
Рет қаралды 23 МЛН
Чистка воды совком от денег
00:32
FD Vasya
Рет қаралды 6 МЛН
Каха и дочка
00:28
К-Media
Рет қаралды 2,2 МЛН
Spread and REST operators in Javascript
14:00
Hitesh Choudhary
Рет қаралды 56 М.
5 Must Know JavaScript Features That Almost Nobody Knows
18:06
Web Dev Simplified
Рет қаралды 478 М.
The CSS Display Property is Changing Forever
15:20
Web Dev Simplified
Рет қаралды 49 М.
Learn JSON in 10 Minutes
12:00
Web Dev Simplified
Рет қаралды 3,2 МЛН
Learn DOM Manipulation In 18 Minutes
18:37
Web Dev Simplified
Рет қаралды 1 МЛН
This is the Only Right Way to Write React clean-code - SOLID
18:23
I'm Ditching Try/Catch for Good!
10:29
Web Dev Simplified
Рет қаралды 186 М.
Build this JS calculator in 15 minutes! 🖩
15:20
Bro Code
Рет қаралды 687 М.
C Programming Tutorial for Beginners
3:46:13
freeCodeCamp.org
Рет қаралды 16 МЛН
Learn JavaScript Scoping In 10 Minutes
11:39
Web Dev Simplified
Рет қаралды 63 М.
小丑教训坏蛋 #小丑 #天使 #shorts
00:49
好人小丑
Рет қаралды 23 МЛН