SlideShare une entreprise Scribd logo
1  sur  66
Télécharger pour lire hors ligne
Missing objects:
?. and ?? in JavaScript
Daniel Ehrenberg @littledan
Igalia, in partnership with Bloomberg
TC39 delegate
BrazilJS 2018
Optional chaining ?.
for
Safe property access
const people = [
{name: "Dan Ehrenberg,
passport: {number: 1234567n, expiration: new Date(2020, 1, 1)}},
{name: "John Doe",
dateOfBirth: new Date(2000, 5, 5)}
];
const people = [
{name: "Dan Ehrenberg,
passport: {number: 1234567n, expiration: new Date(2020, 1, 1)}},
{name: "John Doe",
dateOfBirth: new Date(2000, 5, 5)}
];
const passportNumbers = people.map(person => person.passport.number)
const people = [
{name: "Dan Ehrenberg,
passport: {number: 1234567n, expiration: new Date(2020, 1, 1)}},
{name: "John Doe",
dateOfBirth: new Date(2000, 5, 5)}
];
const passportNumbers = people.map(person => person.passport.number)
// ===> TypeError!
// people[1].passport is undefined,
// so it has no number property
const people = [
{name: "Dan Ehrenberg,
passport: {number: 1234567n, expiration: new Date(2020, 1, 1)}},
{name: "John Doe",
dateOfBirth: new Date(2000, 5, 5)}
];
// Fix:
const passportNumbers = people.map(person => {
if (person.passport) return person.passport.number;
else return undefined;
});
const people = [
{name: "Dan Ehrenberg,
passport: {number: 1234567n, expiration: new Date(2020, 1, 1)}},
{name: "John Doe",
dateOfBirth: new Date(2000, 5, 5)}
];
// Shorter fix:
const passportNumbers = people.map(person =>
person.passport && person.passport.number);
const people = [
{name: "Dan Ehrenberg,
passport: {number: 1234567n, expiration: new Date(2020, 1, 1)}},
{name: "John Doe",
dateOfBirth: new Date(2000, 5, 5)}
];
// With optional chaining:
const passportNumbers = people.map(person =>
person.passport?.number);
Avoid repetition
● Repetition with &&
a && a.b && a.b.c && a.b.c.d
● Don't repeat yourself with ?.
a?.b?.c?.d
Falsiness with &&
const a = { b: 0 };
a && a.b && a.b.toString()
// returns 0
if (0) // takes else branch
if (false) // takes else branch
if (undefined) // takes else branch
if (null) // takes else branch
if ("") // takes else branch
// Similar treatment from &&, ||, etc
0 && 1 // ⇒ 0
false && 1 // ⇒ false
undefined && 1 // ⇒ undefined
null && 1 // ⇒ null
"" && 1 // ⇒ ""
true && 1 // ⇒ 1
Avoid falsiness with ?.
let a = { b: 0 };
a?.b?.toString()
// returns "0"
Exerpted from Wikipedia:
https://en.wikipedia.org/wiki/Safe_navigation_operator
Usable in:
● Coffeescript
● Groovy
● C#
● PHP
● Kotlin
● Angular Templates
● Ruby
● Perl 6
● Swift
● And maybe soon,
JavaScript!
Credit: Oskari Noppa in https://github.com/tc39/proposal-optional-chaining/issues/69#issuecomment-409045384
Nullish coalescing ??
for
default options
Source: Matthew Zeunert, https://www.codereadability.com/what-are-javascript-options-objects/
function findTimeout(options) {
if (options.timeout)
return options.timeout;
else
return 100;
}
findTimeout({}); // ⇒ timeout === 100
findTimeout({ timeout: 1 }); // ⇒ timeout === 1;
function findTimeout(options) {
// Popular shorthand
return options.timeout || 100;
}
findTimeout({}); // ⇒ timeout === 100
findTimeout({ timeout: 1 }); // ⇒ timeout === 1;
function findTimeout(options) {
if (options.timeout)
return options.timeout;
else
return 100;
}
findTimeout({}); // ⇒ timeout === 100
findTimeout({ timeout: 1 }); // ⇒ timeout === 1;
function findTimeout(options) {
if (options.timeout)
return options.timeout;
else
return 100;
}
findTimeout({}); // ⇒ timeout === 100
findTimeout({ timeout: 1 }); // ⇒ timeout === 1;
findTimeout({ timeout: 0 }); // ⇒ timeout ===
function findTimeout(options) {
// Popular shorthand
return options.timeout || 100;
}
findTimeout({}); // ⇒ timeout === 100
findTimeout({ timeout: 1 }); // ⇒ timeout === 1;
findTimeout({ timeout: 0 }); // ⇒ timeout ===
if (0) // takes else branch
if (false) // takes else branch
if (undefined) // takes else branch
if (null) // takes else branch
if ("") // takes else branch
// Similar treatment from &&, ||, etc
undefined || 1 // ⇒ 1
null || 1 // ⇒ 1
0 || 1 // ⇒ 1
"" || 1 // ⇒ 1
false || 1 // ⇒ 1
true || 1 // ⇒ true
function findTimeout(options) {
if (options.timeout !== undefined)
return options.timeout;
else
return 100;
}
findTimeout({}); // ⇒ timeout === 100
findTimeout({ timeout: 1 }); // ⇒ timeout === 1
findTimeout({ timeout: 0 }): // ⇒ timeout === 0
function findTimeout(options) {
if (typeof options.foo !== 'undefined')
return options.timeout;
else
return 100;
}
findTimeout({}); // ⇒ timeout === 100
findTimeout({ timeout: 1 }); // ⇒ timeout === 1
findTimeout({ timeout: 0 }): // ⇒ timeout === 0
function findTimeout(options) {
return options.foo ?? 100;
}
findTimeout({}); // ⇒ timeout === 100
findTimeout({ timeout: 1 }); // ⇒ timeout === 1
findTimeout({ timeout: 0 }): // ⇒ timeout === 0
undefined ?? 1 // ⇒ 1
null ?? 1 // ⇒ 1
0 ?? 1 // ⇒ 0
"" ?? 1 // ⇒ ""
false ?? 1 // ⇒ false
?? is the new ||
const response = {
settings: {
duration: 0,
splashScreen: false
}
};
const duration = response.settings?.duration ?? 300; // 0
const splashScreen = response.settings?.splashScreen ?? true; // false
const headerText = response.settings?.headerText ?? "Header"; // "Header"
Works great together
But is all
that JS?
Maybe it will be soon!
We are looking into it
Optional chaining (?.)
& nullish coalescing (??)
are at Stage 1
Champion: Gabriel Isenberg
// ES6 Destructuring Assignment
let x = 1, y = 2;
[y, x] = [x, y];
⇒ x === 2
y === 1
Who is TC39?
● A committee of Ecma, with…
● JS developers
● Implementers
● Frameworks
● Academics
● etc
Meetings
● Every two months
● For three days
● Summarize/review GitHub activity
● Move proposals through stages
TC39 stages
● Stage 1: An idea
● Stage 2: Agreed-on first draft
● Stage 3: Details worked out
● Stage 4: Battle-tested and standard
?. and ?? each reached Stage 1
● The committee expects to discuss it ✔
● Gabriel Isenberg presented them to TC39,
In 2017
Next steps for
?. and ??
Steps needed for Stage 2
● First draft spec text ✔
● Agreement on syntax and semantics …
● Agreement that we want the proposal …
Details:
Method calls and
property access syntax
// Most languages:
obj.method?(args)
obj?[index]
// JS:
obj.method?.(args)
obj?.[index]
// JS:
obj.method?.(args)
obj?.[index]
// Why?
// JS syntax tries to avoid lots of lookahead
// Ambiguity with ternary operator ?:
obj?[index]:bar
obj.method?(args):bar
// Alternate proposal:
obj??.property
obj.method??(args)
obj??[index]
obj ??? default
Details:
Handling of null
// null is treated as missing, like undefined
null ?? x // ⇒ x
(null)?.x // ⇒ undefined
// Handle null as not missing?
Bigger picture:
Do we need a new
feature?
Add these features?
● Pro
○ Makes some code cleaner
○ Avoids bugs from existing idioms
● Con
○ More to learn, mentally parse, etc
Steps needed for Stage 2
● First draft spec text ✔
● Agreement on syntax, broadly …
● Agreement that we want the proposal …
Plan from here
● Experiment with ?. and ?? in Babel, at Stage 1
● Collect feedback over time
● Consider for Stage 2 in the future
● The features are easy to implement; we are just
taking our time to work out the right design.
Steps needed for Stage 3
● Complete spec text …
● Signoff from reviewers, editor …
● Ready to pass off to implementers …
Steps needed for Stage 4
● Two implementations …
● Conformance tests …
● PR with editor signoff …
Getting involved
Feedback on GitHub issues
● Does this work for you?
● Missing pieces?
● Handle a case differently?
?. GitHub feedback
● Syntax: ?. vs ?&. vs ??.
● Null handling
● Which operations support
optional chaining
● And more!
Test262 tests
● Tests shared between JS engines
● “If it’s not tested, it’s not compatible”
● Finds edge cases
?./?? test262 tests
● ...None yet
● Could be useful for Babel development
● Wanna help?
Documentation/Education
● Explain the feature to contributors, learners
● Understand mental models for JS
?./?? documentation
● "Explainer documents" for each proposal
● Wanted: Better introductory materials
● Wanted: Educators' perspective on the proposals
Implementation
● Open-source projects accepting contributions:
○ Babel
○ TypeScript
○ V8
○ Acorn
● Features developed behind a flag/in a plugin
○ JSC
○ ChakraCore
○ SpiderMonkey
○ And many more
?./?? implementations
● Babel transforms in 7.0
○ @babel/plugin-proposal-nullish-coalescing-operator
○ @babel/plugin-proposal-optional-chaining
■ Included in React Native 0.56
○ Thanks, Justin Ridgewell and Lucas Azzola!
● Want to write more implementations? Try this out?
Attending TC39 as a delegate
● Join Ecma to come to TC39 meetings
● Contact me for more info, littledan@igalia.com
● Get involved in TC39:
https://tc39.github.io/
● ?. and ?? are at Stage 1
for handling null/undefined
● Daniel Ehrenberg
● Twitter/GitHub @littledan
● littledan@igalia.com

