JavaScript shorthands

Let’s talk about shortening JavaScript code. Browser has to parse JavaScript source code every time when it is used in a web page, because JavaScript is a scripting language and the browser gets raw source code as a text. So, code shortening gives the following benefits:

  • Less amount of bytes will be downloaded from the server, which means that the download time will be shorter.
  • Browser parsing phase will take less time
  • Code will be written/read faster and so on.

That’s why shortening code is good. Now let’s talk about how and when code can be shortened:

Longer Version Shorter Version
1. Shortening the function Boolean. This function takes one parameter and returnes Boolean type value true if that parameter is truthy and returns false otherwise.
2. Shortening the function Number. This function takes one parameter, converts it to number value and returns it.
3. This is very useful shorthand. Often we need to get one or another value and one of them has more priority than another(in this case foo has more priority). Often this shorthand is used with default values:

prop = value || defaultValue;
  return foo;
  return bar;
foo || bar
4. This is opposite case than previous: We want to take the second variable if first is defined (or truthy) and we want the first variable if it is not defined (or falsy).
  return bar;
  return foo;
foo && bar
5. This is very useful shorthand too known as “ternary operation”. Often we need to get one or another value or do one or another job depended on some logic.
  return val1;
  return val2;
(condition) ? val1 : val2;
6. When we want to give a value to some variable only once and use it in multiple times; for example to initialize a class just once (“singelton” pattern). The common case is when caching a DOM element. In shorthand is used evaluation of logical expressions.
  //calculate val just once
  val = calcVal();
//use val variable
(!val && (val = calcVal()) );
//use val variable

About Mariami Kupatadze
Oracle Certified Master Linkedin:

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: