DEV Community

loading...
Cover image for Optional chaining and Nullish coalescing operators in AWS Lambda Node.js 14

Optional chaining and Nullish coalescing operators in AWS Lambda Node.js 14

web2033 profile image Eugene Kopich Updated on ・1 min read

Node.js 14 introduces some new features and concepts. Highlights:

  • Nullish coalescing. This introduces ?? which is safer than using || for assignment (as it only evaluates to false for null or undefined).

  • Optional chaining. This introduces ?. which allows safe access to deep keys on objects that may not exist.

The simplest AWS Lambda function that uses both these features:

// AWS_LAMBDA_JS_RUNTIME = 'nodejs14.x'
exports.handler = async event => {
  const name = event?.queryStringParameters?.name ?? 'World'
  return {
    statusCode: 200,
    body: `Hello, ${name}`,
  }
}
Enter fullscreen mode Exit fullscreen mode

Result:

// example.com/endpoint?name=John
'Hello, John'
// example.com/endpoint
'Hello, World'
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

pic
Editor guide