Contenu connexe

Tendances

Applying Blackboard Systems to First Person Shooters
Applying Blackboard Systems to First Person ShootersApplying Blackboard Systems to First Person Shooters
Applying Blackboard Systems to First Person Shooters
hbbalfred
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
Raga Vahini
 
Introduction to CSharp
Introduction to CSharpIntroduction to CSharp
Introduction to CSharp
Mody Farouk
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
g_hemanth17
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
singhadarsh
 

Tendances (19)

JS Fest 2018. Douglas Crockford. The Better Parts
JS Fest 2018. Douglas Crockford. The Better PartsJS Fest 2018. Douglas Crockford. The Better Parts
JS Fest 2018. Douglas Crockford. The Better Parts
 
PDC Video on C# 4.0 Futures
PDC Video on C# 4.0 FuturesPDC Video on C# 4.0 Futures
PDC Video on C# 4.0 Futures
 
Groovy 2.0 webinar
Groovy 2.0 webinarGroovy 2.0 webinar
Groovy 2.0 webinar
 
Monte Carlo C++
Monte Carlo C++Monte Carlo C++
Monte Carlo C++
 
Review of c_sharp2_features_part_ii
Review of c_sharp2_features_part_iiReview of c_sharp2_features_part_ii
Review of c_sharp2_features_part_ii
 
