Understanding the order of JavaScript object assignment [duplicate] - javascript

This question already has answers here:
Javascript - Assigning multiple variables to object properties using curly braces in variable declaration
(2 answers)
Closed 8 years ago.
In looking at JavaScript from various Firefox extensions, I've seen code like the following for creating aliases (example):
let Cc = Components.classes;
let Ci = Components.interfaces;
let Cu = Components.utils;
This makes sense to me. However, I've seen a strange looking variant of this code that looks like this (from this example):
let { classes: Cc, interfaces: Ci, utils: Cu } = Components;
I don't fully understand this assignment statement. I believe that the end result is essentially the same as the former code block, but why? An anonymous object is being assigned the value Components, correct? I've never seen an assignment type like this before, so it makes little sense to me.
I looked at the Values, variables, and literals page at MDN, and the documentation for let, but neither page had any examples of this type of construction.

The second form is a new feature of ECMAScript6, called destructuring assignment. You won't see it in the open web due to lack of support, but you can find it in some code running on node.js or in firefox/addon internals.
Or things that are run through es6 to es5 transpilers.
See MDN docs for further details.

Related

Jascript use custom default return type for bracket-notation [duplicate]

This question already has answers here:
How to declare Hash.new(0) with 0 default value for counting objects in JavaScript?
(3 answers)
Closed 2 years ago.
I want to achieve the following behavior:
For a certain JS object, if I use bracket-notation to access a key that is not defined, I want it to return 0 instead of undefined, similar to how Ruby Hash.new(0) behaves.
Is there a way I can go about implementing such behavior or anything in JavaScript that already exists which I could use instead?
currently having trouble sifting through noise related to this topic (mainly do to a lack of knowing google terms on this topic), any google terms I could use or docs I could read to better understand this would also be a huge help.
You could use the logical OR operator "||".
This will act as a fallback if the property is not defined.
const obj = {hello:'world'};
console.log(obj['hello'] || 0);
console.log(obj['somethingelse'] || 0);
I found MDN (Mozilla Developer Network) to be a great resource for JS related questions.
More on the logical OR operator: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/Logical_OR
More on property accessors (bracket notation): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

Colon after colon syntax while calling a function in Javascript [duplicate]

This question already has an answer here:
Colon after function declaration in javascript [duplicate]
(1 answer)
Closed 4 years ago.
I came across a syntax somewhere on the web recently and couldn't grasp its meaning.
What I understand is that when we write props: Object inside the brackets, it means we're assigning a default value to props as Object. But what does the 2nd colon signify? It looks like a key-value pair but is confusing me still.
Tried searching on the web but wasn't able to search due to lack of terminology. Any ideas what this means?
someFn(props: Object): Object {
return someOtherFn(props);
}
These are type annotations. They are not standard javascript. They are added when using tools that layer static typing onto javascript. The two most popular flavors are Typescript and Flow.
When you write code that uses this syntax you will transpile your source code into code that is syntactically valid for execution by running one of the above mentioned tools on your code. When you do, it will tell you if your usage of the types is correct, raise warnings that are helpful in development, and then strip all this out so it can actually be run.

Where can i find the code source of javascript functions? [duplicate]

This question already has answers here:
Where can I find javascript native functions source code? [duplicate]
(3 answers)
Closed 1 year ago.
For example, i want to know how the querySelector method was built. I checked on MDN but there's only examples that show how to use it.
I also tried to check in the console.log but nothing readable.
There is a non-standard method to do this. Please be aware that it is not fully cross-browser compatible and shouldn't be used in a production environment.
function hello(){
return "Hi!";
}
console.log(hello.toSource());
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toSource for more.
Edit:
To see the source code of a built-in function, you will need to look at the engine source. This varies browser to browser. For example, Chrome uses the V8 engine. See https://github.com/v8/v8

What's new() in node.js

I'm studying the WebRTC tutorial from Google's codelab.
In its index.js section for Node.js. I has the following line.
var fileServer = new(nodeStatic.Server)();
I understand new is an operator to create instances. But it above is using new(nodeStatic.Server)() which confuses me.
Can someone please explain it for me? Thanks.
nodeStatic.Server is apparently a constructor. So, your code works like this;
let serverConstructor = nodeStatic.Server;
let fileServer = new serverConstructor();
The parens are used in your original code to make the competing precedence between new, () and the . operator a little more obvious. You'd have to study the precedence rules in the Javascript spec to see if the parens around nodeStatic.Server are actually needed or not (it appears they are not, but it takes some detailed knowledge of the spec or running your own tests to know that).

Is TypeScript really a superset of JavaScript?

