Last Updated: February 25, 2016
·
1.084K
· hennson

SBN & DRY - Less code length in JavaScript

Time is money or something else. So let's start to spare some. SBN, short for square bracket notation, gives you no increase in performance but reduces the length of your code. Furtheron you can follow the DRY principle and reduce some keystrokes.

Example:

cond ? obj.foo("p1","p2","p3") : obj.bar("p1","p2","p3");

vs.

obj[ cond ? "foo" : "bar" ]("p1","p2","p3");

So let's put this into a small jQuery code snippet that shows or hides an element based on a condition. For instance a textfield contains an specific value...

$(this)[ $("#textbox").val()=="foo bar" ? "show" : "hide" ]();

So, hope that helps and is a good start posting to the coderwall.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside