JS 129: Notes Review

Topics of Interest

Objects

Casual Definition: Anything that contains data and is not a primitive type. Object literals, arrays, dates, functions, anything created by a constructor…. Objects consist of key value pairs. An array uses indexes as keys. Object values can be functions, and these are called methods. STATE + BEHAVIOR.

Example:

{ key: value } // property (state)
{ doThis: function() {}} // method (behavior)

Object factories

Casual Definition: “Hi! have you ever thought, I wish i could reproduce this cool object I made, but i don’t know how? well I’m here to help. what if i told you that you could make a cool function that literally returns any object you want? it’s like 3d printing, but for code! Unfortunately, I use a lot of dumb memory cuz i’m just making copies of so much code. but at least i offer privacy and personal space, cuz objects from this object factor don’t have to share methods with anyone else!”

Formal definition: Object factories are functions that create and return new objects of the same type.

Example:

function carFactory(make, model, year) {
return {
make,
model,
year,
startEngine() {
console.log('vroom');
},
};
};
let myCar = carFactory('honda', 'crv', 2013);
myCar.startEngine() // logs "vroom"

Disadvantages:

  • you can’t use the instanceof operator to determine the object type
  • it copies all the methods & properties into the new object, taking up extra memory and creating redundant code.

Advantages:

  • possible to have private state. i could create and define a variable within my function that is not made available in the returned object.

Constructors

Formal definition: Constructors are functions that store data about a type of object and, when used with the new keyword, create new objects whose [[Prototype]] properties are set to the constructors’ prototype objects (the object referenced by the property prototype. Constructors use the this keyword to set properties and methods. they can have an explicit return value, but don’t have to. Unlike with factory functions, objects created by constructors using the new keyword can be identified as being created by that constructor using the instanceof operator.

Example:

// no inheritance
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
Car.prototype.startEngine = function() {
console.log('vroom');
}
let myCar = new Car('honda', 'crv', 2013);
myCar.startEngine() // logs 'vroom'
// with inheritance!function Player(marker) {
this.marker = marker;
}
Player.prototype.getMarker = function () {
return this.marker;
};
function Human() {
Player.call(this, Square.HUMAN_MARKER);
}
Human.prototype = Object.create(Player.prototype);
Human.prototype.constructor = Human;
function Computer() {
Player.call(this, Square.COMPUTER_MARKER);
}
Computer.prototype = Object.create(Player.prototype);
Computer.prototype.constructor = Computer;

