Optional chaining

4 0 0
                                        

Note: This was a recent a addition to javascript but java has been doing this. 

Side note: I think all programming are just the same. What you need to know is the syntax and you good to go. But of course, you have to be good to at least one program who implements most of the logic and concepts like java, c++ or c# preferably java in my opinion. C++ is hard to grasp for beginners.

Optional chaining - You add a question mark operator to those dot operators ?. who chains the functions. The question mark operator will ask if null or undefined, if it is, it will return undefined.

syntax:

objectName?.key

objectName?.["key 1"]

====================

let person1 = {

    name: "Bell Cranel",

    age: 20,

    sayHelloWorld(){

        return "Hello World";

    }

};

let person2 = {}

function displayPersonInfo(){

     document.writeln('x: ${x?.["name"]}');

     document.writeln('y: ${y?.name}');

     document.writeln('${x.sayHelloWorld?.()}');

}

====================

HTML

displayPersonInfo()

Result:

x: Bell Cranel y: undefined Hello World


Note: You can do chaining to check if the function exist just like the example in the above code. Optional chaining is used only in get() and not in set(). Java has an automatic get() and set() for every properties or variable you create inside a class. So, what I mean here, you cannot use chaining on setting a value on variable or a key in an object. 



Javascript ProgrammingWhere stories live. Discover now