Search code examples
google-api-nodejs-client

why using var {google} instead of var google in google.auth.OAuth


This code is from oauth nodesjs. I want to ask why we are using '{}' around the var google? I also tried using it without '{}' and got error OAuth2 is undefined. i can't understand what is happening here.

var {google} = require('googleapis');
var OAuth2 = google.auth.OAuth2;

Solution

  • To add a little to this answer - this is what's called a destructuring assignment. You can read about them here:

    http://2ality.com/2015/01/es6-destructuring.html

    The code you're looking at here:

    const {google} = require('googleapis');

    Is the same as code that looks like this:

    const google = require('googleapis').google;

    This is just a convenient shorthand that was added in es6. We made the change in the googleapis package when we moved towards ES modules, which don't play nicely with the export=foo style syntax. Hope this helps!