What does the new keyword do?

  1. creates a new empty object
  2. assigns new object’s [[Prototype]] property a reference to the constructor’s prototype object (the object referenced by the constructor’s prototype property.
  3. assigns this a reference to the newly created object
  4. invokes function
  5. returns new object

What happens without the new keyword?

  • function will run like a normal function
  • this is implicitly assigned a reference to the global object
  • if no explicit return value, returns undefined

What happens when there’s an explicit return value AND the new keyword?

  • If the return value is an object, function will return that object instead of the newly created object of the desired type.
  • If the return value is a primitive, function will return newly created object instead of the explicit return value.

Prototypes

Definition: Prototypes can mean a few different things. All objects created in javascript have a built-in [[Prototype]] property (called the object prototype) which by default points to Object.prototype, but can be set to reference any prototype object, using Object.create() or a constructor with the new keyword or Object.setPrototypeOf(a, b). All function objects created in javascript have a separate built-in prototype property (called the function prototype) which references a prototype object from which newly created instances of a constructor inherit. When a constructor creates a new object using the new keyword, that object’s [[Prototype]] property is assigned a references to the constructor’s function prototype, or prototype object, and inherits all the properties and methods inside that object.

Example:

function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
Car.prototype.startEngine = function() {
console.log('vroom');
};
let myCar = new Car('honda', 'crv', 2013);
console.log(Object.getPrototypeOf(myCar) === Car.prototype); // true
// object prototype of myCar references function prototype of Car
console.log(myCar.hasOwnProperty('startEngine')); // false
console.log(myCar.__proto__.hasOwnProperty('startEngine')); // true

OLOO

Casual Definition: “hi i’m an object literal, and i’m full of cool methods and properties. you can use me as a prototype to make a bunch of cool objects like me! just fill me up with methods and then make new objects using the method Object.create(me)!

Formal definition: OLOO stands for Objects Linking to Other Objects, and it is a version of prototypal inheritance. OLOO syntax creates a new object literal that contains all the methods you want to assign to a given type of object, and uses Object.create() to make new objects that inherit from said object. OLOO syntax also allows you to defined an init method, that sets the properties of a newly created object, and returns the object referenced by this.

Example:

let petPrototype = {  init(name, species) {
this.name = name;
this.species = species;
return this;
},
walk() {
console.log('i\'m walkin here');
},
run() {
console.log('run forrest run!');
},
};
let myPet = Object.create(petPrototype).init('Cypress', 'dog');console.log(myPet.name); // Cypress
console.log(myPet.species); // dog
myPet.walk(); // i'm walkin here
// with inheritance
const PlayerPrototype = {
initialize(marker) {
this.marker = marker;
return this;
},
getMarker() {
return this.marker;
},
};
let Human = Object.create(PlayerPrototype);Human.init = function() {
return this.initialize(Square.HUMAN_MARKER);
};
let Computer = Object.create(PlayerPrototype);Computer.init = function() {
return this.initialize(Square.COMPUTER_MARKER);
};

Other:

  • no way to define private state
  • don’t forget to return this with init() method

ES6 classes

Casual Definition: easiest way to do all this! works like a constructor bu syntax sort of like an object literal. syntactic sugarrrrr

Formal definition: ES6 classes are another way to create new objects of a certain type using pseudo-classical inheritance. It is a new syntax which is meant to look more like the syntax of other Object oriented programming language. Classes let you define both the properties and static and instance methods for an object. Classes also make use of the keywords extends to create a subclass that inherits from a superclass (setting up the pseudoclassical inheritance chain) and super to call the constructor of the superclass without explicitly setting the execution context.

Example:

class Pet {  static kingdom = 'animalia'  constructor(name, species) {
this.name = name;
this.species = species;
}
static sayKingdom() {
console.log(Pet.kingdom);
}
sayName() {
console.log(this.name);
}
saySpecies() {
console.log(this.species);
}
}
let cypress = new Pet('Cypress', 'dog');
cypress.sayName(); // logs Cypress
Pet.sayKingdom(); // logs animalia
class Dog extends Pet {
static phylum = 'chordate'
constructor(name, breed) {
super(name, 'dog');
this.breed = breed;
}
static sayKingdomAndPhylum() {
console.log(`Dogs are part of the kingdom ${Pet.kingdom} and phylum ${Dog.phylum}.`);
}
sayBreed() {
console.log(this.breed);
}
}
let trout = new Dog('Trout', 'Chocolate Lab');
trout.sayName(); // trout
trout.sayBreed(); // chocolate lab
Dog.sayKingdomAndPhylum();
// Dogs are part of the kingdom Animalia
// and phylum Chordate.class
// ex 2Player {
constructor(marker) {
this.marker = marker;
}
getMarker() {
return this.marker;
}
}
class Human extends Player {
constructor() {
super(Square.HUMAN_MARKER);
}
}
class Computer extends Player {
constructor() {
super(Square.COMPUTER_MARKER);
}
}

Other: This is considered syntactic sugar. Functionality behind classes works just like pseudo-classical method with constructors — classes just make it more readable and

Methods and properties

Definition: Properties are data stored in an object using key value pairs. Methods are properties with functions as values.

Example:

let object = {
a: 1, // property
b: function(num) { // method
console.log(num + this.a);
},
c() {
console.log(`this is a method definition using compact syntax`);
}
}
object.b(1) // logs 2
object.c()

Other: an object’s properties are said to define an object’s “state”, while methods are said to define an object’s “behavior”

Instance and static methods and properties

Definition: An instance method is a method that can be called directly on an instance of an object. It’s generally defined and stored on the prototype object of a constructor or on the instance itself. An example is myArray.forEach(). Likewise an instance property is a property that belongs to a specific instance of an object type and is accessed directly from that instance, for example myArray.length. A static method is a method that is defined and accessed directly on an object’s constructor. It can also be defined in the body of a class definition with the keyword static ( Array.isArray()). A static property, similarly, is stored directly in a Constructor itself, and it is often used to define constants (number.MAX_VALUE) or arrays of objects created by that constructor.

Example:

function Dog(name) {
this.name = name; // instance property
Dog.allDogs.push(this);
}
Dog.prototype.getName = function() { // instance method
return this.name;
}
Dog.allDogs = []; // static property
Dog.getAllDogs = function() { // static method
return Dog.allDogs;
}
let cypress = new Dog('Cypress');
console.log(Dog.getAllDogs());
console.log(cypress.getName());
console.log(Dog.allDogs);
console.log(cypress.name);

Other: note to self — with constructors, you should define a static method outside of the initial constructor.

Prototypal and pseudo-classical inheritance

Definition: Prototypal inheritance is inheriting properties and methods directly from other objects through their [[Prototype]] property. OLOO programming uses this kind of inheritance. Objects are created with their prototypes set to other objects, and the inheriting object delegates some of its behavior to its prototype. Pseudoclassical inheritance seeks to mimic classical inheritance of other object oriented programming languages. It involves a constructor’s prototype inheriting from another constructor’s prototype (subclass inheriting from superclass). When we assign an object’s [[Prototype]] the prototype object of another constructor, we are using pseudoclassical inheritance.

Example:

