What is ?. symbol used for in java-script? [duplicate] - node.js

This question already has answers here:
Null-safe property access (and conditional assignment) in ES6/2015
(11 answers)
Question mark before dot in javascript / react [duplicate]
(1 answer)
Closed 1 year ago.
I'm learning reactjs with some tutorial and doesn't understand how ?. is work.
Is anyone help me to understand this with simple word.
if (message?.attachments?.length > 0 ) {
return ...
}
If you want more code please ask.

repeated question.
answer here
The optional chaining operator ?. permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid. The ?. operator functions similarly to the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist.
This results in shorter and simpler expressions when accessing chained properties when the possibility exists that a reference may be missing. It can also be helpful while exploring the content of an object when there's no known guarantee as to which properties are required.

Related

unable to access meteor this when using ecmascript [duplicate]

This question already has an answer here:
ES6 Arrow function is changing the scope of this in Meteor.publish [duplicate]
(1 answer)
Closed 7 years ago.
When using meteor with ecmascript's arrow notation, using 'this' to access the value described in the documentation always fails. For example:
Template.temp.onCreated(()=> {
this.var = new ReactiveVar("")
})
and then access it via:
Template.instance().var
always fail. This is consistant in almost any use of 'this' in meteor, client or server side.
When inspecting from the client, I can see that "this" is compiled into "_this" which always cause the code to fail.
the code is compiled into:
_this = this
Template.temp.onCreated(function() {
_this.var = new ReactiveVar("")
})
Any advice is appreciated.
This is because arrow functions are bound to the scope at the time they are created. In your case, at the time of creation the scope is global and your function's scope is, therefore, the global scope.
In conclusion, this behavior is the correct one by design.
You should not use the arrow functions when it is not appropriate. It is not just a "short-hand" to save typing a few characters.

Erlang: Search through list for matching string