Metaprogramming With Ruby
Metaprogramming With RubyMetaprogramming With Ruby
Metaprogramming With Ruby
 
Design Patterns in Modern C++
Design Patterns in Modern C++Design Patterns in Modern C++
Design Patterns in Modern C++
 
Groovy and Grails intro
Groovy and Grails introGroovy and Grails intro
Groovy and Grails intro
 
Clean Code 2
Clean Code 2Clean Code 2
Clean Code 2
 
Making Java Groovy (JavaOne 2013)
Making Java Groovy (JavaOne 2013)Making Java Groovy (JavaOne 2013)
Making Java Groovy (JavaOne 2013)
 
An Introduction to Groovy for Java Developers
An Introduction to Groovy for Java DevelopersAn Introduction to Groovy for Java Developers
An Introduction to Groovy for Java Developers
 
Applying Blackboard Systems to First Person Shooters
Applying Blackboard Systems to First Person ShootersApplying Blackboard Systems to First Person Shooters
Applying Blackboard Systems to First Person Shooters
 
Introduction to Programming Bots
Introduction to Programming BotsIntroduction to Programming Bots
Introduction to Programming Bots
 
Let's talks about string operations in C++17
Let's talks about string operations in C++17Let's talks about string operations in C++17
Let's talks about string operations in C++17
 
Better DSL Support for Groovy-Eclipse
Better DSL Support for Groovy-EclipseBetter DSL Support for Groovy-Eclipse
Better DSL Support for Groovy-Eclipse
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to CSharp
Introduction to CSharpIntroduction to CSharp
Introduction to CSharp
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 

Similaire à Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)

LinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: IntroLinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: Intro
Adam Crabtree
 

Similaire à Missing objects: ?. and ?? in JavaScript (BrazilJS 2018) (20)

JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
 
PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing Insanity
 
Type script
Type scriptType script
Type script
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practices
 
Алексей Ященко и Ярослав Волощук "False simplicity of front-end applications"
Алексей Ященко и Ярослав Волощук "False simplicity of front-end applications"Алексей Ященко и Ярослав Волощук "False simplicity of front-end applications"
Алексей Ященко и Ярослав Волощук "False simplicity of front-end applications"
 
Static types on javascript?! Type checking approaches to ensure healthy appli...
Static types on javascript?! Type checking approaches to ensure healthy appli...Static types on javascript?! Type checking approaches to ensure healthy appli...
Static types on javascript?! Type checking approaches to ensure healthy appli...
 
Little Did He Know ...
Little Did He Know ...Little Did He Know ...
Little Did He Know ...
 
Kubernetes debug like a pro
Kubernetes debug like a proKubernetes debug like a pro
Kubernetes debug like a pro
 
advance-dart.pptx
advance-dart.pptxadvance-dart.pptx
advance-dart.pptx
 
Community-driven Language Design at TC39 on the JavaScript Pipeline Operator ...
Community-driven Language Design at TC39 on the JavaScript Pipeline Operator ...Community-driven Language Design at TC39 on the JavaScript Pipeline Operator ...
Community-driven Language Design at TC39 on the JavaScript Pipeline Operator ...
 
Power Leveling your TypeScript
Power Leveling your TypeScriptPower Leveling your TypeScript
Power Leveling your TypeScript
 
Clean code
Clean codeClean code
Clean code
 
Getting started with typescript
Getting started with typescriptGetting started with typescript
Getting started with typescript
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScript
 
How to build SDKs in Go
How to build SDKs in GoHow to build SDKs in Go
How to build SDKs in Go
 
LinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: IntroLinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: Intro
 
Clojure class
Clojure classClojure class
Clojure class
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 

Plus de Igalia

Building End-user Applications on Embedded Devices with WPE
Building End-user Applications on Embedded Devices with WPEBuilding End-user Applications on Embedded Devices with WPE
Building End-user Applications on Embedded Devices with WPE
Igalia
 
