Front-end development engineer (main job), technical blogger (side job), passed CET6
Ashan and her cat_CSDN personal homepage
Senior topic writer at Niuke, creating a high-quality column “Essentials for Front-end Interviews” at Niuke
The contracted author of Lanqiao Cloud Class, the front-end and back-end practical courses “Vue.js and Egg.js Develop Enterprise-level Health Management Projects” and “Take you to fully master uni-app from entry to practice” have been launched on Lanqiao Cloud Class
Article directory
-
- 1. Use arrow functions
- 2. Abbreviation for object literal
- 3. Destructuring assignment
- 4. Default parameters
- 5. Template string
- 6. Abbreviated conditional judgment
- 7. Short circuit evaluation
- 8. Truth judgment
- 9. Abbreviation for array methods
- 10. Use the spread operator
- 11. Abbreviated attribute methods
- 12. Shorthand syntax for using arrow functions
- 13. Combination of array destructuring assignment and function default parameters
- 14. Abbreviated object method definition
- 15. Using `Array.from` and `Array.of`
When coding JavaScript, there are many shorthand techniques that can improve development efficiency.
Here are 15 commonly used JS abbreviation techniques:
1. Use arrow functions
Use arrow function () => {}
to replace traditional function expressions and simplify function definition.
Traditional function expression:
function add(a, b) {<!-- --> return a + b; }
Arrow function simplified definition:
const add = (a, b) => a + b;
By using arrow functions, we can express the syntax of function definitions more concisely, omitting the function
keyword and the return
statement. The characteristic of the arrow function is that it automatically binds the this
value of the current scope, so it is more convenient and concise to use it in some callbacks or higher-order functions. Keep in mind that there are some differences in semantics and scope binding between arrow functions and traditional function expressions, and be aware of these differences when using them.
2. Abbreviation for object literal
When the name and value of an object attribute are the same, you can write only the attribute name, omitting colons and repeated variable names.
You can omit the property name and colon in the object literal. When the property name and variable name are the same, just write the property name. This is very useful in improving code readability.
For example, traditional writing:
const x = 1; const y = 2; const obj = {<!-- --> x: x, y: y };
Use abbreviations:
const x = 1; const y = 2; const obj = {<!-- --> x, y };
In this example, the attribute name and variable name x
and y
are the same, so we can directly omit the colon and repeated variable name in the object literal and just write the attribute name. This can reduce code redundancy and make the code more concise and easier to read.
3. Destructuring assignment
Use destructuring assignment syntax to extract multiple values from an array or object at once, simplifying variable declaration and assignment.
The destructuring assignment syntax makes it easy to extract multiple values from an array or object at once and assign them to the corresponding variables. This simplifies the process of declaring and assigning variables.
- Extract multiple values from an array:
const arr = [1, 2, 3]; //traditional writing const a = arr[0]; const b = arr[1]; const c = arr[2]; //Use destructuring assignment const [a, b, c] = arr;
- Extract multiple values from an object:
const obj = {<!-- --> x: 1, y: 2, z: 3 }; //traditional writing const x = obj.x; const y = obj.y; const z = obj.z; //Use destructuring assignment const {<!-- --> x, y, z } = obj;
In these examples, we used destructuring assignment syntax to extract multiple values from arrays and objects at once and assign them to the corresponding variables. This simplifies the code and makes the declaration and assignment process more concise and readable. Please note that when destructuring assignment, the variable name needs to be consistent with the property name in the array or object, so that the corresponding value can be extracted correctly.
4. Default parameters
Using default parameters in function declarations can simplify calling functions and avoid passing undefined or null.
Indeed, using default parameters in function declarations simplifies function calls and avoids passing undefined or null . Default parameters allow us to specify the default value of a parameter when defining a function. If the function does not provide a value for the parameter when it is called, the default value will be used.
Here is an example showing how to use default parameters in a function declaration:
function greet(name = 'Guest') {<!-- --> console.log(`Hello, ${<!-- -->name}!`); } greet(); // Output: Hello, Guest! greet('Alice'); // Output: Hello, Alice!
In the above example, we define a function called greet
and set the default value 'Guest'
for the name
parameter. When a function is called without providing a value for the name
parameter, the default value 'Guest'
will be used instead. This way, we can simply call greet()
without passing arguments explicitly, or passing undefined or null.
Using default parameters not only simplifies the way functions are called, but also improves code readability and flexibility. We can still pass a new value to override the default parameter if needed.
Note: The default value of a default parameter can be any legal expression, such as a constant, variable, function call, etc.
5. Template string
Use template strings (“) instead of string concatenation, and use the ${}
syntax to conveniently insert variables.
When we need to insert variables into a string, we can use template strings (“) and ${} syntax instead of traditional string concatenation. This syntax is more concise and intuitive.
Here’s an example showing how to use template strings and the ${} syntax to insert variables:
const name = 'Alice'; const age = 28; // Traditional string concatenation const message = 'My name is ' + name + ' and I am ' + age + ' years old.'; console.log(message); // Use template strings and ${} syntax const message = `My name is ${<!-- -->name} and I am ${<!-- -->age} years old.`; console.log(message);
In the above example, we use template strings instead of traditional string concatenation. In the template string, we use the ${} syntax to insert variables and embed the value of the variable into the string. This makes the code more concise and readable, and avoids tedious string concatenation operations.
6. Abbreviated conditional judgment
Use the ternary operator (condition ? value1 : value2
) to simplify simple conditional judgments.
Yes, using the ternary operator can simplify simple conditional judgments, especially when you need to select different values based on conditions. The syntax of the ternary operator is condition ? value1 : value2
.
Here is an example that shows how to use the ternary operator to simplify a simple conditional judgment:
function getDiscount(price, isMember) {<!-- --> const discount = isMember ? 0.2 : 0; // If isMember is true, discount is 0.2, otherwise it is 0 return price - (price * discount); } console.log(getDiscount(100, true)); // Output: 80 console.log(getDiscount(100, false)); // Output: 100
In the above example, we define a function called getDiscount
that determines the discount value based on the value of the isMember
parameter. If isMember
is true (i.e. a member), the discount is 0.2, otherwise the discount is 0. By using the ternary operator, we can quickly select different values based on conditions and perform corresponding calculations in the function.
Using the ternary operator can simplify your code, making it more concise and readable. However, please note that too complex conditional judgments may reduce the readability of the code, so please use the ternary operator moderately. In some cases, it may be clearer and more readable to use an if-else
statement.
7. Short-circuit evaluation
Use logical AND ( & amp; & amp;
) and logical OR (||
) to perform short-circuit evaluation and simplify some conditional judgments.
The logical AND (& &) and logical OR (||) operators can be used to short-circuit evaluation, thereby simplifying some conditional judgments. This technique is called “short-circuit evaluation”, and it takes advantage of the properties of logical operators: logical AND ( & & ) short-circuit when the previous condition is false, logical OR (||) when the previous condition is false True short circuit.
Here is an example that shows how to use short-circuit evaluation to simplify conditional evaluation:
function greet(user) {<!-- --> const name = user & amp; & amp; user.name || 'Guest'; console.log(`Hello, ${<!-- -->name}!`); } greet({<!-- --> name: 'Alice' }); // Output: Hello, Alice! greet(null); // Output: Hello, Guest! greet(undefined); // Output: Hello, Guest!
In the above example, we defined a function called greet
that accepts a user
parameter. Using short-circuit evaluation, we first determine whether user
exists (not null or undefined). If it exists, use user.name
as the name; otherwise, use the default value 'Guest'
. In this way, we can determine whether the user
object exists and has a name in one line of code, avoiding explicit if-else judgment statements.
Please note that when using short-circuit evaluation, you need to pay attention to the order of operands and the logic of conditional judgment. Make sure that the operand order of logical AND (& &) and logical OR (||) is consistent with the order of conditional evaluation to ensure correct short-circuit evaluation.
Short-circuit evaluation can improve code simplicity and readability in some cases, but it can also make code difficult to understand at other times. Be sure to keep your code clear and maintainable when using short-circuit evaluation.
8. Truth value judgment
Use !!
to convert a value to the corresponding Boolean value to determine whether a variable is true.
You can use !!
to convert a value to the corresponding Boolean value. This technique is called “double negation” and it takes advantage of the type conversion rules in JavaScript.
Here is an example showing how to use !!
to determine whether a variable has a true value:
function isTruthy(value) {<!-- --> return !!value; } console.log(isTruthy(0)); // Output: false console.log(isTruthy('')); // Output: false console.log(isTruthy(null)); // Output: false console.log(isTruthy(undefined)); // Output: false console.log(isTruthy(false)); // Output: false console.log(isTruthy(1)); // Output: true console.log(isTruthy('hello')); // Output: true console.log(isTruthy({<!-- -->})); // Output: true console.log(isTruthy(true)); // Output: true
In the above example, we defined a function called isTruthy
that accepts a value
parameter. By using !!value
, we convert value
into the corresponding boolean value. If value
is a true value (non-zero, non-empty string, non-null, non-undefined, non-false), return true
; otherwise, return false
.
The function of double negation is to convert any value into its corresponding Boolean value, simplifying the process of truth value judgment. It can be used in scenarios such as conditional judgment and logical operations to make the code more concise and intuitive.
It should be noted that the double negation operator !!
is mandatory when converting to a Boolean value. If you only need to determine whether a variable is a true value, you can directly use the variable as a judgment in the conditional statement. condition without using double negation. Using double negation is often used to explicitly convert a value to a Boolean value.
9. Abbreviation of array method
Use array methods such as map
, filter
, reduce
, etc. to replace loop operations and improve code simplicity.
Using array methods such as map
, filter
, reduce
, etc. can operate arrays more concisely, replacing traditional loop operations. They provide a functional programming style that makes code easier to read, write, and maintain. Here is some sample code showing how to use these array methods:
1. Use the map
method:
const numbers = [1, 2, 3, 4, 5]; const squaredNumbers = numbers.map(num => num ** 2); console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25] const doubledNumbers = numbers.map(num => num * 2); console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
In the above example, we use the map
method to operate on each element in the array numbers
to generate a new array. The first example puts the square of each number into the squaredNumbers
array, and the second example puts the multiplication of each number by 2 into the doubledNumbers
array.
2. Use the filter
method:
const numbers = [1, 2, 3, 4, 5]; const evenNumbers = numbers.filter(num => num % 2 === 0); console.log(evenNumbers); // Output: [2, 4] const oddNumbers = numbers.filter(num => num % 2 !== 0); console.log(oddNumbers); // Output: [1, 3, 5]
In the above example, we use the filter
method to filter the array numbers
according to the specified conditions and generate a new array. The first example filters out the even numbers in the array, and the second example filters out the odd numbers in the array.
3. Use the reduce
method:
const numbers = [1, 2, 3, 4, 5]; const sum = numbers.reduce((total, num) => total + num, 0); console.log(sum); // Output: 15 const max = numbers.reduce((maxNum, num) => (num > maxNum ? num : maxNum), -Infinity); console.log(max); // Output: 5
In the above example, we use the reduce
method to reduce the elements in the array numbers
to a value. The first example uses the reduce
method to calculate the sum of all numbers in an array, with an initial value of 0. The second example uses the reduce
method to find the maximum value in an array, with an initial value of negative infinitesimal.
These are examples of using array methods such as map
, filter
, reduce
, etc. instead of looping operations. They can significantly simplify code and provide rich functionality for manipulating and transforming array data.
10. Using spread operators
Use the spread operator (...
) to merge arrays, copy arrays or objects, and simplify related operations.
Use the spread operator (...
) to simplify operations in JavaScript by merging arrays and copying arrays or objects. Here is some sample code demonstrating how to use the spread operator:
1. Merge arrays:
const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; const mergedArray = [...arr1, ...arr2]; console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]
In the above example, we use the spread operator ...
to merge two arrays arr1
and arr2
into a new array mergedArray
.
2. Copy array:
const originalArray = [1, 2, 3]; const copiedArray = [...originalArray]; console.log(copiedArray); // Output: [1, 2, 3]
The above example shows how to use the spread operator ...
to quickly copy an array. By extending the original array into a new array, we create a copy with the same elements.
3. Merge objects:
const obj1 = {<!-- --> foo: 'bar' }; const obj2 = {<!-- --> baz: 'qux' }; const mergedObject = {<!-- --> ...obj1, ...obj2 }; console.log(mergedObject); // Output: { foo: 'bar', baz: 'qux' }
In the above example, we use the spread operator ...
to merge two objects obj1
and obj2
into a new object mergedObject
. In this way, we can combine the properties of multiple objects into a new object.
The spread operator simplifies the code in these examples, allowing us to merge arrays and copy arrays or objects more conveniently. It can be applied to arrays, objects, and iterable objects introduced in ES6 (such as strings, Sets, Maps, etc.).
11. Abbreviated attribute method
Use the shorthand form of the function in the object, just write the function name, omit the colon and the function
keyword.
Using shorthand forms of functions in objects can make your code more concise. In ES6, we can use function names directly in object literals to define function properties, omitting the colon and function
keyword. Here is a sample code:
const obj = {<!-- --> name: 'John', age: 30, greet() {<!-- --> console.log(`Hello, my name is ${<!-- -->this.name}. I'm ${<!-- -->this.age} years old.`); } }; obj.greet(); // Output: Hello, my name is John. I'm 30 years old.
In the above example, we have defined an object obj
that contains a function attribute named greet
. Here the function name greet
is used directly to define the function, and the colon and function
keyword are omitted. Functions can be called like normal functions.
By using the abbreviated form of functions, we can define and use functions in objects more clearly, avoiding the traditional lengthy syntax, making the code easier to read and write.
12. Shorthand syntax for using arrow functions
When there is only one parameter, the parentheses can be omitted; when the function body has only one return statement, the curly braces and return
can be omitted.
When a function has only one parameter, the parentheses outside the parameter can be omitted. When the function body has only one return statement, the curly braces and return
keyword can also be omitted. Here is some sample code to illustrate both cases:
1. Omit parameter brackets:
const square = x => x * x; console.log(square(5)); // Output: 25
In the above example, the square
function has only one parameter, x
, so we can omit the parentheses of the parameter.
2. Omit the curly braces and return
:
const greet = name => `Hello, ${<!-- -->name}!`; console.log(greet('John')); // Output: Hello, John!
In the above example, the greet
function has only one return statement, which returns a string, and no other logic needs to be performed. Therefore, we can omit the curly braces and return
keyword.
This shorthand form can make single-parameter functions and simple return statements more concise, improving the readability and simplicity of the code. Please note that this shorthand form is suitable for specific cases, if the function requires multiple parameters or contains complex logic, you still need to use the full syntax form to define the function.
13. Combination of array destructuring assignment and function default parameters
Combine default parameters with array destructuring assignment to simplify the initialization and assignment of function parameters.
By using default parameters in conjunction with array destructuring assignment, we can simplify the initialization and assignment of function parameters. Here is a sample code:
function printUser({<!-- --> name = 'John', age = 30, city = 'New York' }) {<!-- --> console.log(`Name: ${<!-- -->name}`); console.log(`Age: ${<!-- -->age}`); console.log(`City: ${<!-- -->city}`); } printUser({<!-- --> name: 'Alice', age: 25 }); // Output: // Name: Alice // Age: 25 // City: New York printUser({<!-- -->}); // Output: // Name: John // Age: 30 // City: New York
In the above example, we define a function named printUser
, which accepts an object as a parameter and uses object destructuring assignment to assign the property value to the variable name
, age
and city
. We also use the default parameter to specify a default value for the corresponding property when the function is called.
In this way, we can directly use the destructured assigned variables inside the function without having to manually perform the steps of parameter initialization and assignment. This simplifies the code, making it clearer and more readable, especially when dealing with functions with multiple arguments. If the corresponding property is not provided when calling the function, the default value will be used for initialization.
14. Abbreviated object method definition
Use the shorthand form of the method in the object, omitting the function
keyword and the colon.
The shorthand for using methods in an object is a syntax that omits the function
keyword and the colon. Here is a sample code:
const person = {<!-- --> name: 'John', age: 30, sayHello() {<!-- --> console.log(`Hello, my name is ${<!-- -->this.name}.`); } }; person.sayHello(); // Output: Hello, my name is John.
In the above example, we define a person
object with name
and age
properties, and a sayHello
> method. Notice that the definition of the sayHello
method does not use colons and the function
keyword, but directly writes the function body of the method.
This shorthand makes method definitions in objects more concise. In object literals, if we want to define a simple function as a method, we can directly omit the colon and the function
keyword and write the function body in the position of the method. This reduces redundant code and makes the code clearer and easier to read, especially when we define multiple methods at the same time.
15. Use Array.from
and Array.of
Use Array.from
to convert iterable objects (such as strings and array-like objects) to arrays, and Array.of
to create new arrays with fixed parameters.
Use Array.from
to convert iterable objects (such as strings and array-like objects) into a new array. And Array.of
can create a new array with fixed parameters. Here are two sample codes:
//Use Array.from to convert the string into an array const str = 'Hello'; const arr = Array.from(str); console.log(arr); // Output: [ 'H', 'e', 'l', 'l', 'o' ] // Use Array.from to convert array-like objects to arrays const arrayLike = {<!-- --> 0: 'a', 1: 'b', 2: 'c', length: 3 }; const arr2 = Array.from(arrayLike); console.log(arr2); // Output: [ 'a', 'b', 'c' ] // Use Array.of to create a new array with fixed parameters const newArr = Array.of(1, 2, 3, 4, 5); console.log(newArr); // Output: [1, 2, 3, 4, 5]
In the example code above, the string 'Hello'
is first converted into a new character array arr
using Array.from
. We then use Array.from
to convert an array-like object arrayLike
into an array arr2
.
Next, we use Array.of
to create a new array newArr
and pass the parameters 1, 2, 3, 4, 5
as The elements of the array are passed in.
These two methods make it easy to convert data and create new arrays. Array.from
can handle iterable objects, while Array.of
can create new arrays with fixed parameters, making the code more concise and readable.
These shorthand techniques can make code more concise, readable, and efficient, but make sure you and your team have a clear understanding of them when using them to avoid code that is difficult to understand or maintain.