Objects
new Object()
and{}
is semantically the same, but the{}
is called object literal syntax.- To do a deep-copy of an object, use
Object.assign(target, src)
or in ES6, use the spread syntax.
Variables
let
is a block-level declarationvar
is a global-level declaration
Functions
- Javascript functions are first-class objects because they can have properties and methods just like any other object. (The term first-class citizen means that the citizen (a type, object, entity, or value) supports all operations generally available to other citizens of the same kind.)
- For example, you can define
this.name
in afunction fcn(){...}
. Consequently, this leads to the function acting like aclass
in other notable languages like C++, Java, or Python. - Since functions are first-class, callbacks are possible, as well as anonymous functions and closures.
- For example, you can define
Classes
- There is no such thing as a class statement like in other languages, because Javascript is a prototype-based language.
- Javascript uses functions to represent classes.
Arrays
- You should avoid
for
...in
loops because if someone added new properties toArray.prototype
, they would also be iterated over by this loop.- Use
for (const x of A)
orforEach()
instead
- Use
this
- A special keyword that refers to the current object, but this is specified by the way you called that function (Remember, you can only call
this
in a function).
new
- A special keyword that is strongly related to
this
. It...- Creates a brand new empty object
- Calls the function specified, i.e.
new Person()
- Sets
this
to that new object
- Functions that are designed to be called by
new
is called a constructor function.
constructor.apply(o, args)
- First argument takes the object that should be treated as
this
. - Second argument is an array of arguments.
- Invokes the function right away.
constructor.call(o, [arg1, arg2, ...])
- Similar to
.apply
- First argument takes the object that should be treated as
this
. - Instead of taking an array like in
.apply
, it takes an expanded argument. - Invokes the function right away.
constructor.bind(o)
- You bind the scope of
o
to the function, but you don't invoke the function. (You can choose when to do so.)
Closures
- A closure is the combination of a function and the scope object in which it was created.
- It is useful for...
- Creating private methods in a function
- Encapsulating data