JavaScript

Data Type

  1. Primitive Data The typeof operator can return one of these primitive types:
    string
    number
    boolean
    undefined
    

Note: primitive type string is created from literals: var name = "abc" But strings can also be defined as objects with the keyword new: var name = new String("abc")

var x = "Kay";
var y = new String("Kay");
var x2 = "Kay";

// typeof x will return string
// typeof y will return object
// (x == y) is true because x and y have equal values
// (x === y) is false because x and y have different types (string and object)
// (x === x2) is true because primitive
  1. Complex Data The typeof operator can return one of two complex types:
    function
    object
    
    object for both objects, arrays, and null.

Special value

Here’s a complete list of falsy values in Javascript:
false (the boolean false is also considered falsy)
"" (an empty string)
0 (zero)
null
undefined
NaN (a property that represents the "Not-a-Number" value - indicating that a value is not a legal number)

every value that’s not in the list above is a truthy value.

Difference between UNDEFINED and NULL

1. undefined means a variable has been declared but has not yet been assigned a value. null is an assignment value. It can be assigned to a variable as a representation of no value.

2. undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.

3. Unassigned variables are initialized by JavaScript with a default value of undefined. JavaScript never sets a value to null. That must be done programmatically.

Object

  • So what are objects? Objects are collections of name-value pairs. The names are strings, and the values are strings, numbers, booleans, and objects (including arrays and functions).
  • The name-value pairs (in JavaScript objects) are called properties.
  • JavaScript is fundamentally about objects. Arrays are objects. Functions are objects. Objects are objects.
  • When it comes to inheritance, objects inherit from objects, not classes from classes.
  • JavaScript implements prototype-based OO. In prototype-based OO, new objects are created by copying other objects (instead of being instantiated from a class template) and methods live directly in objects instead of in classes.

Class

  • It's important to note that there are no classes in JavaScript. Functions can be used to somewhat simulate classes. Everything is an object. And when it comes to inheritance, objects inherit from objects, not classes from classes as in Java.
  • There are numerous popular JavaScript libraries that have their own style of approximating class-like functionality in JavaScript.
  • A distinctive feature of classes is the function called constructor. This is where you initialize your object's properties. You don't have to define a constructor function. If you choose not to, the engine will insert an empty one for you.
  • Constructors are nothing new. Calling any function with the new keyword causes it to return an object -- this is called making a constructor call, and such functions are generally called constructors.

Prototype

  • Under normal circumstances, all objects in JavaScript -- including Functions -- are linked to another object, called its prototype.
  • Inheritance is done via delegation: if an object doesn't have a method or property, it is looked up on its prototype(s) (i.e. the object it was cloned from), then the prototype's prototypes and so on.

Function

  1. All functions have a property, called prototype, which points to an object associated with that function.
  2. All function prototypes have a property, called constructor, which points back to the function.

Examples:

  • The Array object is a global object that is used in the construction of arrays.
  • All Array instances inherit from Array.prototype. The prototype object of the Array constructor can be modified to affect all Array instances.
  • Array.prototype.constructorspecifies the function that creates an object's prototype.
  • Mutator methods:
    Array.prototype.pop()
    Array.prototype.push()
    Array.prototype.reverse()
    Array.prototype.shift()
    
  • Immutable methods:
    Array.prototype.concat()
    Array.prototype.indexOf()
    Array.prototype.join()
    Array.prototype.slice()
    

4 ways to create an object

(1) Using object literals (Singleton)

create an object, called foo, and give it a property, called status.

const foo = { status : 'foobar' };

Behind the scenes, when we create an object literal, JavaScript sets the object's prototype reference to Object.prototype, and sets its constructor reference to Object:

const foo = { status : 'foobar' };

Object.getPrototypeOf(foo) === Object.prototype; // true
foo.constructor === Object; // true

Another object literal syntax example:

var apple = {
    type: "macintosh",
    color: "red",
    getInfo: function () {
        return this.color + ' ' + this.type + ' apple';
    }
}

