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:

Explanation
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.
Boolean(value)
!!value
2. Shortening the function Number. This function takes one parameter, converts it to number value and returns it.
Number(value)
+value
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;
if(foo){
  return foo;
}else{
  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).
if(foo){
  return bar;
}else{
  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.
if(condition){
  return val1;
}else{
  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.
if(!val){
  //calculate val just once
  val = calcVal();
}
//use val variable
(!val && (val = calcVal()) );
//use val variable
Advertisements

Leave a Reply

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

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: