9 mistakes for Python programmers when learning JavaScript #70
Labels
blog: programming
@post
This is a blog post
tag: javascript
|178272204-7e20ff98-56d1-457d-842f-70a4ecd17e0f.png
View Post on Blog
The
new
OperatorYou can simply create an instance of a class by
ClassName(...)
in Python. But in JavaScript you need thenew
operator. It can be easily forgotten!See also https://stackoverflow.com/q/1646698/8810271, https://stackoverflow.com/q/383402/8810271
But why sometimes it still works when I forget
new
? For example:As the second link shows, there is a trick:
However, you must use
new
if you are using class:Element in Array or Key in Object / dict
In Python, we have:
However, in JavaScript:
That's because in JavaScript, even Array act like a Object:
So, JS just always detects keys. To determine whether an element in Array, you should do:
Weird map / Are they Different?
map
will pass 3 parameters: value, index, and the Array itself, as shown in[1, 2, 3].map(console.log)
And, passing too many arguments will not cause error:
And as for
parseInt
, there is a second parameter (see below). That's whyparseInt
ands => parseInt(s)
are different.parseInt
v.s.int
Well, that makes sense. And I'm going to specify a radix when using
parseInt
.And note that Python is more friendly:
Dead Variable
Based on https://stackoverflow.com/a/54980674/8810271
Once you have a typo when using
let
in console (such as forgettingnew
), the variable name will never come back. That's because variable initialization did not complete successfully, and you can't re-declare a variable that's already been declared.Worse still, you cannot delete the variable declared using
let
,const
orvar
. Only things like "global variable" can be deleted. See also https://stackoverflow.com/q/1596782/8810271You have to reinvent a good variable name, or reopen the console.
Sure Sorted?
No, JS
sort
is just String sorting:And if you want number sorting, write:
How do you split?
Even though expression is the same, the answer does not.
Hmm, I'd better split, slice and join..
Mutable Default Parameter?
Javascript seems not affected.
Beware of Method / Function Names
Some methods / functions achieve similar, if not the same, effect, but with different names. They are so similar that I often get confused.
The text was updated successfully, but these errors were encountered: