Introduction to javascript Conditional Access Properties and Arrow Functions

  • 2021-12-05 05:30:50
  • OfStack

Directory 1. Conditional access properties 2. Introduction to arrow functions

1. Conditional access to properties

? Is a new feature introduced by ES 2020. It is a conditional attribute access operator. When you access a value of undefined Variable, if you use the. operator, it will report an error directly, and if you use the conditional property access operator to access it, it will return undefined .

Look at the example:


let book = {price:10,
            edition:10,
            name:"javascirpt"
}

console.log(book.page.num)

Direct error reporting:

TypeError: Cannot read property 'num' of undefined

Because book.page Value of undefined , undefined There is no attribute value, so an error will be reported.

If you can't be sure that a value is undefined Or object, in addition to the if statement can be used to judge, you can also directly use conditional access operators to access a certain attribute, even if the accessed object is undefined , also will not report errors. Instead, it returns undefined


console.log(book.page?.num)

Output:

undefined

2. Introduction to the arrow function

The arrow function is ES6 A shorthand method of defining a function, which appears in = > Separate the argument list from the function body.

Examples:


let square = x=>x**2;

console.log(square(3))

Output:

9

The definition of this function is equivalent to the traditional function:


function square(x){
    return x**2
}

Arrow functions are usually used to pass an unnamed function as an argument to another function.


let nums = [1,2,3,4].map(x=>x*2)

console.log(nums)

Output:

[ 2, 4, 6, 8 ]

The arrow function makes the code look simpler.

If you use the traditional function Keyword to define a function, it seems a bit verbose


nums = [1,2,3,4].map(function(x){return x*2})

console.log(nums)

If the arrow function has multiple parameters, it needs to be enclosed in parentheses


const add = (x,y)=>x+y;

console.log(add(1,2))

If the arrow function has more than one statement in its body, enclose the function body in braces and return the value using the return keyword


const add = (x,y)=>{let tmp=x+y;return tmp};

console.log(add(1,2))

At this time, the function body of the arrow function and the ordinary function The defined function body format is completely 1. Therefore, the arrow function is concise and readable in a simple single-line statement. 1 denier function body is too complex, and then using arrow function to define readability is not so good.


Related articles: