
The nullish coalescing operator (??
) is a logical operator that returns its right-hand side operand when its left-hand side operand is null
or undefined
, and otherwise returns its left-hand side operand.

?. → Optional Chaining operator
Optional chaining will eliminate the need for manually checking if a property is available in an object. With option chaining the checking will be done internally.
Example without Optional chaining.
const planet1 = {
name: 'Earth',
size: '6,371 km'
}
const planet2 = {
name: 'Mars',
// size: '3,389.5 km'
}
function printPlanetInfo(planet) {
console.log(`Name: ${planet.name}`)
console.log(`Size: ${planet.size.toUpperCase()}`)
}
printPlanetInfo(planet1)
printPlanetInfo(planet2)
When we pass an planet object which doesn’t have the size property:
To solve the above problem what we do is, we will add check if size property available in the planet object
const planet1 = {
name: 'Earth',
size: '6,371 km'
}
const planet2 = {
name: 'Mars',
// size: '3,389.5 km'
}
function printPlanetInfo(planet) {
console.log(`Name: ${planet.name}`)
planet.size = ( planet && planet.size &&
planet.size.toUpperCase())
|| "undefined"
console.log(`Size: ${planet.size}`)
}
printPlanetInfo(planet1)
printPlanetInfo(planet2)
The optional chaining will check if an object left to the operator is valid (not null and undefined). If the property is valid then it executes the right side part of the operator otherwise return undefined.
function printPlanetInfo(planet) {
console.log(`Name: ${planet.name}`)
planet.size = ( planet?.size?.toUpperCase() ) || "undefined"
console.log(`Size: ${planet.size}`)
}
The native JavaScript equivalent code for above optional chaining operator is
(property == undefined || property == null) ? undefined : property
We can use variables as property name in optional chaining
const planet = {
name: 'Earth',
size: '6,371 km'
}
planet?.size
// We can also use with expressions
planet?.["s"+"ize"]
You can use optional chaining to call a method which may not exist.
const planet = {
name: 'Earth',
size: '6,371 km'
getSize() {
return this.size;
}
}
planet?.getSize?.()
Reference: MDN.
Usually when we start to study data structures, we study first trees and then graph. Can I give you two tips ? First read about graph theory. Try to answer for yourself the two following questions:
Right. Are you a bit more confused now ? 🙂 Let’s blow the candles and see the knowledge emerging like magic. Let’s list some conditions to say: “Hey it is a tree !”
Make it run without errors but you cannot change the location of the `let` statement, that has to stay at the end.
This was a trick question.
Callbacks are not async by default, this was a sync call so the message var was not defined by the time the callback was called.To make this work we need to wrap our call to `cb` in either a `setImmediate` or a `process.nextTick`.
Meetup brings people together in thousands of cities to do more of what they want to do in life. It is organized around one simple idea: when we get together and do the things that matter to us, we’re at our best. And that’s what Meetup does. It brings people together to do, explore, teach and learn the things that help them come alive.
For example, people run marathons, thanks to running Meetups. They write, thanks to writing Meetups. They change their careers, thanks to career Meetups. Because at Meetups, people welcome each other. They talk, help, mentor, and support each other – all in pursuit of moving their lives forward.
My first meetup will be “Computer Science Noobs” on 27th April 2017. After, I will write my experience! Now I need to read the 5th chapter of ‘Imposter’s Handbook’ by Rob Conery, in order to make the most of the discussion.
See you later! Bye!
I arrived in London on 18th March 2017. Sorry if you have been found some errors in this text but my goal is to share some experiences and I am going to use the posts to practice my English 🙂
During the first month I have booked the appointment for national insurance number(NIN) from my wife and me. I have applied the learning drive license to my wife, we have done our National Health Service(NHS) and we have created our banks account. All tasks was sucesfully concluded! 😀
Surprise! My wife is already got a job!
I see you soon.. bye!
Encontrei uma plataforma gratuita para estudar novas linguagens de programação! Achei muito divertido! O site é http://www.sololearn.com ! Lá tem inúmeros cursos para diversas linguagens de programação, e você ainda pode instalar o aplicativo no seu celular e nas horas disponíveis realizar algumas lições 🙂 Boa programação!
Olá amigos! Na disciplina de PAA(Pesquisa e Análise de Algoritmos) do Mestrado, a prof. dra. Roseane de Freitas nos passou alguns desafios do URI, e o primeiro deles que estou postando aqui é “Onde está o mármore”. O enunciado do desafio você pode estar conferindo clicando aqui.
Seguindo então o que nos é apresentado pelo desafio, precisamos receber N(número) e Q(Quantidade de Consultas) e após isso imprimir algo como:
4 1
CASE# 1:
2
3
5
1
5
5 found at 4
Mas aí vem a dúvida, como que o resultado diz que o número 5 foi encontrado na posição 4 ? 🙂 E então ? Já sabe a charada ? Vamos reler o nome do desafio, “onde está o mármore ?”, a questão é que após os números serem inseridos para podemos trabalhar com eles, precisamos realizar a ordenação de modo que os números fiquem em ordem crescente, ou seja, a ordem no exemplo acima ficaria:
Números ordenados de forma crescente: 1 2 3 5, portando o 5 ele foi encontrado em nosso vetor ou conjunto e na posição 4. Então aqui foi a primeira dica. Para concluir, precisamos realizar uma busca pelo número informado e se tratando de busca iremos utilizar a “busca binária” pois conseguiremos uma melhor performance em relação a velocidade.
Marbles was hacked ! 🙂 O código fonte você pode conferir no meu github clinkando AQUI!
Até o próximo post!
Pessoal este post será bem curto mas acredito que a informação é bem valiosa. Estou cursando a Disciplina de Inteligência Artificial e o trabalho que o nosso professor nós pediu é a implementação do algoritmo a*(a star). Primeiro que encontrei um livro excelente que se chama “Objetos, Abstração, Estruturas de Dados e Projetos Usando C++, Elliot B. Koffman e Paul A. T. Wolfgang”, e no capítulo 12 Grafos, “Uma das limitações das árvores é que elas não podem representar estruturas de informação em que um item de dados possui mais de um pai. Neste capítulo, apresentaremos uma estrutura de dados conhecida como um grafo, que nos permitirá superar essa limitação”.
Achei interessante em compartilhar esta interpretação.
Meu primeiro vídeo publicado no Youtube :D, curtam aí!