(2) Using a function

Constructor Function You define a normal JavaScript function and then create an object by using the new keyword.

function Apple (type) {
    this.type = type;
    this.color = "red";
    this.getInfo = getAppleInfo;
}

// global function! don't do this...
function getAppleInfo() {
    return this.color + ' ' + this.type + ' apple';
}

While this works fine, it has one drawback –this function is in the "global namespece". to prevent pollution of the global namespace, you can define your methods within the constructor function:

function Apple (type) {
    this.type = type;
    this.color = "red";
    this.getInfo = function() {
        return this.color + ' ' + this.type + ' apple';
    };
}

// Instantiate new objects with 'new'
var apple = new Apple('macintosh');
apple.color = "reddish";
alert(apple.getInfo());

A drawback of above is that the method getInfo() is recreated every time you create a new object. A more inexpensive way is to add getInfo() to the prototype of the constructor function, like :

function Apple (type) {
    this.type = type;
    this.color = "red";
}

Apple.prototype.getInfo = function() {
    return this.color + ' ' + this.type + ' apple';
};

Singleton, Anonymous Function use an anonymous function, when you really want a constructor function that you'll use only once and there's no sense of giving it a name.

var apple = new function() {
    this.type = "macintosh";
    this.color = "red";
    this.getInfo = function () {
        return this.color + ' ' + this.type + ' apple';
    };
}

apple.color = "reddish";
alert(apple.getInfo());

Let’s say that we want to check to see if a property is available “natively” in the browser. For example, the sessionstorage property, which stores data for a given user session, is something that’s new in HTML5.

// Define a variable to store either true or false, using anonymous function, singleton
var isThereSessionStorage = (function() {
//Some older versions of Firefox may throw a security exception error when this code is executed. 
//So if we need to wrap this piece of code inside a try catch block.
  try {
    return typeof window.sessionStorage !== 'undefined';
  } catch (e) {
    return false;
  }
})(); 

if(!isThereSessionStorage)
// our polyfill code goes here....

(3) Using Object.create

// instead of:
// var o = {};
var o = new Object();

// For arrays
// instead of:
// var a = [];
var a = new Array();
var apple = Object.create(Object.prototype, 
  {
    type: {
       value: 'macintosh',
       enumerable: true,
       writable: true,
       configurable: true
     },
     color: {
       value: 'red',
       enumerable: true,
       writable: true,
       configurable: true
     }
   }

(4) Using ES6/ES2015 Class

class is introduced in ECMAScript 2015, is primarily syntactical sugar over JavaScript's existing prototype-based inheritance.

Classes are in fact "special functions".

class Apple {
  constructor(type, color) {
    this.type = type;
    this.color = color;
   }

    this.getInfo = function() {
        return this.color + ' ' + this.type + ' apple';
    };
}

// Instantiate new objects with 'new'
var apple = new Apple('macintosh', 'red');
alert(apple.getInfo());

Note: An important difference between function declarations and class declarations is that function declarations are hoisted and class declarations are not.

immutable

In JavaScript, strings and numbers are immutable by design.

var statement = "I am an immutable value”;
var otherStr = statement.slice(8, 17);

However, reference type can be mutable.

var arr = [1, 2, 3];
var person = {name: “Kai", age: 32};

In order not to change the original value, One must make a deep copy, using one of the following immutable method:

var a = {name: “Kai", things: [0, 1, 2]};

(1) b = Oject.assign({}, a, {name: "John"})
    b = {...a, name: "John"}

    b.things.push(3) //Bad: this changes a as well
    b.things.concat(3) // Good

(2) b = a.concat(3)

(3) b = a.filter((val) => val !==2)

(4) map
     B = Oject.assign({}, a, {new})

(5) reduce

JavaScript doesn’t (yet) have immutable lists and maps, so we’ll need a third-party library for now.

var arr = new ImmutableArray([1, 2, 3]);
var person = new ImmutableMap({name: “Kai", age: 32});

results matching ""

    No results matching ""