Shorthand tips that JavaScript developers need to know (advanced)
This article brings you the abbreviation skills that JavaScript developers need to know (advanced). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. Variable assignment
When assigning the value of one variable to another variable, you first need to ensure that the original value is not null, undefined or empty.
This can be achieved by writing a judgment statement containing multiple conditions:
if (variable1 !== null || variable1 !== undefined || variable1 !== '') { let variable2 = variable1; }
or abbreviated to the following form:
const variable2 = variable1 || 'new';
You can paste the following code into es6console , Test by yourself:
let variable1; let variable2 = variable1 || ''; console.log(variable2 === ''); // prints true variable1 = 'foo'; variable2 = variable1 || ''; console.log(variable2); // prints foo
2. Default value assignment
If the expected parameter is null or undefined, there is no need to write six lines of code to assign a default value. We can accomplish the same operation in just one line of code using just a short logical operator.
let dbHost; if (process.env.DB_HOST) { dbHost = process.env.DB_HOST; } else { dbHost = 'localhost'; }
The abbreviation is:
const dbHost = process.env.DB_HOST || 'localhost';
3. Object attributes
ES6 provides a very simple way to assign attributes to objects. If the property name is the same as the key name, the abbreviation can be used.
const obj = { x:x, y:y };
The abbreviation is:
const obj = { x, y };
4. Arrow function
Classic functions are easy to read and write, but if they are nested in other functions and called, the entire function It can get a little long and confusing. At this time, you can use the arrow function to abbreviate it:
function sayHello(name) { console.log('Hello', name); } setTimeout(function() { console.log('Loaded') }, 2000); list.forEach(function(item) { console.log(item); });
The abbreviation is:
sayHello = name => console.log('Hello', name); setTimeout(() => console.log('Loaded'), 2000); list.forEach(item => console.log(item));
5. Implicit return value
The return value is what we usually use to return the final result of the function Keywords. An arrow function with only one statement can return a result implicitly (the function must omit the parentheses ({ }) in order to omit the return keyword).
To return a multi-line statement (such as object text), you need to use () instead of {} to wrap the function body. This ensures that the code is evaluated as a single statement.
function calcCircumference(diameter) { return Math.PI * diameter }
The abbreviation is:
calcCircumference = diameter => ( Math.PI * diameter; )
6. Default parameter value
You can use the if statement to define the default value of the function parameter. ES6 provides that default values can be defined in function declarations.
function volume(l, w, h) { if (w === undefined) w = 3; if (h === undefined) h = 4; return l * w * h; }
The abbreviation is:
volume = (l, w = 3, h = 4 ) => (l * w * h); volume(2) //output: 24
7. Template string
In the past, we were used to using " " to convert multiple variables into strings, but is there a simpler way? What about the method?
ES6 provides corresponding methods, we can use backticks and $ { } to combine variables into a string.
const welcome = 'You have logged in as ' + first + ' ' + last + '.' const db = 'http://' + host + ':' + port + '/' + database;
The abbreviation is:
const welcome = `You have logged in as ${first} ${last}`; const db = `http://${host}:${port}/${database}`;
8. Destructuring assignment
Destructuring assignment is an expression used to quickly extract attribute values from an array or object and assign them to defined variables.
In terms of code abbreviation, destructuring assignment can achieve good results.
const observable = require('mobx/observable'); const action = require('mobx/action'); const runInAction = require('mobx/runInAction'); const store = this.props.store; const form = this.props.form; const loading = this.props.loading; const errors = this.props.errors; const entity = this.props.entity;
The abbreviation is:
import { observable, action, runInAction } from 'mobx'; const { store, form, loading, errors, entity } = this.props;
You can even specify your own variable name:
const { store, form, loading, errors, entity:contact } = this.props;
9. Expansion operator
The expansion operator is in ES6 Introduced, using the spread operator can make JavaScript code more efficient and interesting.
Some array functions can be replaced by using the spread operator.
// joining arrays const odd = [1, 3, 5]; const nums = [2 ,4 , 6].concat(odd); // cloning arrays const arr = [1, 2, 3, 4]; const arr2 = arr.slice( )
The abbreviation is:
// joining arrays const odd = [1, 3, 5 ]; const nums = [2 ,4 , 6, ...odd]; console.log(nums); // [ 2, 4, 6, 1, 3, 5 ] // cloning arrays const arr = [1, 2, 3, 4]; const arr2 = [...arr];
The difference between the functions of concat() and concat() is that the user can use the spread operator to insert another array into any array.
const odd = [1, 3, 5 ]; const nums = [2, ...odd, 4 , 6];
You can also use the expansion operator in combination with ES6 destructuring symbols:
const { a, b, ...z } = { a: 1, b: 2, c: 3, d: 4 }; console.log(a) // 1 console.log(b) // 2 console.log(z) // { c: 3, d: 4 }
10. Mandatory parameters
By default, if no value is passed to the function parameter, then JavaScript will set the function parameters to undefined. Other languages will issue warnings or errors. To perform parameter assignment, you can use an if statement to throw an undefined error, or you can take advantage of "forced parameters".
function foo(bar) { if(bar === undefined) { throw new Error('Missing parameter!'); } return bar; }
The abbreviation is:
mandatory = ( ) => { throw new Error('Missing parameter!'); } foo = (bar = mandatory( )) => { return bar; }
11. Array.find
If you have ever written the find function in ordinary JavaScript, then you may have used a for loop. In ES6, a new array function called find() was introduced, which is shorthand for implementing a for loop.
const pets = [ { type: 'Dog', name: 'Max'}, { type: 'Cat', name: 'Karl'}, { type: 'Dog', name: 'Tommy'}, ] function findDog(name) { for(let i = 0; i<pets.length><p>The abbreviation is: </p><pre class="brush:php;toolbar:false">pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy'); console.log(pet); // { type: 'Dog', name: 'Tommy' }
12. Object [key]
Although it is a common practice to write foo.bar as foo ['bar'], this These practices form the basis for writing reusable code.
Please consider the following simplified example of a verification function:
function validate(values) { if(!values.first) return false; if(!values.last) return false; return true; } console.log(validate({first:'Bruce',last:'Wayne'})); // true
The above function completes the verification work perfectly. But when there are many forms, validation needs to be applied, and there will be different fields and rules. It would be a good choice if you could build a generic validation function that can be configured at runtime.
// object validation rules const schema = { first: { required:true }, last: { required:true } } // universal validation function const validate = (schema, values) => { for(field in schema) { if(schema[field].required) { if(!values[field]) { return false; } } } return true; } console.log(validate(schema, {first:'Bruce'})); // false console.log(validate(schema, {first:'Bruce',last:'Wayne'})); // true
Now with this validation function, we can reuse it in all forms without having to write a custom validation function for each form.
13. Double-bit operators
Bit operators are the basic knowledge points in JavaScript beginner tutorials, but we don’t often use bit operators. Because no one wants to work with 1s and 0s without dealing with binary.
But the double-bit operator has a very practical case. You can use double-bit operators instead of Math.floor( ). The advantage of the double-negative positioning operator is that it performs the same operation faster.
Math.floor(4.9) === 4 //true
The abbreviation is:
~~4.9 === 4 //true
The above is a complete introduction to the abbreviation techniques that JavaScript developers need to know (advanced), if you want to know more about JavaScript video tutorial, please pay attention to the PHP Chinese website.
The above is the detailed content of Shorthand tips that JavaScript developers need to know (advanced). For more information, please follow other related articles on the PHP Chinese website!

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Zend Studio 13.0.1
Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor