You can learn a lot from this collection, so look it over✨
15 JavaScript Shorthand Techniques — Ultimate CheatSheet
The robust and well-liked programming language JavaScript has a large built-in function library that may be used to do a variety of tasks.
This article covers 15 JavaScript features that every developer should know.
Whether you are a novice or a seasoned developer, these features will come in handy.
So, let’s discuss these 15 important JavaScript features.
1. Repeat a string
To repeat a string multiple times in JavaScript, you can use either the longhand or shorthand methods.
Longhand:
You can use a loop to repeat a string multiple times.
Here is an example of how to do this using a for
loop:
function repeatString(string, num) {
let result = '';
for (let i = 0; i < num; i++) {
result += string;}
return result;
}
console.log(repeatString('Hello', 5));
// Output: "HelloHelloHelloHelloHello"
Shorthand:
In the shorthand method, we use therepeat()
method to repeat a string multiple times.
repeat()
only supports modern browsers, so you must use the longhand approach to support older browsers.
Example:
console.log('Hello'.repeat(5));
// Output: "HelloHelloHelloHelloHello"
2. Combining of Arrays
In JavaScript, you can use both a longhand approach and a shortcut method for merging two or more arrays.
Longhand:
Here is an example of how to do this using afor
loop:
let array1 = [10, 20, 30];
let array2 = [40, 50, 60];
let mergedArray = [];
for (let i = 0; i < array1.length; i++) {
mergedArray.push(array1[i]);
}
for (let i = 0; i < array2.length; i++) {
mergedArray.push(array2[i]);
}
console.log(mergedArray);
// Output: [10, 20, 30, 40, 50, 60]
Shorthand:
For shorthand, you can use the concat()
,...
, and reduce()
method. Theconcat()
and...
methods combine the elements of two or more arrays by appending the elements of the second array to the end of the first array.
Here are examples of how to use the contact()
,...
methods:
// concat()let array1 = [10, 20, 30];
let array2 = [40, 50, 60];
let mergedArray = array1.concat(array2);
console.log(mergedArray);
// Output: [10, 20, 30, 40, 50, 60]
// ...
let array1 = [10, 20, 30];
let array2 = [40, 50, 60];
let mergedArray = [...array1, ...array2];
console.log(mergedArray);
// Output: [10, 20, 30, 40, 50, 60]
If you want to combine the arrays in a different way, you can use the reduce()
method.
Example:
// reduce()
let array1 = [10, 20, 30];
let array2 = [40, 50, 60];
let mergedArray = array1.reduce((acc, val) => acc.concat(val), array2);
console.log(mergedArray);
// Output: [40, 50, 60, 10, 20, 30]
3. Parameters a function accepts
You can find the number of parameters accepted by a function in 3 different ways.
Method 1:
Based on the number of named arguments in the function definition, the length
property of a function returns the number of arguments that the function expects to receive.
function myFunction(a, b, c) {
// function body
}
console.log(myFunction.length); // Output: 3
Method 2:
The parameters passed to a function are stored in an object called an argument
, which looks like an array. Using the length
property of the argument object, you can find out how many arguments were passed to the function.
Due to the fact that the objectsarguments
are not real arrays, not all array methods are accessible. Use theArray.from()
function to turn the arguments
object into an actual array if you wish to use array methods on it.
function myFunction(a, b, c) {
console.log(arguments.length); // Output: 3
}
myFunction(1, 2, 3);
You cannot use the arguments
object to figure out how many arguments a function expects from outside the function because it is only accessible inside the function. The length
property would then need to be used, just like in Method 1.
4. Loops in JavaScript
JavaScript provides several types of loops for repeating code blocks repeatedly.
Some examples of loops that are commonly used are:
for loop
The increment or decrement expression, the loop condition, and the variable for the for-loop are its three main parts. The loop will keep running as long as the condition is true.
Example of a for loop that counts from 1 to 5:
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Output:
1
2
3
4
5
for-in loop
You can iterate over an object’s properties with afor-in
loop.
In this example, we iterate over the properties of an object usingfor-in
loops.
Example:
let object = {a: 1, b: 2, c: 3};
for (let property in object) {
console.log(property + ": " + object[property]);
}
Output:
a: 1
b: 2
c: 3
for-of loop
If the iterable object is an array or string, you can use afor-of
loop to iterate over the values.
An array of elements is iterated over using afor-of
loop:
let array = [1, 2, 3];
for (let element of array) {
console.log(element);
}
Output:
1
2
3
5. String to Array
You can use thesplit
method to convert a string to an array in JavaScript. This method splits a string into substrings using a separator string or a regular expression.
The following example shows how to convert a string into an array using thesplit
method:
let string = "apple,banana,orange";
let array = string.split(",");
console.log(array); // prints ["apple", "banana", "orange"]
Using a shorthand method, you can achieve the same result:
let string = "apple,banana,orange";
let array = [...string.split(",")];
console.log(array); // prints ["apple", "banana", "orange"]
You can iterate over characters in a string by using a for loop
. Using this method, you can convert a string into an array by pushing each character into its own array.
An example would be:
let string = "apple,banana,orange";
let array = [];
for (let i = 0; i < string.length; i++) {
array.push(string[i]);
}
console.log(array); // prints ["a", "p", "p", "l", "e", ",", "b", "a", "n", "a", "n", "a", ",", "o", "r", "a", "n", "g", "e"]
In this method, instead of splitting the string into substrings, each character of the string is a separate element in an array. The split method allows you to separate a string based on a separator, as shown in the first two examples.
6. Max and Min in an Array
You can find the maximum and minimum numbers in an array using the JavaScript examples below.
Longhand:
// Find the maximum number in an array
const array = [3, 7, 1, 9, 2, 5];
let maxNumber = array[0];
for (let i = 1; i < array.length; i++) {
if (array[i] > maxNumber) {
maxNumber = array[i];
}
}
console.log(maxNumber); // Output: 9
// Find the minimum number in an array
const array = [3, 7, 1, 9, 2, 5];
let minNumber = array[0];
for (let i = 1; i < array.length; i++) {
if (array[i] < minNumber) {
minNumber = array[i];
}
}
console.log(minNumber); // Output: 1
Using Math.max()
and Math.min()
, you can easily calculate the maximum or minimum:
// Find the maximum number in an array
const array = [3, 7, 1, 9, 2, 5];
const maxNumber = Math.max(...array);
console.log(maxNumber); // Output: 9
// Find the minimum number in an array
const array = [3, 7, 1, 9, 2, 5];
const minNumber = Math.min(...array);
console.log(minNumber); // Output: 1
// Find the maximum number in an array
const array = [3, 7, 1, 9, 2, 5];
const maxNumber = Math.max(...array);
console.log(maxNumber); // Output: 9
// Find the minimum number in an array
const array = [3, 7, 1, 9, 2, 5];
const minNumber = Math.min(...array);
console.log(minNumber); // Output: 1
7. Convert strings to numbers
To convert strings to numbers in JavaScript, there are several methods.
Using the parseInt()
or parseFloat()
functions:
// Convert a string to an integer
const num1 = "42";
const num2 = parseInt(num1); // num2 is now of type number with the value 42
// Convert a string to a float
const num3 = "3.14";
const num4 = parseFloat(num3); // num4 is now of type number with the value 3.14
Using the unary plus operator(+)
:
// Convert a string to a number
const num1 = "42";
const num2 = +num1; // num2 is now of type number with the value 42
// Convert a string to a negative number
const num3 = "-42";
const num4 = +num3; // num4 is now of type number with the value -42
8. Assigning values to multiple variables
JavaScript provides both longhand and shorthand functions for assigning values to multiple variables:
Using the individual assignment statement method:
let x;
let y;
let z;
x = 1;
y = 2;
z = 3;
Destructuring assignment shorthand method:
let x, y, z;
[x, y, z] = [1, 2, 3];
Destructuring assignment can also be used to assign variables from an object:
const obj = {a: 1, b: 2, c: 3};
let a, b, c;
({a, b, c} = obj);
9. Exponent power
There are several ways to calculate the exponent power of a number in JavaScript. Here are some examples:
Using for
loop:
function power(base, exponent) {
let result = 1;
for (let i = 0; i < exponent; i++) {
result *= base;
}
return result;
}
console.log(power(2, 3)); // Output: 8
Using the Math.pow()function:
function power(base, exponent) {
return Math.pow(base, exponent);
}
console.log(power(2, 3)); // Output: 8
Also, you can find the exponent power of a number by using the exponentiation operator (**
):
const base = 2;
const exponent = 3;
const result = base ** exponent; // result is now 8
10. Double bitwise Not operator (~~)
With the help of the (~~
) operator, you can round a number to the closest integer.
Example:
const num = 3.14;
const roundedNum = ~~num; // roundedNum is now 3
You can use (~~) operators in place of Math.floor().
const num = 3.14;
const roundedNum = Math.floor(num); // roundedNum is now 3
You can also use (~~
) to transform a non-integer value into an integer.
For example:
const num = "3.14";
const intNum = ~~num; // intNum is now 3
This is similar to using the parseInt()function:
const num = "3.14";
const intNum = parseInt(num); // intNum is now 3
11. Default Value to a Function Parameter
In JavaScript, you can assign default values to function parameters in different ways.
Longhand:
function greet(name) {
name = name || 'Anonymous';
console.log(`Hello, ${name}!`);
}
In the example above, the name
parameter has a default value of 'Anonymous'
. If no value is passed for the name
parameter when the greet
function is called, it will use the default value.
Shorthand:
function greet(name = 'Anonymous') {
console.log(`Hello, ${name}!`);
}
In this example, the default value for the name
parameter is specified directly in the function definition, using the =
syntax. If no value is passed for the name
parameter when the greet
function is called, it will use the default value.
12. Ternary Operator
It is also known as the conditional operator or the ternary conditional operator.
The syntax for the Ternary Operator in JavaScript is:
condition ? value_if_true : value_if_false;
if-else
You can use the if-else statement to achieve the same result as with the ternary operator.
Example:
let x = 10;
let y = 20;
if (x > y) {
maxValue = x;
} else {
maxValue = y;
}
console.log(maxValue); // Output 20
In the following example, we will use the JavaScript ternary operator:
let x = 10;
let y = 20;
let maxValue = (x > y) ? x : y;
console.log(maxValue); // Output 20
In this example, the condition x > y
is evaluated to be false
, so the value of y
is assigned to maxValue
. If the condition had been true
, the value of x
would have been assigned to maxValue
instead.
The ternary operator can be helpful for expressing conditional logic in a single line of code, despite the fact that it can be more challenging to read and understand than the if-else form.
It’s a good idea to use the ternary operator when the conditional logic becomes more complicated.
13. Swap two variables
In JavaScript, to swap the values of two variables, you can use different methods.
Here are some examples:
Longhand:
let x = 1;
let y = 2;
let temp = x;
x = y;
y = temp;
In the example above, we create a temporary variable (temp) to store the value of x, then assign the value of x to the value of y and the value of y to temp.
let x = 1;
let y = 2;
[x, y] = [y, x];
In this example, the values of x and y are swapped using the destructuring assignment method. You can assign variables to the elements of an array or object using the destructuring assignment. Without the need for a temporary variable, it can be a convenient way to swap values.
If either approach is used, x will be 2 and y will be 1.
14. Check Multiple Conditions
There are a few different ways you can check multiple conditions in JavaScript.
Here are a few options:
1. Using the **&&**
operator:
This operator allows you to check if multiple conditions are true.
For example:
if (x > 0 && y < 10) {
// execute some code
}
This will only execute the code inside the if statement if both conditions (x > 0 and y < 10) are true.
2. Using the **||**
operator:
This operator allows you to check if at least one of the multiple conditions is true.
For example:
if (x === 1 || x === 2 || x === 3) {
// execute some code
}
This will execute the code inside the if statement if x is equal to 1, 2, or 3.
3. Using the switch
statement:
This allows you to check multiple conditions and execute different code blocks depending on the value of a given expression. For example:
switch (x) {
case 1:
// execute some code
break;
case 2:
// execute some code
break;
case 3:
// execute some code
break;
default:
// execute some code
}
This will execute the code inside the case block that matches the value of x. If none of the cases match, the code inside the default block will be executed.
It’s important to note that the &&
and ||
operators have a specific order of precedence, so you may need to use parentheses to group conditions in the way that you want.
4. Array.prototype.include()
You can use the Array.prototype.include() method to check multiple conditions in JavaScript.
Example:
const value = 2;
if ([1, 'one', 2, 'two'].includes(value)) {
console.log('The value is either 1, "one", 2, or "two"');
} else {
console.log('The value is not 1, "one", 2, or "two"');
}
// Output: The value is either 1, "one", 2, or "two"
The Array.prototype.include() the
function checks to see if a value is present. The code inside the if block will be run in the example above if the value is present. If the value cannot be found, the code in the else block will be executed.
15. Remove Properties
The delete operator allows you to delete a number of properties from an object.
Take the following as an example:
let obj = {
prop1: 'value1',
prop2: 'value2',
prop3: 'value3',
prop4: 'value4'
};
delete obj.prop1;
delete obj.prop3;
console.log(obj); // Outputs { prop2: 'value2', prop4: 'value4' }
Alternatively, you can use the Object.assign()
method to create a new object with the desired properties removed.
Example:
let obj = {
prop1: 'value1',
prop2: 'value2',
prop3: 'value3',
prop4: 'value4'
};
let newObj = Object.assign({}, obj);
delete newObj.prop1;
delete newObj.prop3;
console.log(newObj); // Outputs { prop2: 'value2', prop4: 'value4' }
In modern JavaScript (ES6 and later), you can use the Object.entries()
and Object.fromEntries()
methods to remove multiple properties from an object.
Example:
let obj = {
prop1: 'value1',
prop2: 'value2',
prop3: 'value3',
prop4: 'value4'
};
let newObj = Object.fromEntries(
Object.entries(obj).filter(([key]) => key !== 'prop1' && key !== 'prop3')
);
console.log(newObj); // Outputs { prop2: 'value2', prop4: 'value4' }
Wrap up
In this article, we reviewed 15 JavaScript features every developer should know. These JavaScript features will make your life easier, no matter what level of experience you have.
I hope that it was useful. If so, follow me Ishrat if you haven’t already, for more helpful content like this.
Thank you for reading, and happy coding!✌🏻
You can also find me on Twitter, GitHub, Hashnode, and DEV.to.