// Prototypallet animalPrototype = {
walk() {
console.log('i am walking');
}
};
let dog = Object.create(animalPrototype);
dog.speak = function() {
console.log('bark bark');
};
dog.walk(); // logs i am walking
dog.speak(); // logs bark bark
// Pseudoclassicalfunction Animal() {}Animal.prototype.walk = function() {
console.log('i am walking');
};
function Dog() {
Animal.call(this);
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.speak = function() {
console.log('bark bark');
};
let doggy = new Dog();
doggy.walk();
doggy.speak();

Encapsulation

Definition: Encapsulation is combining related state (properties) and behavior (methods) into a common object — combining the data and the actions associated with that data together. This is a fundamental concept behind Object Oriented Programming.

Other: In other languages, encapsulation might also refer to objects having private state, and restricting access to certain state and behaviors outside of the object so that implementation details are hidden unless necessary for other parts of an application to work.

Polymorphism

Definition: Polymorphism refers to the ability of objects with different types to respond to the same method invocation. It can be implemented through inheritance by method overriding. It can also be implemented through duck typing; by ensuring that objects of different types use the same method name to perform different but related functions, those objects can be interacted with in a uniform way.

Example: Object.prototype.toString() vs Array.prototype.toString() vs Number.prototype.toString()

class Dog {
speak() {
console.log('bark');
}
}
class Bird {
speak() {
console.log('tweet');
}
}
class Cat {
speak() {
console.log('meow');
}
}
let Animals = [new Dog(), new Bird(), new Cat()];Animals.forEach(animal => {
animal.speak();
}); // logs bark, tweet, and meow

Other: Can be used in a couple ways.

  1. inheritance — like toString() — is polymorphism in which two different object types can respond to the same method call simply by overriding a method inherited from a superclass
class Animal {
move() {}
}
class Fish extends Animal {
move() {
console.log("swimming");
}
}
class Cat extends Animal {
move() {
console.log("walking");
}
}
// Sponges and Corals don't have a separate move method - they don't move
class Sponge extends Animal {}
class Coral extends Animal {}
let animals = [new Fish(), new Cat(), new Sponge(), new Coral()];
animals.forEach(animal => animal.move());

2. through duck typing! (if it quacks like a duck, we’ll treat it as a duck). When objects of different unrelated types both respond to the same method name.

class Chef {
prepare(wedding) {
this.prepareFood(wedding.guests);
}
prepareFood(guests) {
// implementation
}
}
class Decorator {
prepare(wedding) {
this.decoratePlace(wedding.flowers);
}
decoratePlace(flowers) {
// implementation
}
}
class Musician {
prepare(wedding) {
this.preparePerformance(wedding.songs);
}
preparePerformance(songs) {
// implementation
}
}
class Wedding {
constructor(guests, flowers, songs) {
this.guests = guests;
this.flowers = flowers;
this.songs = songs;
}
prepare(preparers) {
preparers.forEach(preparer => {
preparer.prepare(this);
});
}
}

Collaborator objects

Definition: Collaborator Objects are objects that help to define the state of other objects. For example, if I have a Deck object and a Card object, and the Deck object has a property that consists of an array of Card object, the Deck and Card objects are collaborators. Collaboration lets you chop up a problem into smaller cohesive pieces.

Example:

let cat = {
name: 'Fluffy',
makeNoise() {
console.log('Meow! Meow!');
},
eat() {
// implementation
},
};
let pete = {
name: 'Pete',
pet: cat,
printName() {
console.log(`My name is ${this.name}!`);
console.log(`My pet's name is ${this.pet.name}`);
},
};

Other: Built-in objects like Arrays and Dates are also collaborators!

Single vs multiple inheritance

Definition: Javascript is single inheritance — meaning that objects can only directly inherit from one other object. They only have one [[Prototype]]. In other languages, there might be multiple inheritance, when objects can inherit from more than one prototype object and classes can inherit from multiple other superclasses. In Javascript, we can mimic the idea of multiple inheritance by creating mix-ins (more below).

Example:

class Bird {}  
class FlyingBird extends Bird {
fly() {}
}
class SwimmingBird extends Bird {
swim() {}
}
class Stork extends FlyingBird {}
class Parrot extends FlyingBird {}
class Penguin extends SwimmingBird {}
class Ostrich extends SwimmingBird {}
// Hmmm.... we have a problem.
// What to do with ducks and geese???
// we can't inherit from both classes!
class Duck extends FlyingBird {
swim() {}
}
class Goose extends FlyingBird {
swim() {}
}

Mix-ins

Definition: A mix-in is a bundle of methods & properties that can be mixed into a class using Object.assign or something similar. Object.assign copies properties from a mix-in object into a constructor’s prototype object (or into a class). Mix-ins should be used when an object needs to have a certain capability (as opposed to inheritance which works with an “is a” relationship).

Example:

const Swimmable = {
swim() {}
}
const Flyable = {
fly() {}
}
class Stork {}
Object.assign(Stork.prototype, Flyable);
class Parrot {}
Object.assign(Parrot.prototype, Flyable);
class Penguin {}
Object.assign(Penguin.prototype, Swimmable);
class Ostrich {}
Object.assign(Ostrich.prototype, Swimmable);
class Duck {}
Object.assign(Duck.prototype, Swimmable, Flyable);
class Goose {}
Object.assign(Goose.prototype, Swimmable, Flyable);
// example 2
let Hand = {
addToHand(newCard) {
this.cards.push(newCard);
},
resetHand() {
this.cards = [];
},
showHand(caption) {
console.log(caption);
console.log("");
this.cards.forEach(card => console.log(` ${card}`));
console.log("");
},
getCards() {
return this.cards;
},
revealAllCards() {
this.cards.forEach(card => card.reveal());
},
numberOfCards() {
return this.cards.length;
},
};
Object.assign(Player.prototype, Hand);
Object.assign(Dealer.prototype, Hand);

Other: Some developers like to use mix-ins with factory functions, but it has the downsides of other factory functions (memory, hidden constructor)

Methods and functions; method invocation vs. function invocation

Definition: Method invocation is when you call a method on an object — it looks like myObject.doAction(). With method invocation, the implicit execution context of the method is the calling object ( myObject ). Function invocation is calling a function without a calling object, like print(). With function invocation, the implicit execution context is the global object.

Example:

function foo() {
this.bar = 'bar';
}
foo(); // function invocation
global.bar; // bar
let foo = {
bar: function() {
console.log(this);
}
};
foo.bar(); // method invocation
// `foo` is the implicit execution context for `bar`
// { bar: [Function: bar] }

Higher-order functions

Definition: Higher order functions are functions that accept other functions as arguments or return functions. Array.prototype.map() and the like are all higher order functions that take functions for an argument.

Example:

function createGreeter(language) {
switch(language) {
case: 'eng' {
return function() {
console.log('hello!');
}
}
case: 'sp' {
return function() {
console.log('hola!');
}
}
case: 'ger' {
return function() { // returns an anonymous function
console.log('guten !');
}
}
}
}
let englishGreeter = createGreeter('eng');

The global object

Definition: The global object is the implicit execution context for function calls, meaning that when you call a function using function notation, this is assigned a reference to the global object. Like any object, the global object has properties and methods, including NaN, infinity, isNaN(), parseFloat(). When you declare a variable without using a let, const, or var keyword, you are creating a property of the global object.

Example:

function myFunction(num) {
this.number = num;
}
myFunction(1);
letter = 'a';console.log(global.number); // logs 1
console.log(global.letter); // logs a

Other: In node, the global object is called global, in a browser it’s called window

Method and property lookup sequence

Definition: The method and property lookup sequence refers to how Javascript finds methods and properties in an object’s prototype chain. Javascript initially searches the object, then it searches the object’s prototype, then the prototype’s prototype, until it reaches Object.prototype. If JS doesn’t find the method or property in Object.prototype, it returns undefined.

Example:

let myArray = [];
let prototypeLevel1 = Object.getPrototypeOf(myArray);
let prototypeLevel2 = Object.getPrototypeOf(prototypeLevel1);
console.log(myArray.hasOwnProperty('length')); // trueconsole.log(myArray.hasOwnProperty('toString')); // false
console.log(prototypeLevel1.hasOwnProperty('toString')); // true
console.log(myArray.hasOwnProperty('hasOwnProperty')); // false
console.log(prototypeLevel1.hasOwnProperty('hasOwnProperty')); // false
console.log(prototypeLevel2.hasOwnProperty('hasOwnProperty')); // true
console.log(myArray.hasOwnProperty('cats')); // false
console.log(prototypeLevel1.hasOwnProperty('cats')); // false
console.log(prototypeLevel2.hasOwnProperty('cats')); // false

Function execution context and this

Definition: Execution context is the environment in which a function or method executes. It refers to the current value of the this keyword.

Example:

let foo = {
myFunction() {
console.log(this);
}
};
function bar() {
console.log(this);
}
foo.myFunction(); // prints out foobar(); // prints out object [global]

Implicit and explicit execution context

Definition: Implicit execution context is the environment automatically assigned to a function by javascript. Whenever a function is called, JS binds an implicit execution context to the keyword this. This is why function invocation automatically assigns the global object to this , and method invocation automatically assigns the calling object to this. The execution context for a function can however be set explicitly using the call, apply, or bind methods, or an optional thisArg argument when it applies. Explicitly setting an execution context can help prevent context loss.

Example:

// implicitlet foo = {
myFunction() {
console.log(this);
}
};
function bar() {
console.log(this);
}
foo.myFunction(); // logs foo
bar(); // logs [global object]
// explicitlet foo = {
myFunction() {
console.log(this);
}
};
function bar() {
console.log(this);
}
foo.myFunction.call([]); // logs [], explicit context set to []let boundBar = bar.bind({});
boundBar() // logs {}, explicit context bound to {}