I just started using TypeScript and sometimes get compiler errors "use of undeclared variable". For example the following works in plain JavaScript :
var foo = {};
foo.bar = 42;
If I try to do the same in TypeScript it won't work and give me the mentioned error above. I have to write it like that:
var foo :any = {};
foo.bar = 42;
In plain JavaScript the type definition with any is neither required nor valid, but in TypeScript this seems to be mandatory. I understand the error and the reason for it, but I always heard in Videos and read in the documentation:
typescriptlang.org:
"TypeScript is a typed superset of JavaScript [...]"
Introduction Video #minute 3:20:
"All JavaScript code is TypeScript code, simply copy and paste"
Is that a thing that changed during the development of TypeScript or do I have to pass a specific compiler setting to make this work?
The reason for TypeScript's existence is to have a compiler and language which can enforce types better than vanilla Javascript does. Any regular Javascript is valid TypeScript, syntactically. That does not mean that the compiler must be entirely happy with it. Vanilla Javascript often contains code which is problematic in terms of type security. That doesn't make it invalid TypeScript code, but it's exactly the reason why TypeScript exists and it's exactly the compiler's job to point out those problems to you.
The languages as such are still sub/supersets of one another.
Theorem: TypeScript is neither a subset nor a superset of JavaScript.
Proof:
When we say language A is a subset of language B, we mean all valid A-programs are also valid B-programs.
Here is a valid TypeScript program that is not a valid JavaScript program:
let x: number = 3;
You identified a valid JavaScript program that is not a valid TypeScript program:
var foo = {};
foo.bar = 42;
Complicating factor 1: TypeScript is almost a superset. TypeScript is intended to be a near superset of JavaScript. Most valid JS is also valid TS. What JS is not can usually be easily tweaked to compile without errors in TS. In other words, most valid JS is also valid TS.
Complicating factor 2: non-fatal errors The TypeScript compiler generates the JavaScript code you intend sometimes even if there are errors. The your example that I referenced earlier emits this error
error TS2339: Property 'bar' does not exist on type '{}'.
but also this JS code
var foo = {};
foo.bar = 42;
The TS documentation notes
You can use TypeScript even if there are errors in your code. But in this case, TypeScript is warning that your code will likely not run as expected.
I think we can call this a failed compilation (and thus invalid TypeScript) for the following reasons:
The compiler seems to use the term warning in the conventional sense, so we should interpret error in the conventional sense too: an error indicates the compilation failed.
The documentation indicates that the resulting JavaScript is not necessarily correct as to what was intended. An incorrect output seems just as bad as (if not worse than) no output. They should both be considered failed.
The TypeScript compiler exits with a non-zero status code, which conventionally indicates that the process failed in some way.
If we call any TypeScript program that outputs JavaScript "valid", then we would have to call the following TypeScript program valid, because it a dot compiles to the empty string after issuing errors:
.
Complicating factor 3: TS accepts JS files: The TypeScript compiler can passthrough files ending in .js (see compiler documentation for --allowJs). In this sense TypeScript is a superset of JS. All .js files can be compiled with TypeScript. This is probably not what people who visit this question are meaning to ask.
I think complicating factor 1 is the thing that Anders Hejlsberg is getting at. It might also justify the misleading marketing on TypeScript's homepage. The other answers have fallen prey to complicating factor 2. However the general advice given in the other answers is correct: TypeScript is a layer on top of JavaScript designed to tell you when you do something bad. They are different tools for different purposes.
No. In other answers I believe the technical reason has been well explained, but I notice an example that could immediately serve as a contradiction to the claim in the question (different semantics):
// In TypeScript
function f<A>(a: A) { return a; };
console.log(f<Function>(f)); // <-- This line. It will print the function f since it is an identify function that in this case takes self and returns self.
Comparing to the below JavaScript example
// In JavaScript
function f(a) { return a; };
console.log(f<Function>(f)); // <-- This line. This is VALID JavaScript
At first glance you might think there should be a syntax error for the JavaScript example. HOWEVER, once you examine it closely, you'll notice that actually the line is executed as
console.log((f < Function) > f); // Evaluate to false
which is completely valid in JavaScript. This essentially means the same line of code resulted in 2 completely different interpretation in JavaScript and TypeScript, therefore a counterexample to the question.
The definition
"All JavaScript code is TypeScript code, simply copy and paste"
is true. Because any JavaScript code can passed to the TypeScript compiler.
So it's sort of a Layer on top of JavaScript. So, of course the underlaying Layer (JavaScript) can be passed through the layers to the top (TypeScript), but not the other way around.
Why not?
Think of it as a bike (JavaScript) and a motorcycle (TypeScript). The basics are the same (two wheels, a frame), but the motorcycle as an engine and some enhanced features.
So, you can use your motorcycle (TypeScript) as a bike (JavaScript), but you cannot use a bike as a motorcycle.
EDIT:
If your compiler throws a warning, why does it make the
statement wrong? It just says: Hey, you are using TypeScript, and it's
more strict than what you gave me.
See this example, it compiles perfectly to JavaScript, but throws a warning.

Categories

Resources