Automated Testing for Web-based Systems on Embedded Devices
Automated Testing for Web-based Systems on Embedded DevicesAutomated Testing for Web-based Systems on Embedded Devices
Automated Testing for Web-based Systems on Embedded Devices
Igalia
 
Running JS via WASM faster with JIT
Running JS via WASM      faster with JITRunning JS via WASM      faster with JIT
Running JS via WASM faster with JIT
Igalia
 
Introducción a Mesa. Caso específico dos dispositivos Raspberry Pi por Igalia
Introducción a Mesa. Caso específico dos dispositivos Raspberry Pi por IgaliaIntroducción a Mesa. Caso específico dos dispositivos Raspberry Pi por Igalia
Introducción a Mesa. Caso específico dos dispositivos Raspberry Pi por Igalia
Igalia
 

Plus de Igalia (20)

A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Building End-user Applications on Embedded Devices with WPE
Building End-user Applications on Embedded Devices with WPEBuilding End-user Applications on Embedded Devices with WPE
Building End-user Applications on Embedded Devices with WPE
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Automated Testing for Web-based Systems on Embedded Devices
Automated Testing for Web-based Systems on Embedded DevicesAutomated Testing for Web-based Systems on Embedded Devices
Automated Testing for Web-based Systems on Embedded Devices
 
Embedding WPE WebKit - from Bring-up to Maintenance
Embedding WPE WebKit - from Bring-up to MaintenanceEmbedding WPE WebKit - from Bring-up to Maintenance
Embedding WPE WebKit - from Bring-up to Maintenance
 
Optimizing Scheduler for Linux Gaming.pdf
Optimizing Scheduler for Linux Gaming.pdfOptimizing Scheduler for Linux Gaming.pdf
Optimizing Scheduler for Linux Gaming.pdf
 
Running JS via WASM faster with JIT
Running JS via WASM      faster with JITRunning JS via WASM      faster with JIT
Running JS via WASM faster with JIT
 
To crash or not to crash: if you do, at least recover fast!
To crash or not to crash: if you do, at least recover fast!To crash or not to crash: if you do, at least recover fast!
To crash or not to crash: if you do, at least recover fast!
 
Implementing a Vulkan Video Encoder From Mesa to GStreamer
Implementing a Vulkan Video Encoder From Mesa to GStreamerImplementing a Vulkan Video Encoder From Mesa to GStreamer
Implementing a Vulkan Video Encoder From Mesa to GStreamer
 
8 Years of Open Drivers, including the State of Vulkan in Mesa
8 Years of Open Drivers, including the State of Vulkan in Mesa8 Years of Open Drivers, including the State of Vulkan in Mesa
8 Years of Open Drivers, including the State of Vulkan in Mesa
 
Introducción a Mesa. Caso específico dos dispositivos Raspberry Pi por Igalia
Introducción a Mesa. Caso específico dos dispositivos Raspberry Pi por IgaliaIntroducción a Mesa. Caso específico dos dispositivos Raspberry Pi por Igalia
Introducción a Mesa. Caso específico dos dispositivos Raspberry Pi por Igalia
 
2023 in Chimera Linux
2023 in Chimera                    Linux2023 in Chimera                    Linux
2023 in Chimera Linux
 
Building a Linux distro with LLVM
Building a Linux distro        with LLVMBuilding a Linux distro        with LLVM
Building a Linux distro with LLVM
 
turnip: Update on Open Source Vulkan Driver for Adreno GPUs
turnip: Update on Open Source Vulkan Driver for Adreno GPUsturnip: Update on Open Source Vulkan Driver for Adreno GPUs
turnip: Update on Open Source Vulkan Driver for Adreno GPUs
 
Graphics stack updates for Raspberry Pi devices
Graphics stack updates for Raspberry Pi devicesGraphics stack updates for Raspberry Pi devices
Graphics stack updates for Raspberry Pi devices
 
