Family Magazine

Short Circuiting in JavaScript (2023)

By Geoff Griffiths @mmatraining1980

I asked Chat GPT to explain Short Circuting in JavaScript to me like I was 10.
I also asked for some jokes to be thrown in the mix.

“Hey there kiddo! You know how when you’re playing video games and there’s a super long level, but you discover a secret shortcut and skip straight to the end? Well, that’s kinda what we do in Javascript with something called “Short Circuiting”.

We use two super cool signs, “&” and “||“.

Okay, first let’s talk about the two “ands” – “&”. It’s like you and your best friend are on a secret mission. You both need to do your parts for the mission to be successful. If one of you fails, the mission fails. In Javascript, both sides of “&” must be true for the whole thing to be true.

If the first part is false, Javascript doesn’t even bother to check the second part, because it already knows the mission failed! (this is the short-circuiting – it just quits)

Now, let’s talk about the two “ors” – “||“. This is like saying, you can have an ice cream OR a cake for dessert. If you get ice cream, that’s great! You don’t need the cake anymore (although, cake is always good).

Similarly, in Javascript, if the first part of “||” is true, Javascript takes the shortcut and doesn’t bother checking the second part.

Here’s a geeky joke for you: Why don’t programmers like nature? It has too many bugs! And don’t forget, always be like Javascript’s “&” and “||”. Take the shortest path and save your energy for more video games!

😉

Yea, so after reading that, I’m none the wiser, so here’s some notes from a video that I found on YouTube…

Short Circuiting in JavaScript (2023)

If price is more than 500 and less than 2000

Then print “hello”

If both operands are true, then print hello.

The “short circuit” occurs, because if the first parameter is not true, then JavaScript won’t bother running the second one.

So if the price was 400, and wasn’t greater than 500, then the JS would stop running and not bother to evaluate if the price is also less than 2000

It’s the same with the “or” operands, or operators, whatever they are called.

If the first condition is true, then it won’t bother running or looking at the second one, because with the “or” operator, only one of them has to be true.

Short Circuiting in JavaScript (2023)

Back to Featured Articles on Logo Paperblog