Hopefully this is what my problem is(having problem reading the error log that erlang prints). I'm trying to search through a list to find a matching string(PID from a client converted to a string) but it just results in a crash.
...
#7 ClientPID = pid_to_list(From),
#8 list:member(ClientPID, #server.users), % 'users' being a list in the record 'server'
...
The 'users' list in the 'server' record is just defined to users = [], if it helps.
Crash report:
** Reason for termination ==
** "{undef,[{list,member,[\"<0.568.0>\",2],[]}, {server,loop,2,[{file,\"server.erl\"},{line,8}]},
{genserver,loop,2,[{file,\"c:/Erlang/ServCli/genserver.erl\"}{line,13}]}]}"
Module is called lists not list. It's common mistake :)
And your argument are little off. You are using record, and proper usage look like this: VariableThatStoresRecord#record_name.filed_name. In your case it could be something like State#state.users (or just shorten State parameter in loop function to S if you don't like this double state).
What you are doing is actually a semantic suger, which returns on which element in record/tuple given field is stored (since all records are in fact tuples). In you case #state.users returns 2 (first element is record name, and I guess that users is first defined field in your record).
Regarding the error message. First thing is thing you get undef error. So it means that you are meking call to undefined function (which is quite common, since Erlang is dynamic language). Than you get list of tuples, which represents call-trace, from newest to oldest like this
[ { function call definition }
{ function call definition }
{ function call definition } ]
The first one is most interesting, since it is the call to undefined function. You can see that it is call to module list and function member. Other than that you can expect either actual arguments, or just arrity (those variables could be garbage collected already in erlang), and some information about function definition (like file and line number).
And from {list,member,[\"<0.568.0>\",2],[]} you can see that you are trying to call list:member function, with arguments "<0.568.0>" and 2. If you change your call to lists:member(ClientPID, Server#server.users) it should work.
Since most of the error messages are usually nested tuples/lists, which are hard to read if they are presented in one line. So what I do is copy them to my editor, split the one-liner into multiple lines, and than auto indent (emacs does this really great, and some editor can follow this lisp-like indention for Erlang).

what does getType do in antlr4?

This question is with reference to the Cymbol code from the book (~ page 143) :
int t = ctx.type().start.getType(); // in DefPhase.enterFunctionDecl()
Symbol.Type type = CheckSymbols.getType(t);
What does each component return: "ctx.type()", "start", "getType()" ? The book does not contain any explanation about these names.
I can "kind of" understand that "ctx.type()" refers to the "type" rule, and "getType()" returns the number associated with it. But what exactly does the "start" do?
Also, to generalize this question: what is the mechanism to get the value/structure returned by a rule - especially in the context of usage in a listener?
I can see that for an ID, it is:
String name = ctx.ID().getText();
And as in above, for an enumeration of keywords it is via "start.getType()". Any other special kinds of access that I should be aware of?
Lets disassemble problem step by step. Obviously, ctx is instance of CymbolParser.FunctionDeclContext. On page 98-99 you can see how grammar and ParseTree are implemented (at least the feeling - for real implementation please see th .g4 file).
Take a look at the figure of AST on page 99 - you can see that node FunctionDeclContext has a several children, one labeled type. Intuitively you see that it somehow correspond with function return-type. This is the node you retrieve when calling CymbolParser.FunctionDeclContext::type. The return type is probably sth like TypeContext.
Note that methods without 'get' at the beginning are usually children-getters - e.g. you can access the block by calling CymbolParser.FunctionDeclContext::block.
So you got the type context of the method you got passed. You can call either begin or end on any context to get first of last Token defining the context. Simply start gets you "the first word". In this case, the first Token is of course the function return-type itsef, e.g. int.
And the last call - Token::getType returns integral representation of Token.
You can find more information at API reference webpages - Context, Token. But the best way of understanding the behavior is reading through the generated ANTLR classes such as <GrammarName>Parser etc. And to be complete, I attach a link to the book.

I declared String s1=null and s2="Hello" by using s1.equals(s2) it shows NullPointer Exception why? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
How the equals function knows s1 having the null reference to the String.
You are getting a null pointer because you are saying null.something....this is a null pointer exception..You cant call a method on a null
Its a runtime exception. As you know equals is a instance method so when it is actually called at runtime, it should has object of the String. So when there is null instead of real object it throws null pointer exception.
The equals() method is not able to execute.
When you call s1.equals(s2), it will try to execute equals() method of s1 object, but since s1 is null, therefore you get a nullPointerException.
For more details check Documentation
The equals() method provided by Object tests whether the object references are equal—that is, if the objects compared are the exact same object.

Keep `this` on prototype's object [duplicate]

This question already has answers here:
Organize prototype javascript while perserving object reference and inheritance
(3 answers)
Closed 8 years ago.
I am trying to build a small javascript library for study purposes. I have an object inside a prototype that has some functions inside. I would like to access this (the one that has valueOf and stuff) from inside the functions, but this now brings me only the object parent to the functions.
My code (coffee):
HTMLElement.prototype.on =
click: (action) -> #valueOf().addEventListener('click', action, false)
# I'd like this to work,
# but `this` here refers to the `on` object
Is this possible? I know I'm kinda reinventing the wheel, but as I said, it's for study purposes, so that's the idea.
I am not 100% sure about the "this" the OP is referring to but I'll try to answer:
Let's first compile your coffee-script code to javascript:
HTMLElement.prototype.on =
click: (action) =>> #valueOf().addEventListener('click', action, false)
HTMLElement.prototype.on = {
click: function(action) {
return this.valueOf().addEventListener('click', action, false);
}
};
Ok, all right. In javascript the value of this in a function can be determined by many factors, one of which is a MemberExpression. When you call a function with a.b(), where a is an object, this inside the function b will be bound to a. In your case you are probably calling the function like that:
element.on.click(...);
The issue is that element.on is itself an object. The expression will evaluate to
(element.on).click(...);
and the value of this in the click function will be the object prototype.on, not element.
Basically, don't do it that way. It will be a pain to bind this to the HTMLElement instance. Put the function directly on the prototype. The only solution I can think of (terrible, shame on me) is:
element.on.click.bind(element)(...)
If I understand your problem correctly, the solution is the => Operator.
http://coffeescript.org/#fat-arrow

Resources