Top 10 JavaScript Shorthands for Beginners
JavaScript shorthands not only speed up the coding process but also make scripts shorter, therefore lead to faster page loads. Shorthand codes are just as valid as their longhand versions; they essentially stand for the same thing–only in a more compact format. They are one of the simplest code optimization techniques.
There are several JavaScript shorthands, however they don’t have an official reference guide. Some are really simple, while others are quite intimidating even for experienced developers. In this article, you can find 10 JavaScript shorthands for beginners with which you can start out with code optimization and write more concise code.
Read Also: CSS Shorthand vs. Longhand – When to Use Which
1. Decimal numbers
If you regularly work with big decimals this shorthand can be godsend, as you don’t have to type out all the zeros anymore, just replace them with the e
notation. For instance, 1e8
means the addition of eight zeros after the 1
digit, it equals to 100000000
.
The number after the letter e
indicates the number of zeros that come after the digit(s) before e
. Likewise, 16e4
is the shorthand for 160000
, etc.
/* Shorthand */ var myVar = 1e8; /* Longhand */ var myVar = 100000000;
2. Increment, decrement
The increment shorthand is made up of two +
signs, it means that the value of a variable is to be incremented by one. Similarly, the decrement shorthand consists of two -
signs, and it means that the variable is to be decremented by one.
These two shorthands can be used only on numeric data types. They have an indispensable role in loops, their most frequent use case is the for
loop.
/* Shorthand */ i++; j--; /* Longhand */ i=i+1; j=j-1;
3. Add, distract, multiply, divide
There’s a shorthand for each of the four basic mathematical operations: addition, distraction, multiplication, and division. They work similarly to the increment and decrement operators, just here, you can change the value of a variable by any number (not just by one).
In the example below, the i
variable is incremented by 5
, j
is decremented by 3
, k
is multiplied by 10
, and l
is divided by 2
.
/* Shorthand */ i+=5; j-=3; k*=10; l/=2; /* Longhand */ i=i+5; j=j-3; k=k*10; l=l/2;
4. Determine character position
The charAt()
method is one of the most frequently used string methods, it returns the character at a specified position (for instance, the 5th character of a string). There’s a simple shorthand you can use instead: you add the character position enclosed in square brackets after the string.
Pay attention that the charAt()
method is zero-based. Therefore, myString[4]
will return the 5th character in the string ("y"
in the example).
var myString = "Happy birthday"; /* Shorthand */ myString[4]; /* Longhand */ myString.charAt(4);
5. Declare variables in bulk
If you want to create more than one variables at the same time you don’t have to type them out one by one. It’s sufficient to use the var
(or let
) keyword only once, then you can just list the variables you want to create, separated by a comma.
With this shorthand, you can declare both undefined variables and variables with a value.
/* Shorthand */ var i, j=5, k="Good morning", l, m=false; /* Longhand */ var i; var j=5; var k="Good morning"; var l; var m=false;
6. Declare an associative array
Declaring an array in JavaScript is a relatively simple task, by using the var myArray = ["apple", "pear", "orange"]
syntax. However, declaring an associative array is a little more complicated, as here, you don’t only have to define the values but also the keys (in case of regular arrays the keys are 0, 1, 2, 3, etc.
).
An associative array is a collection of key-value pairs. The longhand way is to declare the array, then add each element one by one. However, with the shorthand below, you can also declare the associative array plus all its elements at the same time.
In the example below, the myArray
associative array assigns their place of birth (values) to famous people (keys).
/* Shorthand */ var myArray = { "Grace Kelly": "Philadelphia", "Clint Eastwood": "San Francisco", "Humphrey Bogart": "New York City", "Sophia Loren": "Rome", "Ingrid Bergman": "Stockholm" } /* Longhand */ var myArray = new Array(); myArray["Grace Kelly"] = "Philadelphia"; myArray["Clint Eastwood"] = "San Francisco"; myArray["Humphrey Bogart"] = "New York City"; myArray["Sophia Loren"] = "Rome"; myArray["Ingrid Bergman"] = "Stockholm";
7. Declare an object
The shorthand for object declaration works similarly to the one for associative arrays. However here, there are not key-value pairs but property-value pairs that you need to place between the braces {}
.
The only difference in the shorthand syntax is that object properties are not enclosed in quotation marks (name
, placeOfBirth
, age
, wasJamesBond
in the example below).
/* Shorthand */ var myObj = { name: "Sean Connery", placeOfBirth: "Edinburgh", age: 86, wasJamesBond: true }; /* Longhand */ var myObj = new Object(); myObj.name = "Sean Connery"; myObj.placeOfBirth = "Edinburgh"; myObj.age = 86; myObj.wasJamesBond = true;
8. Use the conditional operator
The conditional (ternary) operator is frequently used as the shortcut for the if-else
statement. It consists of three parts:
- the condition
- what happens if the condition is true (
if
) - what happens if the condition is false (
else
)
In the example below, we send a simple message (inside the message
variable) to people who want to enter a club. Using the shorthand form, it’s just one line of code to run the evaluation.
var age = 17; /* Shorthand */ var message = age >= 18 ? "Allowed" : "Denied"; /* Longhand */ if( age >= 18) { var message = "Allowed"; } else { var message = "Denied"; }
If you want to test it just copy the code into the web console (F12 in most browsers) and modify the value of the age
variable a few times.
9. Check presence
It frequently happens that you need to check whether a variable is present or not. The “if presence” shorthand helps you do so with much less code.
Beware that most articles on JavaScript shorthands don’t give the proper longhand form, as the if( myVar )
notation doesn’t simply check if the variable is not false but also a handful of other things. Namely, the variable cannot be undefined, empty, null, and false.
var myVar = 99; /* Shorthand */ if( myVar ) { console.log("The myVar variable is defined AND it's not empty AND not null AND not false."); } /* Longhand */ if( typeof myVar !== "undefined" && myVar !== "" && myVar !== null && myVar !== 0 && myVar !== false ) { console.log("The myVar variable is defined AND it's not empty AND not null AND not false."); }
You can test how the “if presence” shorthand works by inserting the following code snippet into the web console and changing the value of myVar
a few times.
To understand how this shorthand works, it’s worth testing it with the values of ""
(empty string), false
, 0
, true
, a non-empty string (e.g. "Hi"
), a number (e.g. 99
), and when the variable is undefined (simply var myVar;
).
10. Check absence
The “if presence” shorthand can be used to check the absence of a variable by placing an exclamation mark before it. The exclamation mark is the logical not operator in JavaScript (and in most programming languages).
Therefore, with the if( !myVar )
notation, you can check if the myVar
variable is not undefined, empty, null, or false.
var myVar; /* Shorthand */ if( !myVar ) { console.warn("The myVar variable is undefined (OR) empty (OR) null (OR) false."); } /* Longhand */ if( typeof myVar === "undefined" || myVar === "" || myVar === null || myVar === 0 || myVar === false ) { console.warn("The myVar variable is undefined (OR) empty (OR) null (OR) false."); }
Read Also: JavaScript Jargon: 10 Terms You Should Know