Common JavaScript Techniques

Common JavaScript Techniques:

1. Demonstate your understanding of they keyword typeof
console.log(typeof typeof 1);

// this follows the order of operations from keyword closest to the value. In this case, (typeof 1) shall return a string called "number". Next, (typeof "number") would return a string valued as "string"

2. Accessing private methods
var someObject = {
name: 'Some Object',
getName: function(){
var newObject = someObject.getName.bind(someObject);

// In order to access a function with a return of "this" value (meaning someObject), someObject must be specified as the argument to the .bind function. This is required even though the someObject has already been instantiated with the call to someObject.getName property.

3. Array operations
var testArray = [1,2,3,4,5];
// Add items toward the end
testArray = [7,...testArray];

// Insert items at the beginning
testArray = [...testArray,-1];

// splice at certain positions
testArray = [-2,...testArray,8];

4. Inheritance in JavaScript
// Constructor
function animal(type){
this.member = type;
// Add public methods = function(string){
return this.member +"name: "+string;
// Invoke the new public method
var myPet = new animal('dog');"Dragon"); // returns "dog name: Dragon"

5. How to use private
...By observing Closures as characteristics of JavaScript, where inner functions have access to the outer variables and parameters. Here are some examples:

function publicFunction(){ = value;
} = "some name";

function privateFunction(){
var that = this;
var name = value;
function name(){};

function priviledgedFunction(){ = function(){};

6. Demonstrate currying
var operate = function(x){
if (x=='add'){
return function(y,z) {
var result = y + z;
return result;
};//endif add
if (x=='subtract'){
return function(y,z) {
var result = y - z;
return result;
};//endif add

var addNums = operate(add);
var subtractNums = operate(subtract);
addNums(5,5); //10
subtractNums(5,5); //0

7. Self-executing anonymous function
// some code;

// this function has no name, and it's automatically invoked upon instantiation

Leave a Reply

Your email address will not be published. Required fields are marked *