The two new features updated today are designed to make coding easier and compatibility more compatible. GlobalThis provides a standard way to retrieve global objects in different environments. Optional chains are primarily about increasing the security of getting content from an object. You can also follow my wechat public number, snail full stack.

For the WEB(browser) environment, the global variable in JS is window/self, I believe you know more about window, also more familiar, small make up today also know the object of self, from the current point of view, can be considered the same. Here is an example of a delay

setTimeout(() = > {      
    console.log('lilei')},1000) // lilei
Copy the code

Because the above example is a global method, it would be if it were written in full

window.setTimeout(() = > {      
    console.log('lilei')},1000) // lilei
Copy the code
self.setTimeout(() = > {      
    console.log('lilei')},1000) // lilei
Copy the code

Also, we can customize a method that gets global variables in different environments, like this

const getGlobal = () = > {    
    if(typeofself ! = ='undefined') {return self    
}    
if(typeof window! = ='undefined') {return window    
}    
if(typeof global! = ='undefined') {return global    
}   
throw new Error('Unable to find global object')}
const testGlobal  = getGlobal()console.log(testGlobal)
Copy the code

With the introduction of globalThis in ES11, the above bunch of code can be shortened to this

console.log(globalThis)
Copy the code

Two, optional chain before xiaobian when looking at other people’s code found this symbol, but when searching on the Internet, do not know how to search, also temporarily put it off, until see the concept of optional chain, I did not suddenly understand. For example, when we call a property or method on an object, many times we don’t know whether the data passed from the back end actually has the specified property. In this case, our code would look like this:

const user = {    
    address: {street:'No.1 Street'.getNum(){            
        return '88'}}}const street = user && user.address && user.address.streetconsole.log(street) // No.1 Street
const streetNum= user && user.address && user.address.getNum && user.address.getNum() // Call console.log(streetNum) // 88
Copy the code

With the optional chain, our code can be written like this

conststreet = user ? .address ? .streetconsole.log(street)// No.1 Street
conststreetNum= user ? .address ? .getNum ? . ()console.log(streetNum) / / 88
Copy the code

Is it convenient and clear? That’s all for today’s sharing. It’s another day of progress. Come on!