91 points · by pitayanblog · 4y ago · 91 comments
function createNewArray(item) {
return
[item]
}
The author claims this produces “Uncaught SyntaxError: Invalid or unexpected token”. This is incorrect; you end up with the body being `return; [item];` thanks to Automatic Semicolon Insertion, which is unlikely to be what was intended, and will produce a warning in some environments (e.g. “unreachable code after return statement” in Firefox), but is not a syntax error.I presume the author wrote slightly different code. Most especially, I don’t believe anything is ever indentation-sensitive.
Javascript shouldn't be indentation dependent, but I have no trouble believing that it's doing something weird to indents because of this "feature".
Generally, the rule seems to be "insert a semicolon wherever the syntax messes up but can be fixed by adding semicolons". Then there are some special cases (++/--/continue/break/return/throw/arrow functions/yield) with more specific rules about where semicolons are placed and when; those are probably why the example produces "unexpected" results.
I think the added complexity of these special rules and cases are an unnecessary burden, and honestly the language should never have allowed leaving out semicolons when it was clearly designed to have semicolons.
return (
[item]
)
or for this case: return [
item
]
You could do other things to prevent it from sticking out of the side of the monitor but if it is to say return true if this and that and that and that and that it would (to me) look better on separate lines. let c = a + b
(() => { ... })()
This is evaluated as: let c = a + (b(() => {...}))()
which usually results in "TypeError: b is not a function." Obviously this can be solved with a semicolon after the "let c..." line, but another common approach is to just prefix all IIFEs with semicolons, since empty statements are no-ops in JS: let c = a + b
;(() => {...})()
I personally prefer to forego semi-colons, but I have a hard time getting worked up over it either way.Whereas JavaScript technically requires it but many browsers decided to support parsing missing semicolons for the sake of making bad websites render (much like how most browsers will support a variety of incorrectly formatted HTML documents as well). The problem here is that JavaScript's syntax wasn't designed to have semicolons omitted. Which leads to all sorts of edge case problems and no clear answer on how they should be handled.
function foo() {
let a = b = 0
a++
return a
}
console.log(typeof a)
console.log(typeof b)
As expected, `a` is defined with `let`, so it is a local variable. But `b` is defined without let, so it is actually globally. I personally do not like declaring multiple variables in a single statement like this, so I've probably not coded any bugs with this behaviour, but I have most certainly worked on code which I now understand to have latent bugs due to this behaviour.Actually, at this point, with the prolifiration of strict mode and linters, I'd say that these old gotchas mostly belong to quizzes and spec discussions, since personally I have not seen new code written this way even in vanilla JS for years by now.
[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
Maybe it wasn't 'new' code but it was new enough to use let.
on edit: actually considering the project I would think it was written somewhere within the last 2 years.
let a = 0, b = 0You need to call `foo()` before the first `console.log` to get that behavior.
function foo() {
let a = b = 0
a++
return a
}
foo() // <------ INSERT THIS
console.log(typeof a)
console.log(typeof b)As a side-comment, often I see JavaScript learning channels and Twitters focusing a lot on JS gotchas and stuff like the prototype chain. I’ve worked on production JavaScript apps for years and have never needed to touch the JS prototype system. Time could probably be spent better elsewhere, as fun as the gotchas are. NB: I’m not necessarily saying the author of this blog is guilty of this - for all I know this is the only post like that they have written; but I have seen many channels/Twitters where this kind of stuff is post of what they discuss - possibly because of interview questions in their areas).
I think that is similar to “why do we bother teaching χ in school, I've never used it as an adult”, where the answer is a mix of:
1. For the people it is useful to, it is very useful. Those that may later be building frameworks rather than using them for instance, to save them reinventing wheels, or those coming from other languages who might otherwise have more trouble reasoning with JS as they try to use it exactly like they've used something else.
2. For the people it isn't directly useful to, at least a vague understanding of what goes on can be useful if only because you need some knowledge to know if you need to care.
3. For everyone else, perhaps myself included though I'm probably more in group 2, you taking a hit to your learning time is a sacrifice well made to make sure the people who do find it useful get it!
People always say that it's actually simpler than "traditional", Java-like classes... yet when JS gained that, with ES6, I could immediately "grok" what `class` and `new` was doing. I could never do that with __proto__ and prototype.
var a = { foo: 5 };
a.__proto__ = { foo: 10, bar: 2 };
console.log(a.foo, a.bar); // 5, 2
You can also use Object.create() to initialize an object with a given prototype. So the above is equivalent to: var a = Object.create({ foo: 10, bar: 2 });
a.foo = 5;
console.log(a.foo, a.bar); // 5, 2
The real confusing part is the property called "prototype". This doesn't exist on random objects, it's only available on functions, and it sets the __proto__ of the object created with that function when used as a constructor (that is, when using the "new" operator). function Foo() {}
Foo.prototype = { foo: 10, bar: 2 };
var a = new Foo();
a.foo = 5;
console.log(a.foo, a.bar); // 5, 2
The "new" operator also sets a.constructor = Foo, and calls the constructor method. You can think of the new operator as syntax sugar performing the below: function Foo() {}
Foo.prototype = { foo: 10, bar: 2 };
// The four lines below are equivalent to `var a = new Foo();`
var a = {};
a.constructor = Foo;
a.__proto__ = Foo.prototype;
Foo.call(a);
a.foo = 5;
console.log(a.foo, a.bar); // 5, 2
The reason for all of these different mechanisms is history. The original mechanism was the constructor `prototype`, then in ES5, Object.create() was added. Then, much later on, `__proto__` was standardized (it was a non-standard extension before). function Foo() {}
Foo.prototype = { foo: 10, bar: 2 };
var a = new Foo();
console.log(a.foo, a.bar); // 5, 2
Isn’t your logged a.foo wrong? a.foo === 10, right?The other prototype based language I've programmed in was the Io language and there it made sense, just by having a built-in clone utility. See Objects section https://iolanguage.org/tutorial.html
With the lack of a clone operation, in order to define new objects types you had to go through hacky stuff, like explicitly setting up .prototype properties.
Exactly. Not just half-baked but half-assed too, the entire concept of constructors doesn't belong for starters.
Javascript's prototypal system was never a philosophy, it was just a way to quickly get an object system up and running (which is why delegation has to be hand-rolled, delegating ctors stinks, and most of the native objects can't be derived from at all), essentially a terrible implementation detail people had to deal with out of necessity.
> With the lack of a clone operation, in order to define new objects types you had to go through hacky stuff, like explicitly setting up .prototype properties.
As you link to io, JS IO's clone way back (in ES5 I think?) in Object.create. I don't think it's very good, though I think IO's clone is even worse as it really do what you'd intuit in reading the word (I think JS's naming is less confusing, though hardly great).
In Self, the "clone" operation would simply do a shallow copy (unless you'd overridden it). So you'd have an object, "clone" it, and you'd get a copy of that with the same slots set to the same value.
A prototype then would simply be an existing "reference" instance you'd copy, and you'd get the same parent slots, meaning you'd get the same parents (what Javascript and Io mis-call prototypes).
The new ES6 "class" syntax is really syntax sugar on the existing prototype system. "class" does not add new functionality to the language. Anything that can be written with "class" can be written with the older way. So really, you need to understand the prototype system to really understand how "class" works.
But I think you don't actually need to deeply understand how the prototype system works to use the new ES6 class syntax. Your "Java intuition" + the knowing that there could be gotchas in corner cases should suffice if you don't do anything weird.
Prototypal inheritence is seen as simpler because conceptually it involves less "things". Both JS and Java have runtimes with values containing basic data (strings, ints, bools etc) as well as objects. Where they differ is that JS has first class functions (meaning functions are also values just like basic data and objects), which is what enables prototypal inheritance. And Java has a compile time where it generates static objects (classes) that aren't values and can't be changed, that's what enables classical inheritance.
It's generally considered that conceptually the functional approach is simpler, because in those languages functions adhere to the same rules as objects and other data, you can add new ones, remove them, move them around, copy them into a different variable etc. So all the "things" that apply to working with functions are just the same "things" that work on everything else, there's nothing really extra there, you don't need all these special rules and concepts like "reflection" where you're "reaching into the internals" of the running program or whatever it is in Java, because you don't have any "internals" to reach into. Nothing is happening at some compile time before the code actually runs, and nothing is static or out of bounds.
None of that really has much to do with prototypal inheritance itself. But it's relevant in that you can't just pick which kind of inheritance to use, you need the language constructs that enable them, so they're part of the complexity. The two forms of inheritance are basically the same thing, you just have an object with your functions on it that has a special label saying "if you don't find what you're looking for, look at this object instead". The difference is that in Javascript that label is just a standard property on an object, that can hold another object. Whereas in Java, that label is an "extends" or "inherits" clause on class that's wired up at compile time, and at runtime it's treated as static and outside of the programmer's control.
Among other things, it does not require any new syntax.
Which was added anyway, because Javascript got constructors (and `new`) to match Java,
Compile 3 times to figure out the answer in 30 seconds and never do the wrong one again, saving your employer about 1,000 man hours across the team, which they’ll instead use to interview additional people seeing if they unnecessarily memorized these answers and smugly pretend that “anybody that doesn’t know this basic knowledge is a joke, source: me, I made that up on the spot for my ego” not knowing what the day to day coding challenges are at all from the very people that were hired to “hit the ground running”
for (var i = 0; i < 3; i++) {
const end = Date.now() + 100;
while (Date.now() < end);
setTimeout(() => {
console.log(i);
}, 100);
}
The answer is no, it will still log three thrice, because of how the event loop works: execution is single-threaded, which means that anything you queue up, whether microtasks like promises or tasks like timeouts, has to wait until you finish what you’re executing. There’s no preemption.Edit: Each time the loop is run, a new anonymous function is created. But in the "let" version, each of those functions is bound to a different version of "i", which means "i" is actually being re-declared as a new and separate variable every time the loop body runs?
Variable declarations with `var` should be avoided, linters commonly reject such code.
I had to look this up, because it's so far outside of even moderately normal practices I'd not encountered it.
https://stackoverflow.com/questions/30469755/why-a-variable-...
Hoisting. Within the function body the declaration of the variable, but not it's initialization, is (re-ordered) hoisted to the top of the function, much like old C. So the clobbered global definition happens at the function frame step rather than exactly where a sane programmer would expect such insane code to perform it.
console.log(parseInt("020" + 020, base=5))
Most languages would throw an error because "020" + 020 = "02016" and we try to parse this in base 5. However, the parseInt function silently stops reading the input if it encounters an invalid character.Language design nitpicks:
- the octal prefix is kind of difficult to see and could lead to accidental conversions, at least the clearer representation 0o20 is also understood.
- the parseInt function understands the prefix 0x, but not 0b, 0o and only when the base is 16 or not setSure, if by “poor man” you refer to the guy who has to debug that “code”. Name a variable with an existing or unwritable `window` property and enjoy.
Don’t do this stuff, use a linter and a decent editor that can do this automatically.
Dog.prototype = new Animal()
This is nonsensical, it is assigning an object instance into a prototype. Dog.prototype = Animal
would make sense.> 3, 3, 3
Is this still true? Wasn't there some special behaviour introduced for for(;;) some years ago that "fixed" this?
The confusion here is that `i` is never snapshotted in time. The variable is captured by the closure, but the only thing captured is the symbol, not the value.
let a = NaN;
let b = null;
[a,b].indexOf(a);
[a,b].indexOf(b);
FYI Array.prototype.Includes was made to "fix" this problem. ["1", "7", "11"].map(parseInt)
returning [1, NaN, 3]