Dealing with context loss

Definition: Context loss happens when a function is put in a different context than originally intended, and unexpected behavior results. Context loss can happen when a function is nested inside a different function, moved from an object into another function, or passed as an argument to a function (like forEach). You can deal with this context loss through hard-binding with bind, using call or apply methods, creating a context variable self in a local scope and assigning it a reference to this, using arrow functions, or using an optional thisArg argument.

Example:

// context loss when method is passed into another function as argument
let obj = {
a: 'hello',
b: 'world',
foo: function() {
[1, 2, 3].forEach(function(number) {
console.log(String(number) + ' ' + this.a + ' ' + this.b);
}); // function is actually executed by forEach, so context is global object, rather than “obj”
},
};
obj.foo();// orconst survivorSeasons= {
titles: ['Cook Islands', 'Micronesia', 'Pearl Islands', 'Australian Outback', 'All Stars'],
showTitle: 'Survivor',
listGames: function() {
this.titles.forEach(function(title) {
console.log(this.showTitle + ': ' + title);
});
}
};
survivorSeasons.listGames();// context loss when method is moved from another object
function repeatThreeTimes(func) {
func(); // can't use func.call(john); john is out of scope
func();
func();
}
function foo() {
let john = {
firstName: 'John',
lastName: 'Doe',
greetings: function() {
console.log('hello, ' + this.firstName + ' ' + this.lastName);
},
};
repeatThreeTimes(john.greetings); // Strips context
}
foo();// context loss when function is nested in an another function
let obj = {
a: 'hello',
b: 'world',
foo: function() {
function bar() {
console.log(this.a + ' ' + this.b);
}
bar();
},
};
obj.foo(); // => undefined undefined// hard binding
let obj = {
a: 'hello',
b: 'world',
foo: function() {
[1, 2, 3].forEach(function(number) {
console.log(String(number) + ' ' + this.a + ' ' + this.b);
}.bind(this); // permanently binding function context to this
// no matter how it's called
},
};
// context variable
let obj = {
a: 'hello',
b: 'world',
foo: function() {
let self = this;
[1, 2, 3].forEach(function(number) {
console.log(String(number) + ' ' + self.a + ' ' + self.b);
});
},
};
// arrow function
let obj = {
a: 'hello',
b: 'world',
foo: function() {
[1, 2, 3].forEach(number => {
console.log(String(number) + ' ' + this.a + ' ' + this.b);
});
},
};
// thisArg
let obj = {
a: 'hello',
b: 'world',
foo: function() {
[1, 2, 3].forEach(function(number) {
console.log(String(number) + ' ' + this.a + ' ' + this.b);
}, this);
},
};

call, apply, and bind

Definition: call is a method that assigns an explicit execution context to a function. call is invoked directly on the function that is being executed, and it completes the execution within the context is passed in as the first argument. Any other function arguments are passed as the second & third arguments and so forth. apply is similar to call in that it assigns a function an explicit execution context. The main difference is that after the first argument, the remaining function arguments are passed in as an array of arguments. bind is another method to set an execution context, but rather than executing the function in a specified context, bind permanently binds the objects to the specified context, and returns the new bound function. Now anytime you call the bound function, the context will permanently be assigned to the context specified in the first argument to bind. Using call or apply on a bound function won’t change the context. One downside of bind is that you can’t use the invocation method to determine the execution context.

Example:

// with context loss
let obj = {
a: 'hello',
b: 'world',
foo: function() {
function bar(argument1) {
console.log(this.a + ' ' + this.b + ' ' + argument1);
}
bar('hi');
},
};
obj.foo(); // => undefined undefined hi// with call
let obj = {
a: 'hello',
b: 'world',
foo: function() {
function bar(argument1) {
console.log(this.a + ' ' + this.b + ' ' + argument1);
}
bar.call(this, 'hi');
},
};
obj.foo(); // => hello world hi// with apply
let obj = {
a: 'hello',
b: 'world',
foo: function() {
function bar(argument1) {
console.log(this.a + ' ' + this.b + ' ' + argument1);
}
bar.apply(this, ['hi']);
},
};
obj.foo(); // => hello world hi
// with bind
let obj = {
a: 'hello',
b: 'world',
foo: function() {
let bar = function(argument1) {
console.log(this.a + ' ' + this.b + ' ' + argument1);
}.bind(this);
bar('hi');
},
};
obj.foo(); // => hello world hi

Other: None of these methods mutate the original function.

Object.assign and Object.create

Definition: Object.assign is a method in the built-in Object constructor that takes two or more object arguments and copies all of the properties and methods from the objects passed in as second + arguments into the object passed in as the first argument. Object.assign permanently mutates the object passed in as the first argument. Object.create is another method in the built-in Object constructor. It takes one argument, an object, and returns a new object whose [[Prototype]] property is set to the object passed into the argument. Object.create does not mutate the object passed in as argument.

Example:

let myObject = Object.assign({}, {cat: 'meow', dog: 'woof'})
console.log(myObject); // logs {cat: 'meow', dog: 'woof'}
let inheritedObject = Object.create(myObject);console.log(inheritedObject); // logs {}
console.log(Object.getPrototypeOf(inheritedObject));
// logs {cat: 'meow', dog: 'woof'}

Other: In OO programming, Object.assign is used with mix-ins. Object.create is used for regular prototypal inheritance, OLOO, and pseudoclassical inheritance with constructors.

Built-in constructors like Array, Object, String and Number

Definition: You can use built-in constructors with the new keyword to treat them all as objects.

  • Arrays created using the new keyword are passed arguments separated by commas that correspond with the array elements, or if you pass in a single number argument, it creates an empty array with the length property set to that argument. One useful application of this is with Array.prototype.fill which replaces all elements of its calling array with its argument (new Array(3)).fill(‘*’) // [‘*’, ‘*’, ‘*’]). The Array constructor still works exactly the same if you use the new key word or not! (`new Array(1,2,3)` has same results as `Array(1,2,3)`).
  • Object constructor creates new objects. Can alsobe invoked without the new keyword. All objects created with Object literal syntax inherit from Object.prototype. All arrays also have access to methods on Object.prototype. Almost all JavaScript objects, whether built-in or custom-created, inherit from Object.prototype, either directly or further down the prototype chain.
  • The Date constructor creates date object representing specific date and time. Calling Date w/o args returns object representing date of creation
    you can also call with many different types of argument.
  • String objects are created with the String constructor (new String(‘xyz’)) and are not the same as string primitives. A string primitive’s type is ‘string’, but the String object’s type is ‘object’. When you call a method on a string primitive, Javascript invisibly wraps the primitive in a string object, and uses the object to access the property to call a method. once the method has been called, JS discards the string object. When properties or methods return strings, they return primitives. It’s generally not a good idea to create string objects explicitly. String() used without the new keyword just returns a new string literal.
  • The Number and Boolean constructors work in much the same way as the String constructor. When called with new, they create Number and Boolean objects. When called without new, the Number function converts its argument to a number, and the Boolean function converts its argument to a boolean.

Example:

let emptyArray = new Array(0,1,2,3)Date.prototype.toString (‘Sat Jun 01 2019 01:15:06 GMT+0500 (Pakistan Standard Time)’)
Date.prototype.getFullYear (2019)
Date.prototype.getDay (zero-indexed representation of week day)
String(‘abc’) // ‘abc
String(undefined) // ‘undefined’
Number(‘123’); // 123
Boolean(0); // false
Boolean(‘abc’); // true

Other: You can add methods to built-in prototypes, but you shouldn’t. You can use array methods on strings using call! Even though they don’t have the the same prototype chain, they do have indexable elements and a length property. Just don’t use mutating array methods, because strings are immutable.

Some Specific Definitions

Variables

  • Variables declared with let, const
  • Function parameters
  • Function names
  • Class names

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Puppeteer’ing in Firebase & Google Cloud Functions

Master regular expressions in JavaScript

React-Rails User Authentication(Part 2- React Frontend)

PayUbiz UI Integration

How To Add Schema JSON-LD to Your Hugo Blog/Site

The best programming articles of the week

Did you know Chrom DevTools can do this?

Node Testing Frameworks: The Good, the Bad, the Slow and the Hungry

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Liza Couser

Liza Couser

More from Medium

Millimeter DApp Architecture

Weights Aequilibrium

How I got into Red Hat, Part 1

CS373 Spring 2022: Sahran Hashim