@rkenmi - Javascript Concepts

Javascript Concepts


Javascript Concepts


Back to Top

Updated on March 29, 2019

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 declaration
  • var 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 a function fcn(){...}. Consequently, this leads to the function acting like a class in other notable languages like C++, Java, or Python.
    • Since functions are first-class, callbacks are possible, as well as anonymous functions and closures.

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 to Array.prototype, they would also be iterated over by this loop.
    • Use for (const x of A) or forEach() instead

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...
    1. Creates a brand new empty object
    2. Calls the function specified, i.e. new Person()
    3. 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

Article Tags:
Javascriptunlisted