Delegated Compositing - Utilizing Wayland Protocols for Chromium on ChromeOS
Delegated Compositing - Utilizing Wayland Protocols for Chromium on ChromeOSDelegated Compositing - Utilizing Wayland Protocols for Chromium on ChromeOS
Delegated Compositing - Utilizing Wayland Protocols for Chromium on ChromeOS
 
MessageFormat: The future of i18n on the web
MessageFormat: The future of i18n on the webMessageFormat: The future of i18n on the web
MessageFormat: The future of i18n on the web
 
Replacing the geometry pipeline with mesh shaders
Replacing the geometry pipeline with mesh shadersReplacing the geometry pipeline with mesh shaders
Replacing the geometry pipeline with mesh shaders
 
I'm not an AMD expert, but...
I'm not an AMD expert, but...I'm not an AMD expert, but...
I'm not an AMD expert, but...
 
Status of Vulkan on Raspberry
Status of Vulkan on RaspberryStatus of Vulkan on Raspberry
Status of Vulkan on Raspberry
 

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Dernier (20)

Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 

Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)

  • 1. Missing objects: ?. and ?? in JavaScript Daniel Ehrenberg @littledan Igalia, in partnership with Bloomberg TC39 delegate BrazilJS 2018
  • 3. const people = [ {name: "Dan Ehrenberg, passport: {number: 1234567n, expiration: new Date(2020, 1, 1)}}, {name: "John Doe", dateOfBirth: new Date(2000, 5, 5)} ];
  • 4. const people = [ {name: "Dan Ehrenberg, passport: {number: 1234567n, expiration: new Date(2020, 1, 1)}}, {name: "John Doe", dateOfBirth: new Date(2000, 5, 5)} ]; const passportNumbers = people.map(person => person.passport.number)
  • 5. const people = [ {name: "Dan Ehrenberg, passport: {number: 1234567n, expiration: new Date(2020, 1, 1)}}, {name: "John Doe", dateOfBirth: new Date(2000, 5, 5)} ]; const passportNumbers = people.map(person => person.passport.number) // ===> TypeError! // people[1].passport is undefined, // so it has no number property
  • 6. const people = [ {name: "Dan Ehrenberg, passport: {number: 1234567n, expiration: new Date(2020, 1, 1)}}, {name: "John Doe", dateOfBirth: new Date(2000, 5, 5)} ]; // Fix: const passportNumbers = people.map(person => { if (person.passport) return person.passport.number; else return undefined; });
  • 7. const people = [ {name: "Dan Ehrenberg, passport: {number: 1234567n, expiration: new Date(2020, 1, 1)}}, {name: "John Doe", dateOfBirth: new Date(2000, 5, 5)} ]; // Shorter fix: const passportNumbers = people.map(person => person.passport && person.passport.number);
  • 8. const people = [ {name: "Dan Ehrenberg, passport: {number: 1234567n, expiration: new Date(2020, 1, 1)}}, {name: "John Doe", dateOfBirth: new Date(2000, 5, 5)} ]; // With optional chaining: const passportNumbers = people.map(person => person.passport?.number);
  • 9. Avoid repetition ● Repetition with && a && a.b && a.b.c && a.b.c.d ● Don't repeat yourself with ?. a?.b?.c?.d
  • 10. Falsiness with && const a = { b: 0 }; a && a.b && a.b.toString() // returns 0
  • 11. if (0) // takes else branch if (false) // takes else branch if (undefined) // takes else branch if (null) // takes else branch if ("") // takes else branch // Similar treatment from &&, ||, etc
  • 12. 0 && 1 // ⇒ 0 false && 1 // ⇒ false undefined && 1 // ⇒ undefined null && 1 // ⇒ null "" && 1 // ⇒ "" true && 1 // ⇒ 1
  • 13. Avoid falsiness with ?. let a = { b: 0 }; a?.b?.toString() // returns "0"
  • 14. Exerpted from Wikipedia: https://en.wikipedia.org/wiki/Safe_navigation_operator Usable in: ● Coffeescript ● Groovy ● C# ● PHP ● Kotlin ● Angular Templates ● Ruby ● Perl 6 ● Swift ● And maybe soon, JavaScript!
  • 15. Credit: Oskari Noppa in https://github.com/tc39/proposal-optional-chaining/issues/69#issuecomment-409045384
  • 17. Source: Matthew Zeunert, https://www.codereadability.com/what-are-javascript-options-objects/
  • 18. function findTimeout(options) { if (options.timeout) return options.timeout; else return 100; } findTimeout({}); // ⇒ timeout === 100 findTimeout({ timeout: 1 }); // ⇒ timeout === 1;
  • 19. function findTimeout(options) { // Popular shorthand return options.timeout || 100; } findTimeout({}); // ⇒ timeout === 100 findTimeout({ timeout: 1 }); // ⇒ timeout === 1;
  • 20. function findTimeout(options) { if (options.timeout) return options.timeout; else return 100; } findTimeout({}); // ⇒ timeout === 100 findTimeout({ timeout: 1 }); // ⇒ timeout === 1;
  • 21. function findTimeout(options) { if (options.timeout) return options.timeout; else return 100; } findTimeout({}); // ⇒ timeout === 100 findTimeout({ timeout: 1 }); // ⇒ timeout === 1; findTimeout({ timeout: 0 }); // ⇒ timeout ===
  • 22. function findTimeout(options) { // Popular shorthand return options.timeout || 100; } findTimeout({}); // ⇒ timeout === 100 findTimeout({ timeout: 1 }); // ⇒ timeout === 1; findTimeout({ timeout: 0 }); // ⇒ timeout ===
  • 23. if (0) // takes else branch if (false) // takes else branch if (undefined) // takes else branch if (null) // takes else branch if ("") // takes else branch // Similar treatment from &&, ||, etc
  • 24. undefined || 1 // ⇒ 1 null || 1 // ⇒ 1 0 || 1 // ⇒ 1 "" || 1 // ⇒ 1 false || 1 // ⇒ 1 true || 1 // ⇒ true
  • 25. function findTimeout(options) { if (options.timeout !== undefined) return options.timeout; else return 100; } findTimeout({}); // ⇒ timeout === 100 findTimeout({ timeout: 1 }); // ⇒ timeout === 1 findTimeout({ timeout: 0 }): // ⇒ timeout === 0
  • 26. function findTimeout(options) { if (typeof options.foo !== 'undefined') return options.timeout; else return 100; } findTimeout({}); // ⇒ timeout === 100 findTimeout({ timeout: 1 }); // ⇒ timeout === 1 findTimeout({ timeout: 0 }): // ⇒ timeout === 0
  • 27. function findTimeout(options) { return options.foo ?? 100; } findTimeout({}); // ⇒ timeout === 100 findTimeout({ timeout: 1 }); // ⇒ timeout === 1 findTimeout({ timeout: 0 }): // ⇒ timeout === 0
  • 28. undefined ?? 1 // ⇒ 1 null ?? 1 // ⇒ 1 0 ?? 1 // ⇒ 0 "" ?? 1 // ⇒ "" false ?? 1 // ⇒ false ?? is the new ||
  • 29. const response = { settings: { duration: 0, splashScreen: false } }; const duration = response.settings?.duration ?? 300; // 0 const splashScreen = response.settings?.splashScreen ?? true; // false const headerText = response.settings?.headerText ?? "Header"; // "Header" Works great together
  • 31. Maybe it will be soon! We are looking into it Optional chaining (?.) & nullish coalescing (??) are at Stage 1 Champion: Gabriel Isenberg
  • 32. // ES6 Destructuring Assignment let x = 1, y = 2; [y, x] = [x, y]; ⇒ x === 2 y === 1
  • 33. Who is TC39? ● A committee of Ecma, with… ● JS developers ● Implementers ● Frameworks ● Academics ● etc
  • 34.
  • 35.
  • 36. Meetings ● Every two months ● For three days ● Summarize/review GitHub activity ● Move proposals through stages
  • 37. TC39 stages ● Stage 1: An idea ● Stage 2: Agreed-on first draft ● Stage 3: Details worked out ● Stage 4: Battle-tested and standard
  • 38. ?. and ?? each reached Stage 1 ● The committee expects to discuss it ✔ ● Gabriel Isenberg presented them to TC39, In 2017
  • 40. Steps needed for Stage 2 ● First draft spec text ✔ ● Agreement on syntax and semantics … ● Agreement that we want the proposal …
  • 42. // Most languages: obj.method?(args) obj?[index] // JS: obj.method?.(args) obj?.[index]
  • 43. // JS: obj.method?.(args) obj?.[index] // Why? // JS syntax tries to avoid lots of lookahead // Ambiguity with ternary operator ?: obj?[index]:bar obj.method?(args):bar
  • 46. // null is treated as missing, like undefined null ?? x // ⇒ x (null)?.x // ⇒ undefined // Handle null as not missing?
  • 47. Bigger picture: Do we need a new feature?
  • 48. Add these features? ● Pro ○ Makes some code cleaner ○ Avoids bugs from existing idioms ● Con ○ More to learn, mentally parse, etc
  • 49. Steps needed for Stage 2 ● First draft spec text ✔ ● Agreement on syntax, broadly … ● Agreement that we want the proposal …
  • 50. Plan from here ● Experiment with ?. and ?? in Babel, at Stage 1 ● Collect feedback over time ● Consider for Stage 2 in the future ● The features are easy to implement; we are just taking our time to work out the right design.
  • 51. Steps needed for Stage 3 ● Complete spec text … ● Signoff from reviewers, editor … ● Ready to pass off to implementers …
  • 52. Steps needed for Stage 4 ● Two implementations … ● Conformance tests … ● PR with editor signoff …
  • 54. Feedback on GitHub issues ● Does this work for you? ● Missing pieces? ● Handle a case differently?
  • 55. ?. GitHub feedback ● Syntax: ?. vs ?&. vs ??. ● Null handling ● Which operations support optional chaining ● And more!
  • 56. Test262 tests ● Tests shared between JS engines ● “If it’s not tested, it’s not compatible” ● Finds edge cases
  • 57.
  • 58. ?./?? test262 tests ● ...None yet ● Could be useful for Babel development ● Wanna help?
  • 59. Documentation/Education ● Explain the feature to contributors, learners ● Understand mental models for JS
  • 60.
  • 61. ?./?? documentation ● "Explainer documents" for each proposal ● Wanted: Better introductory materials ● Wanted: Educators' perspective on the proposals
  • 62. Implementation ● Open-source projects accepting contributions: ○ Babel ○ TypeScript ○ V8 ○ Acorn ● Features developed behind a flag/in a plugin ○ JSC ○ ChakraCore ○ SpiderMonkey ○ And many more
  • 63.
  • 64. ?./?? implementations ● Babel transforms in 7.0 ○ @babel/plugin-proposal-nullish-coalescing-operator ○ @babel/plugin-proposal-optional-chaining ■ Included in React Native 0.56 ○ Thanks, Justin Ridgewell and Lucas Azzola! ● Want to write more implementations? Try this out?
  • 65. Attending TC39 as a delegate ● Join Ecma to come to TC39 meetings ● Contact me for more info, littledan@igalia.com
  • 66. ● Get involved in TC39: https://tc39.github.io/ ● ?. and ?? are at Stage 1 for handling null/undefined ● Daniel Ehrenberg ● Twitter/GitHub @littledan ● littledan@igalia.com