What and why in JS

Key JavaScript code concepts for achieving success in programming.
On this page

1.0 Since JS has no interfaces how it is implemented

To understand what interface do and what is required one needs to have some object oriented programming knowledge. It is similar to class but can not be instantiated. It only exposed methods that interested object or class can implement the way they want. When a class implements an interface it is said to inherits the abstract functions, along with any other members defined in interface. e.g, any constant , methods , static methods and any nested types. NOte> Abstract methods do not have any code that are only blue prints for those who inherit them so provide the body by writing the code.

1.1 What is Duck Typing in JS

1.2 What does it mean to say JavaScript needs a host environment to run

Traditionally a programme written in high level computer language is either compiled or interpreted into machine language so that it can be run by the machine operating system. This is the direct approach of running a programme. There exist another way which allows a programme to be written or scripted for another programme known as host. Now it is the responsibility of the host programme to run the script this may be regarded as an indirect approach . Javascript belongs to the second group which needs a host environment to be run. For example when a programme written in JS is included in an html page it is said to be embedded in html. This html page is run by the browser. The browser has the ability to start JS programme because another piece of code called interpreter also known as JS engine is embedded in the browser. Therefore browser which itself is a computer programme probably written in C or C++ loads the JS engine when encounters the JS script in Html page and let the interpreter do the rest of the job of executing the JS script or code or programme. In modern day computing, the term script and programme are used interchangeably. But in early days scripting was regarded much easier than programming. With the advent of NodeJS, JavaScript can be run in nodeJs environment acting as a host for JavaScript programme. NodeJs is itself a programme where a popular v8 engine is embedded to run JavaScript programmes

1.3 What was the need behind the JavaScript creation

In early 1990s, the company called Netscape communications wanted Netscape browser to have the ability to run external programme to achieve more flexibility over html pages.The company hired Brendan Eich to attach/embed another language in HTML. Soon “LiveScript” was born, but its name was changed into “JavaScript” because of the reasons that Java language at that time was getting popularity as an alternative to c++ and was much easier to learn and programme than its counterparts. Though JavaScript and Java may sound related but they were not. Java language was designed as an Object oriented class based languages from top down providing code re use through classical inheritance, while JavaScript was Object based language with features of functional programming disguised in c style coding , providing code reuse through prototype inheritance. Having one programme to be able to run another programme which can control the contents of first programme was turned out to be very beneficial.*/

1.4 What are global variables of host environment

A host environment that runs the JS programme expose some variables to be used in JS programme this variable or variables are called “global” variables. These global variables can be used in the programme so that they can be manipulated. For example browsers exposes a variable called “window” which is commonly used in JS script. Similarly nodeJS also exposes a global variable known as “global” when working in REPL shell.

1.5 What are user defined global or local variables

The word global or local refers to variables visibility and has to do with the scope of the variable. It is the scope which defines whether a given variable can be accessed from certain position in the programme or not. All variables which are declared globally ( not inside any function or any object ) are accessible from anywhere in the programme. In contrast variables defined in functions are known as local variable and only visible inside the function.

1.6 What are static variables

A static variable as the name suggest is static by creation. It comes into being when the programme is compiled and lasts for the entire life of the programme. In OOPs a static member variable, which is a class variable that belongs to the type and not to every instance or every object of a that particular type . Being static means that it can not be controlled by the instantiated object but by its blueprint. Since Js is class less language the closest thing is the constructor function that defines the type, thus can be shared by all instances of that type. Though it can be shared among all type but can only be updated by the blue print or the class itself. The common use of the static variable to keep the count of the same type being created.

 1 // Declare your constructor
 2 var Animal = function(name){
 3  Animal.count++;
 4  this.name = name;
 5 };
 6 //Initialize the static variable with the help of the constructor name
 7 var Animal.count = 0;
 8 // create an instance of Animal
 9 var rabbit = new Animal("bunny");
10 var cat = new Animal("nimmy");
11 console.log("Animal count is " + Animal.count); //2

1.7 How to avoid static variable defined globally

 1/* The above can be avoided as shown below */
 2var Animal = function (name) {
 3  Animal.count = ++Animal.count || 1 // first time it is undefined
 4  this.name = name
 5}
 6var fish = new Animal('gold')
 7var pony = new Animal('gil')
 8console.log('Animal count is ' + Animal.count) // 2
 9/* If we could see closely the constructor function has no special construct, but because of calling with `new` operator it returns an object by default. As long as it is returning the object, this special function would be regarded as constructor function otherwise it would be an another normal function. Having said that, this technique could be used for keeping track of how many times the function was called. A normal generic function can be written as follows:*/
10
11function fn() {
12  argument.callee.count = ++arguments.callee.count || 1
13  console.log(arguments.callee.count)
14}
15// Now the above function can be renamed to what ever you want.

1.8 What is a leaking global variable

1/*
2If you add variable to global space, it is available to global objects and becomes the property of the global object.
3 */
4var x = 10
5console.log(global.x) //
6/*
7The x variable can be accessed by any global object. This is regarded leaking the global variable. To avoid this, if yo do not need to make it global, always write in a closure/ anonymous function or have some other mechanism that does it for you.
8 */

1.9 What is the proper way of avoiding the global variable leakage

 1;(function () {
 2  var x = 10
 3})()
 4/*
 5If you need to  expose this variable to any object then have a function to do this which is passed that object as an argument.
 6 */
 7function initialize(obj) {
 8  obj.x = 10
 9}
10// or more precisely
11function initialize(myObject) {
12  myObject.myVariable = ' private to only this object'
13}
14/*
15The above is a function and its invocation can be deferred until we need it.
16This discussion is about how to make you code modular
17 */

1.10 What is a property in JavaScript

1/* JS is object based language. Object is a Data type,that represent more structured data than primitive data types.Data in objects are stored in pairs what is known as name and value or more often key/value pair. The name/key in JavaScript is known as the "property" of the object, which always maps itself to its assigned "value". This property in JS is a string a non numeric value.*/
2var o = { x: 1, y: 2 }
3/* In above code x and y are properties  of object o when accessed they are turned into string before accessing the values. Therefore o.x is equal to o["x"].
4 */
5// The same is usually written like this
6var o = {
7  x: 1,
8  y: 2
9}

1.11 Does properties of object have associated attributes

1 /* All properties when declared are given some default attributes. Number one is a "value" which needs to be assigned, there are three more attributes attached to them. Below are given all four attributes:*/
2 > var x = 10;
3 > console.log(Object.getOwnPropertyDeiscriptor(global,"x"));
4 > { value: 10,
5   writable: true, // can be updated
6   enumerable: true, // can be enumerated when needed
7   configurable: false // the above behaviour can not be changed
8  }
9  /* if " writable " become false, it can not be changed, it act like a constant variable. If "enumerable" is set to false, it can not be enumerated using `for(prop in object)` loop or in `Object.keys()` method It remains hidden. JavaScript most `fundamental object` sets this property to false on some properties if they are not be shown. Similarly if a configurable attribute is set to false, it simply means that the other two attributes can not be assigned any other value. Or this property  attributes can not be assigned again. In case of re assignment it throws an error*/

1.12 What happens to globally declared variables

1/* When variables are declared globally. JavaScript make them properties of a global object exposed by the host environment. In browser this global object is "window" and in nodeJS working with REPL shell it is "global" but in js file, it is the programmer that defines the global object.
2 */

1.13 How property attributes can be seen

1 /* Use "getOwnPropertyDescript(target) static method on Object by providing the target object as an argument to get the result as shown below."
2  */
3 > var o = {}
4 > Object.definePropterty(o,x,{value:10,writable:true,enumerable:true,configurable:false});
5 >console.log(Object.getOwnPropertyDescriptor(o,"x"));
6 /*{ value: 100,
7  writable: false,
8  enumerable: true,
9  configurable: false }*/

1.14 How property can be made constant so it can not be either changed or deleted

1.16 How to make a property readable

1/* Make its writeable attribute false as well as configurable false too*/

1.16 What does it mean to say that a property can not be redefined

 1/* If a configurable attribute of any property is set to false, then it can not be redefine again.
 2 */
 3'use strict'
 4var o = {}
 5Object.defineProperty(o, 'x', {
 6  value: 100,
 7  writable: false,
 8  enumerable: true,
 9  configurable: false
10})
11console.log(o.x) // should be 100.
12o.x = 11 // TypeError. An error is thrown in strict mode,
13console.log(o.x) // it can not be assigned any value

1.17 How to iterate over all properties enumerable or not

1/* Non enumerable properties does not show in `..in..` operator. To see them `console.log(Object.getOwnPropertyNames(obj))` This will give an array of all properties available. This method can be changed with others
2 */
3var obj = { x: 1, y: 2, r: 10 } // supposing they were defined non numerable
4console.log(Object.getOwnPropertyNames(obj)) //[ 'x', 'y', 'r' ]
5console.log(Object.getOwnPropertyNames(obj).sort()) //[ 'r', 'x', 'y' ]

1.18 What is a property descriptor object

1/* It is the object created internally to keep track the attributes of any object's properties. To get the reference to this object " Object.getOwnPropertyDiscriptore(target)" function is used.
2 */

2.0 Variables

2.1 How to declare a variable

1/* Simply use a keyword `var` preceded by legal variable name. JS by default assigns it a special data type known as `undefined` */
2var a // a is declared, by default it is assigned an `undefined`
3console.log(a)

2.2 How to declare more than one variable

1/*
2 A common pattern used in nodejs when importing module, 
3  */
4var assert = require('assert'),
5  should = require('should'),
6  express = require('express')
7
8// Or
9var var1, var2, var3

2.3 What is a type in JavaScript

1/* A type defines the nature of the data you want to store. There are primitive data type and structured data type known as objects.
2 primitive data type: number,string,boolean,null,undefined and symbols(ES-6)
3 structured data type: object
4 When a variable is declared without being assigned any value its type is not assigned yet. When the programme runs JS engine assigns it a default type known as "undefined".
5  */

2.4 How a type is assigned to a variable that stores the value

1/* JS is loosely typed language, when a variable is declared its type is not defined like in C , C++ or Java.
2 When a variable is assigned any value , the value determines the type of the variable at run time. This is one of the reasons it is called dynamic language.
3  var x ; // type is not undefined.
4  console.log(typeof x); // undefined.
5  x = 10; console.log(typeof x); // number. values(integer,floating,double)
6  x = true; console.log(typeof x); // boolean. values(true or false )
7  x = "JS"; console.log(typeof x); // string. value( any combination of characters enclosed in single or double quotation marks)
8  x = null; console.log(typeof x); // null value(null)
9  */

2.5 How primitive data types are declared

1/* Primitive data type are not created as object, but simply declared. Declaration is enough for their existence.*/
2var x // a variable is declared

2.6 How primitive data types are assigned values

1/* variables are assigned values using assignment "=" operator
2 var x = 100; // There are two operation performed 1. previous value of x is deleted if any present then new value is assigned to it. This process is called initialisation. It is equal to the following.*/
3var x
4x = 10
5/* If same variable is assigned a value more than once, only the last value is valid */
6x = 20
7x = 30
8console.log(x) // 30. 10 and 20 are lost
9/* If previous value needs to be saved it must be assigned to any other variable */

2.7 How primitive data types are copied

 1/* They are copied by value and not by reference */
 2x = 30
 3var y = x
 4x = 100
 5console.log(x) // 100.
 6console.log(y) // 30.
 7/*
 8 The above behaviour happens because primitive data type are copied by value and not by reference. When the expression `y = x` is executed value of x is created and assigned to y. Having done this if x value is changed, it will not make any difference to y.
 9 Note: If they were copied by reference the value of `y` would always show the last value assigned to x. Because it was pointer to x.
10 */

2.8 Is function a type in JS

1/* When a variable is declared and assigned any value, it gets its type according to its value. Similarly when a function is declared it gets it type as function. This type comes from the built in constructor "Function()". Thus an object returned by this constructor is denoted by a function type.
2 > Note: You do not need to call this function constructor explicitly. Declaring a function automatically calls it and returns a new object of type function which is referred by the function name you provided.
3  */

2.9 What does it mean to say that primitive data types are mutable

1/* A variable that holds the value can be changed as shown below;
2  var x = 10;
3  x = true;
4  x = "JS";
5 It is the last value that is taken the rest are thrown away.
6 Js primitive data types can be changed once they are assigned. To find out about the type of any variable  a `typeof()` operator is used.
7 */

2.10 What does it mean to say variables are hoisted in JS

 1console.log(x) // undefined
 2var x
 3
 4/* In above code, variable x is used before it was declared. It is not possible if execution happens in sequential manner. When JS programme is run it is first parsed,one of the job of this parsing is to collect all declaration of variables and functions as well as the arguments passed in function to gather at one place. So when they are referred again in program, JS environment knows about their existence. This process is also known as hoisting. If it was not declared at all it would have thrown an error.
 5 ---------------------------------------------------------------------------
 6 var x = 10
 7 // other code
 8 ...........
 9 console.log(y); // ReferenceError: y is not defined anywhere in the programme
10 ---------------------------------------------------------------------------
11 Similarly only declaration is hoisted not the assignment.
12 var x = 10;
13 // other code
14 console.log(x + y); // NAN. (10 + undefined)?
15 var y;
16  */

2.11 What is a global variable

1/* JavaScript allows variables to be declared anywhere in the programme. They can be declared either at the top of the programme or in the middle of the programme or at the end of the programme. As long as they are not declared within any function or inside any object. They are labelled as global variable.
2 */

2.12 What is true-global vs implied-global variable

 1 /* If a variable is declared with a key word "var" like " var x = 10", it is regarded as true global variable. Being a true global variable sets the value of its "configurable" attribute to false that is, it can neither be deleted by using a "delete" operator, nor the other two attributes can be changed.
 2 */
 3 > var x = 10;
 4 > delete x;
 5 > false;
 6 > console.log(x); // 10. It still exist.
 7 /* But if a variable is assigned a value without it being declared  using "var", it is taken an implied global and can be deleted using "delete" operator. */
 8 > y = x;
 9 > delete y;
10 > true;
11 > console.log(y); // ReferenceError. y is not defined

2.13 How to avoid global variables becoming the property of the global object exposed by the host environment

1/* Provide them a scope or declare them in an object.*/

2.14 Can JavaScript variables be declared without the keyword var

 1/* Declaring a variable is seen within the context where it is declared. Variables declared in global context varies from the variables declared inside any functions. For example any variable declared globally without `var` is flagged as an error unless it is used with in any expression.
 2 */
 3var x = 10 // A true global
 4y = x // y is implied global
 5console.log(x + a) // undefined. No error thrown
 6z // error.
 7// Declaring inside a function
 8function fn() {
 9  t
10  console.log(t)
11}
12// The above will not throw an error unless it is run. A function declaration is not a function expression. When a function is invoked , it is flagged an an error.

3.0 Functions in JavaScript

3.1 What is a Function with capital F

1/* JS environment provides number of built in objects ready to be used. They are known by different names like universal objects,global objects or fundamental objects. They are more than 70 objects. Some of commonly used one are given below.
2 >Object,Array,Date,Function,
3 >>Boolean,Number,Math,
4 >>>RegExp,Error,TypeError,Map,Set,Iterator etc
5 Function is also an object in JS and can be used to create functions from Function constructor.
6  */

3.2 If everything in JS is objects how are they created

3.3 How to declare a named function

1function fn() {}
2/* A function declaration always hoisted */

3.4 What happens if a same identifier is used to define other function

 1/* JavaScript behaviour of assignment operator is as follows:
 2 1. Primitive data type are assigned by value.
 3 2. Objects data type are assigned by reference.
 4 When variables are copied they are copied by value, thus the new variable has its own contents and change in the original does not depict in the copy.
 5 Dealing with object is different,since function is also a type of object thus assigning one function to another function only copies the pointer. Therefore change in the original reflects in the copy. 
 6  */
 7function fn() {
 8  console.log('I am first  fn')
 9}
10function fn() {
11  console.log('I am second  fn')
12}
13fn() // I am second fn. The first one is lost
14function f1() {
15  console.log('I am no 1')
16}
17// Have a pointer to f1,
18var pf = f1 //
19// Now declare it again using same identifier
20function f1() {
21  console.log('I am no 2')
22}
23f1() // I am no 2
24pf() // I am no 2 // why not "no 1" ?
25
26/* The pointer of f1 gets the same result because function was not copied only the pointer. Second point is to note that. `pf = f1` expression evaluates on run time. At run time the value of f1 will point to the last value assigned to it because of hoisting. Thus it will always show " I am no 2"
27 */

3.5 How to store the pointer to function declaration before it is changed

 1/* No matter where you declare the function in a same scope ( being an object ), Js will hoist its declaration. Thus avoid declaring a same function  again down the line . If you have to change, do not declare them again, assign the new value. This is how the reference to the old value is not lost. */
 2function fn() {
 3  console.log('This is fn')
 4}
 5// copy fn to another variable
 6var f = fn
 7f() // This is fn
 8fn() // this is fn
 9/*
10 The  above shows that function object fn is now pointed by another variable f and can be invoked by both of them.
11  */
12function f1() {
13  console.log('I am no 1')
14}
15f1() // I am no 2. Why because down the line it has been re declared
16// Have a pointer to f1,
17var pf = f1
18// Now declare it again using same identifier
19function f1() {
20  console.log('I am no 2')
21}
22f1() // I am no 2
23pf() // I am no 2
24/* 
25  To store the pointer to previous declaration, this is how it is done
26  */
27function fn() {
28  console.log('first fn')
29}
30// copy fn to another variable
31var f = fn
32// now assign new value to fn.
33fn = function fn() {
34  console.log('second fn')
35}
36f() // first fn
37fn() // second fn
38f() // first fn

3.6 How to re assign a function

 1/* Re assigning function is different from declaring it again within the same scope. If you re declare it, because of hoisting all variable or identifier or pointer to the original declaration will have point to new declaration. But in case or re assigning it a new value either a new function or anything else will divert its pointer to a new value leaving all other identifier as it as.
 2 */
 3function fn() {
 4  console.log('This is old')
 5}
 6var pfn = fn
 7// assign new value to fn
 8fn = function () {
 9  console.log('This is new')
10}
11// invoke them
12fn() // This is new;
13pfn() // This is old .
14/* The reference to old value of function was saved and used */

What happens when a function is declared

 1 /* Declaring a function is not same as invoking the function. Only declaring a function does not execute the function. If a function is only declared as shown */
 2 function fn(){}.
 3 /*
 4  The following things happens when the code is compiled
 5 1. The function identifier is stored as a reference variable to the function. This identifier or a name of a function, in above case "fn" represent an object of type "Function". In other words, when code is compiled, the built in constructor function "Function()" is used to create the function.
 6 */
 7 console.log(fn); // [Function:fn]
 8 console.log("fn---> " + fn); // fn--->function fn(){}
 9 /*
10 Variable fn ( which is a Function object ) now refers to a function--->function fn() {}
11 2. A list of parameters are stored if any passed.
12 3. Determine the value of `this` according to function's scope
13 */
14 console.log(typeof fn); // function.
15 console.log(fn instanceOf Function); true.
16 console.log(fn.constructor); //[Function:Function]

What happens when a function is executed

1/* 
2 A function must be executed with respect to its scope. Thus, attention must be paid at the time of function declaration because the place it is declared provide its scope.
3 When a function is executed. Following steps are taken by the run time.
4 1. The code inside the function body is run
5 2. Once done, all list of local variables are destroyed
6 3. A value is returned.
7
8  */
1/* Visit the site and see if it is legal or not [link](address);
2 */

How to assign a named function to a variable

1 var foo = function fn() { }; // semicolon is must b/c it is an expression.
2 /* There is no need to write a function name as done above. It is superfluous here. The above expression can rightly be re written as shown below */
3 var foo = function (){};
4 >Note: The function created is an anonymous function which is referenced by the variable foo. For debugging purpose, it can be defined as shown below.
5 var foo = function foo(){}; // They are known as Named function expression NFEs

How to write an anonymous function

1 function(){}
2 /* it has to be assigned or returned for further reference*/
3 var fn = function(){ };
4 return function() { }; // probably from its enclosing function

In how many ways a function expression can be written

 1/* There are three ways a function expression can be written
 2 In second way when a name function is assigned to a variable, probably only good for function tracing call, otherwise invoking the function with its name foo does not work.
 3  */
 4// Anonymous function expression
 5var fn = function () {}
 6fn() // works
 7// Named function expression
 8var fn = function foo() {}
 9fn() //works but not foo();
10// Immediately Invoked function expression
11;(function fn() {})() // or (function fn(){}(););

What does an anonymous function return

1/* Whether it is a named or unnamed , IIFEE or not an IIFEE , all functions returns `undefined` by default.
2 */
3console.log((function () {})()) //undefined

How to write nested / inner function

 1function fn() {
 2  return function () {}
 3} // or
 4//
 5function fn() {
 6  function welcome() {
 7    return 'Welcome To'
 8  }
 9  return welcome() + ' JS'
10}
11console.log(fn()) // Welcome to JS.

How nested functions Scope Chain is established

 1/* Nested functions, no matter on what level they exist have access to their parents function / enclosing function.  */
 2var x = 100
 3function one(args) {
 4  /* This has access to global variable and to arguments passed. The functions below get to access the argument passed to this functions because of having a lexical scope
 5   */
 6  function two() {
 7    // This has access to all variable defined above;
 8    function three() {
 9      // This has access to all variable defined above;
10      function four() {
11        // This has access to all variable defined above;
12        function five() {
13          // This has access to all variable defined above;
14        }
15      }
16    }
17  }
18}

How to find out the type of function

 1/* When objects are created, they are created from their corresponding constructors. The constructor function  is a special function that represent your object acting as a class thus providing an object its identity. So the best bet is to look for its constructor property.
 2 */
 3function fn() {}
 4/* Since a function in Js is also an object, look for its constructor*/
 5console.log(
 6  fn.constructor
 7) /* [Function: Function] . It is an object of type Function which is created from the constructor function name `Function()` */
 8console.log(typeof fn) //function
 9console.log(fn instanceof Function) // true.
10// similarly
11var o = Object()
12console.log(o.constructor) //[Function: Object]
13console.log(typeof o) // object
14/* The first argument tells that it is created from a function constructor of type Object. */

How to create a function from its constructor

1/* In normal situation a function declaration is enough, but if there is a need to use a function constructor, it is done in the following way
2 */
3var fn = new Function('a', 'b', ' return a +b')
4console.log(fn(10, 20)) // 30
5console.log(fn + '') // function anonymous(a,b){return a +b}
6// The constructor signature is Function("arg1","arg2",...."body")

What is returned by the function implicitly

1function fn() {} // or function fn() { return }
2console.log(fn()) // undefined.
3/* undefined is returned implicitly in both cases */

What is the prototype of a function object

1console.log(Object.getPrototypeOf(fn)) //Function

What services are provided by the function’s prototype to be shared

1function fn() {}
2var myProto = Object.getPrototypeOf(fn)
3console.log(JSON.stringify(Object.getOwnPropertyNames(myProto)))
4/*["length","name","arguments","caller","constructor","bind","toString","call","apply"]*/

How to get all the services inherited from the prototype chain

 1/* JS does not provide any function to traverse the prototype chain. It has to be done manually. Following three built in objects when created shares code from their corresponding prototype.*/
 2
 3function fn() {}
 4var arr = []
 5var date = new Date()
 6
 7// check function's inherited properties
 8var allProp = []
 9for (var o = fn; o !== null; o = Object.getPrototypeOf(o)) {
10  for (var name of Object.getOwnPropertyNames(o)) {
11    allProp.push(name)
12  }
13  // next object in prototype chain
14  allProp.push('Next in Chain--->')
15}
16console.log(JSON.stringify(allProp))
17/* In above code o.__proto__ property can be used to replace Object.getPrototypeOf(o) method. The result will be same
18 */
19/*["length","name","arguments","caller","prototype","Next in Chain--->","length","name","arguments","caller","apply","bind","call","toString","constructor","Next in Chain--->","hasOwnProperty","constructor","toString","toLocaleString","valueOf","isPrototypeOf","propertyIsEnumerable","__defineGetter__","__lookupGetter__","__defineSetter__","__lookupSetter__","__proto__","Next in Chain--->"]
20 */

How to invoke a function

1/* Having an engine does not do anything unless it is started. Functions have to be executed/called/invoked or started. They all refer to same thing. To invoke a function you must precede it by trailing brackets*/
2function fn() {}
3fn() // it is invoked in global context
4function outer() {
5  function inner() {}
6  inner() // it is invoked by outer context
7}
8outer() // it is invoked by the global context

Does outer/enclosing function invoke an inner function

1/* Nested functions have to be executed explicitly, calling outer does not call an inner function automatically*/
2function outer() {
3  function inner() {
4    console.log('I am not executed by myself')
5  }
6}
7outer() // only outer is invoked

How to execute an inner function

 1 /* Either execute in outer context or make it IIFE */
 2 function outer(){
 3  function inner(){
 4   console.log("I am executed with the right context");
 5  }
 6  inner(); // ok. inner is available
 7 }
 8 // Or
 9 function (){
10  (function(){
11   console.log("I am IIFE");
12  }());
13 }
14 outer();

How to invoke an inner function outside its context

1/* return it from its enclosing function and assigned it to variable then invoke it using trailing brackets */
2function outer() {
3  return function () {
4    console.log('I am invoked by my beneficiary')
5  }
6}
7outer()() // direct invocation by the global context
8var beneficiary = outer()
9beneficiary() // I am invoked by my beneficiary

What is the difference b/w returning an anonymous function or named function

1/* There is technically no difference,both of them need to be invoked explicitly by the receiving variable or context */
2function outer() {
3  return function inner() {
4    console.log('I am invoked by my beneficiary')
5  }
6}
7outer()() //Or
8var beneficiary = outer()
9beneficiary()

What is the benefit of returning a function

 1/* In JS a function having been returned from its enclosing function still have access to its enclosing function's state and can be used to alter or update  it.*/
 2function party() {
 3  var guestList = ['Barbara', 'Michael', 'Louise'] // private members
 4  function showGuest() {
 5    // private function
 6    console.log('Party guests :' + guestList)
 7  }
 8  showGuest()
 9  return function (guest) {
10    if (!guest) {
11      guestList.pop()
12      showGuest()
13    } else {
14      guestList.push(guest)
15      showGuest()
16    }
17  }
18}
19var guestCounter = party() //Party guests :Barbara,Michael,Louise
20// one guest left
21guestCounter() //Party guests :Barbara,Michael
22// another entered
23guestCounter('Neil') //Party guests :Barbara,Michael,Neel
24/* The variable guestCounter is the beneficiary or the receiving function, becomes or act as a closure having an access to its parent / enclosing function state which exited long ago.*/

Are closures only implemented by nested functions

 1/* In functional programming, higher order function accept simple values along with functions and also return a function. When a function is returned it  comes out of its enclosing function but still has the access to its enclosing function state. This is known as closures. Nested functions provide the access to its outer function and when returned holds that link acting as a closure as shown in above example. But closures are not restricted to function only. An object returned from a function also acts as a closures*/
 2
 3//module pattern uses closures
 4var PartyModule = (function () {
 5  //private variable and methods
 6  var guest = ['Barbara', 'Michael', 'Louise']
 7  function showGuest() {
 8    console.log(guest)
 9  }
10  // an object returned
11  return {
12    //public members
13    guestList: function () {
14      showGuest()
15    },
16    popIn: function (newGuest) {
17      guest.push(newGuest)
18    },
19    popOut: function () {
20      guest.pop()
21    }
22  } // end of return
23})()
24//console.log(PartyModule);
25PartyModule.guestList()
26PartyModule.popOut()
27PartyModule.popOut()
28PartyModule.guestList()
29PartyModule.popIn('Ronald')
30PartyModule.guestList()
31PartyModule.popOut()

What is the execution context

1 /* Whenever a function in invoked, it is invoked by something. This something can be understood by the function execution context. Thus whatever invokes a function is said to own the code of the currently running function. It is represented by the keyword `this`*/
2 var obj = {x:1, move:functtion( return this;){}};
3 obj.move(); // A method move is invoked  and given `this` as a reference
4 var car = new MyCar(); // /* An instance of MyCar is created and given a reference `this` */
5
6 /* To see if it is the case, test the return value  */
7 console.log( obj.move() === obj ); // true
8 > function fn() { return this;}
9 > console.log(fn() == global); // true, working with node REPL console

What is this keyword refer to inside a function

 1/* When a JS programme is run, the process that runs the programme is said to execute the programme. This process may expose one or more global variables to be used in your programme. Therefore inside the function key word "this" refers to that global object. In browser the global object is `window`. In nodeJs, when working in `REPL` shell it refers to `global` variable.*/
 2function f1() {
 3  return this
 4}
 5console.log(f1() === undefined ? 'it is undefined' : f1()) // logs to global object
 6/* in Strict mode the value of this remains undefined because when the function was run, it was undefined.*/
 7function f1() {
 8  'use strict'
 9  return this
10}
11console.log(f1() === undefined ? 'it is undefined' : f1()) // logs to undefined

What is a global execution context

1/* When JS interpreter first time executes the code, it enters into a state what is known as global execution context. It can be divided into two phases:
2  1. Creation Phase, where declared variables and functions defined and arguments are stored in one place and scope chain is established ( part of this process is what is known as hoisting). Next the value of `this` is determined,if possible.
3  2. Execution Phase, where code is interpreted and executed.*/

What is the difference b/w function and a method

1/* When a function is defined inside an object, it is commonly called a method. Since a method is defined inside an object, it has to be invoked by the object. It can not  be invoked by the global execution context. When a method is invoked upon any object it is given a keyword `this` to be used inside the object or inside the method. While only function declaration in global context belongs to a global object and the keyword `this` inside that function refers to a global object */

How methods are different from functions

 1/* When a function is defined inside an object is commonly called a method. Since a method is defined inside an object, it has to be invoked by the object. It can not  be invoked by the global execution context. When a method is invoked upon any object it is given a keyword `this` to be used inside the object or inside the method. Having said that it is quite common to retrieve a function from an object as shown below, and invoking it in global context*/
 2var obj = {
 3  x: 1,
 4  getX: function () {
 5    return this.x
 6  }
 7}
 8// getting a reference to getX
 9var ref = obj.getX // note a method is not called
10ref // ?. ref is a function
11ref() // o.k . ref is function but what is returned ? undefined
12/* here is lurking a potential danger, when ref() is invoked how  is it invoked? It is invoked by global context, when run, the code inside referring to context would be wondering for the right context e.g., what is `this` would be referring to. Therefore before it is invoked it needs to be bound to the right context. When you got the access to the object method you broke the context in with it was supposed to be run. ECMAScript-5 provides `bind()` function for this purpose. */

What does it mean to have a reference to object’s method

 1/* It is quite common to retrieve a function from an object as shown below, and invoking it in global context*/
 2
 3var obj = {
 4  x: 1,
 5  getX: function () {
 6    return this.x
 7  }
 8}
 9// getting a reference to getX
10var ref = obj.getX // note a method is not called
11ref // ?. ref is a function
12ref() // o.k . ref is function but what is returned ? undefined
13
14/* here is lurking a potential danger, when ref() is invoked how,  is it invoked? It is invoked by a global context, when run, the code inside referring to context would be wondering for the right context e.g., what is `this` would be referring to. Therefore before it is invoked it needs to be bound to the right context. When you got the access to the object method you broke the context in which it was supposed to run. ECMAScript-5 provides `bind()` function for this purpose. */
15
16var boundIt = ref.bind(obj)
17boundIt() // 1. this will  give you the expected result

How an execution context be manipulated

1/* As shown in above example ECMAScript-5 provides a way to bind execution context to any function that needed it.
2 Bind() function can also copy your function to another identifier
3 */
4function fn() {
5  console.log('I am fn')
6}
7fn() // I am fn
8var f = fn.bind({})
9console.log(f())

What is the difference when invoking a function with new operator new fn()and without it fn()

 1/* fn(); invokes the function by the global context and by default it returns  undefined if nothing is returned explicitly. While the `new` operator when used returns a new object and regards this call as constructor function call.*/
 2
 3console.log(
 4  fn()
 5) /* undefined. It results in execution of the function and shows the returned value */
 6
 7console.log(new fn())
 8/* fn {}. A new object of type `function` created using `Function` constructor and returned. The returned function object  can be hold in another variable.
 9 */
10var f = new fn()
11/* "f" represent an object which is returned as a result of new operator returning the value. The type of returned object is "Object"*/

What is the Function object in JS

1/* JS provides an environment which is full of predefined objects. These objects are available anywhere in the program to be used and regarded as universal objects or global objects. They are called global objects because they are available everywhere in the programme to be used. They are different from JS language **global** variable or objects. There are more than 70 objects. Among them 12 are known as Fundamental objects. Function object is one of them which provides facility for object creation. */

What are global function properties

1/* JavaScript environment not only provides fundamental objects to be used anywhere in the programme but also provides global function. These global functions are invoked globally and not on any object. When run they return the value to the caller
2 */
3console.log(isNaN(true))

What is a functor

1
2 console.log( fn instanceof Object); // true.
3 /* instanceof operator checksif the object"*/
4 /* `fn` being an object is allowed to use `Object`s services*/
5 console.log(fn.name + "," fn.arguments "," fn.length);

4.0 Function as an object

4.1 If function is also an object of type Function, how properties can be added to it

 1/* A function in JavaScript is also a special kind of object, it gets created when a function is declared. And referenced by the function identifier or any other variable it is referenced.
 2 */
 3function add() {
 4  console.log('I am a function')
 5}
 6/* when the call comes here we already have a handle or a reference to the function object. Let's add some expando properties to it.*/
 7add.x = 10
 8add.y = 20
 9// Now two properties are added to the function.
10console.log(Object.getOwnPropertyNames(add))
11//[ 'length', 'name', 'arguments', 'caller', 'prototype', 'x', 'y' ]
12console.log(add.x) // 10
13// a function can also be added this way
14add.fn = function (a, b) {
15  return a + b
16}
17console.log(add.fn(2, 3)) // 5

4.2 Can the properties of a function object be added inside a function

 1/*
 2 Since a function object is a special kind of object, it allows you to add properties to it outside and inside the function. But when properties are declared inside the function. They are not available until the function is run explicitly or implicitly.
 3  */
 4function fn() {
 5  fn.x = 10
 6}
 7console.log(fn.x) // undefined.
 8// Invoke the function and then access
 9fn()
10console.log(fn.x) // 10
11// Similarly function can be added inside the function as a property.
12function fn() {
13  fn.x = 10
14  fn.add = function (a, b) {
15    return a + b
16  }
17}

4.3 How variables or methods attached to a function object be used? / What is the correct use of function object

 1/* The function object is not intended to be used as a replacement of object but  understanding the inner working of a function is helpful and lead to define user data type. For example if multiple instance of a particular type is required, the first step is to write the blueprint for it. In JS this blue print is written as a constructor function equivalent to class in class based oo programming. The constructor function is basically the way to start creating your own data type rather than using singleton. Constructor function are dealt in next section of object. A variable or a method attached to a function object can be used to keep track of some other object or keep track of himself.
 2 */
 3function Animal(name) {
 4  Animal.count = ++Animal.count || 1
 5  this.name = name
 6}
 7// Attaching method to function object
 8Animal.showCount = function () {
 9  console.log(Animal.count)
10}
11var dear = new Animal('beauty')
12var lion = new Animal('king')
13console.log(Animal.showCount()) //2

4.5 What is the difference between adding normal variables inside a function and adding them as a property

1/* As discussed earlier, variables and function added as a property of function object using its name do not get initialized until the function is run. Once the values are initialized they belong to function object
2 >Note: When properties are added to any object, they all act as public members of an object. To change this behaviour, these can be added to a function and from that function you can return an object which has access to them.
3  */

4.6 How to get multiple references ( pointers ) to same function

 1/* A function object can be referred to by as many pointers as you want. It acts like a value. */
 2function sayGreetings(messages) {
 3  console.log(messages + ' to everyone!')
 4}
 5var french = {},
 6  english = {},
 7  arabic = {}
 8// assign same functions to all objects
 9french.say = sayGreetings
10english.say = sayGreetings
11arabic.say = sayGreetings
12//
13french.say('Bonjor')
14english.say('Welcome')
15arabic.say('Ahlan wa Sahlan')
16
17/* The above scenario can easily be written by providing a class or F that exposes its functionality */
18function Language() {
19  this.sayGreetings = function (message) {
20    console.log(message + ' to everyone!')
21  }
22}
23var french = new Language()
24french.sayGreetings('Bonjor')
25var english = new Language()
26english.sayGreetings('Welcome')
27var arabic = new Language()
28arabic.sayGreetings('Ahlan wa Sahlan')

4.7 How to copy a pointer or reference to same function

 1 /* JS functions are first class citizen, that is they act like values. When pointed by different identifiers, any change inside the function is visible to all.
 2  */
 3 function greetings(){
 4  console.log(greetings.message);
 5 }
 6 greetings.message = "This becomes static";
 7 // Assign greetings to other variables
 8 var p1 = greetings,
 9  p2 = greetings,
10 // Invoking p1 and p2 will result in sharing the same function.
11 console.log(p1());// This becomes static
12 console.log(p2()); // This becomes static
13 // changing message
14 greetings.message = "This is also static";
15 console.log(p1());// This is also static
16 console.log(p2());// This is also static

5.0 Objects

5.1 How objects are created by constructor function in JS

 1/* JS creates all objects using either built in constructor or user defined constructor. These constructor or normal functions started with capital letter ( by convention ) to make it look different from normal functions. Inside these constructor function they make use of a key word `this` which is given to this function when it is invoked with `new` operator. */
 2
 3function House() {} // constructor function
 4var myHouse = new House() // House {}
 5/* Here Js internally creates an empty object `{}` and give it to this constructor. Now it is constructor job to do its work. Since inside this constructor `this` refers to **myHouse** you can do what ever you like to do with your instance of `House`. Note by default every function returns something and in this case your empty object is returned.
 6 If you return not an object but a function or any other value then it will not be regarded as a function constructor*/
 7function House() {
 8  counter = 0
 9  console.log('I am a house. My counter is ' + counter)
10  return function () {
11    counter++
12    console.log(' I am incremented by one ' + counter)
13    return counter
14  }
15}
16// Invoke the function
17var myHouse = House() // I am a house. My counter is 0
18// Inner function is returned, invoke it now
19myHouse() // I am incremented by one 1
20var hisHouse = new House() // I am a house. My counter is 0
21husHouse() //I am incremented by one 1
22/* The above function is not a constructor since it returned a function.*/

5.2 How to set constructor function’s prototype to null so instances created form the constructor function does not inherit code from default Object.prototype

 1 /* When a function is declared, a function object is created from its constructor function internally. Among the default properties/code it gets to share there is one property called `prototype`. This property is commonly used to add method and new properties to default prototype object.
 2 For example, if you want to add code that is shared by all the instances of the class, it has to be added to the prototype object using this property `prototype`. Note this `prototype` property only available to function object. In order to add to the object of any type, first get its prototype using`Object.getPrototypeOf(target)` and then add any property of function using dot operator.
 3  */
 4 // Adding functionality to built in Date object
 5    Date.prototype.showAlienDate = function () {console.log("☺♂↓☺☻•☻")};
 6    var d1 = new Date();
 7    d1.showAlienDate(); // it works
 8    // Adding to object
 9    var pen = {};
10   pen.writes();    //error write is neither a member of pen nor its prototype
11
12   // get the prototype of pen object and add this function to it.
13   (Object.getPrototypeOf(pen)).writes = function(){console.log("It works")}
14   //call this function on pen
15   pen.writes();    // It works
16   /* Another way to add properties or method to constructor function is to use its prototype property. This property is defined on Function object for only this purpose */
17   Object.prototype.writes = function(){console.log("it also works")}
18   pen.writes() = // it also works
19   #

5.4 How to create objects in JavaScript from built in Constructor

1/* Use built in constructor provided for built-in objects */
2var ob = {} // or
3var ob = new Object()

How to create objects with predefined properties using Object constructor

1 /* Object constructor only allows you to create objects with only one value. This value can be any value. If no value is provided or if it is `null` or undefined. The Object constructor creates an empty object and return it. Thus there exist no way to create object with properties except you have to use ECMAScript-5 definceProperties method*/
2 var ob = new Object(); // Or
3 var ob = new Object(null);// Or
4 var ob = new Object(undefined) // are all same
5#

What can be other valid values of the Object constructor

1/* The prime candidate would be the primitive data type, which are not objects e.g., number,boolean,string,...  */
2var n_ob = new Object(10) // A Number object is created
3var b_ob = new Object(true) // A Boolean object is created
4var s_ob = new Object('Hello') // A String object is created
5var obj = new Object(hello) // Error hello? is what, not a string
6/* When using console to see the object, an object wrapper is returned as shown below */
7console.log(n_ob) // [Number:10], which indicates that, it is wrapper
8consle.log({}) // {} , which indicates that it is an object not a wrapper

The Object constructor creates an object wrapper what does it mean?/ If a value is primitive data type it creates a box what does it mean

1/* As shown in above example neither the value 10,true or Hello are objects but this constructor function make them act as an object. This making of primitive data type to act as an object is regarded as creating an object wrapper around it. Or sometimes referred as creating a box for a given value.*/
2var a = 10 /*A primitive data type. No operation of object can be performed on it*/
3a.x = 100 // Error the variable a is not an object
4var ob = new Object(a) // An object wrapper is created of type number.
5/* The above is same as */
6var ob = new Number(a) // Using built in Number constructor provided
7ob.x = 100 // O.k  ob is an object wrapper

How to get the constructor of the newly created object

1/* Use `constructor` property upon any object to find its constructor */
2console.log(ob.constructor) // [Function: Object]
3/*[Function:Object] --> it is created from a function named Object Or in other words the Object constructor  type is a Function*/
4console.log(typeof ob) // funciton

How to get the print out of the constructor function

1 /* One can use the console.log function to print the constructor fucnton with the help of   */
2 console.log(ob.constructor.toString()) // function Object(){[native code]}
3 // Or simply use + ""
4 console.log(ob.constructor. + ""); /* native code indicates the language used to implement this function */

How to get only the name of the constructor

1 /*Since (ob.constructor) itself is a function, it can safely apply all services provided by its prototype.*/
2 console.log((ob.constructor).name)); // Object

How to instantiate only one object of a class from the constructor function

 1/* When a new object is instantiated through its constructor, the logic can be used in the constructor to make sure if it already exist or not. If it does exist it should not create another instance at all. But it creates an infinite loop and needs to be handled properly as shown below.*/
 2
 3var singleton = (function Anyobject() {
 4  var instance
 5  function createInstance() {
 6    var object = new Anyobject()
 7  }
 8  return {
 9    getInstance: function () {
10      if (!instance) {
11        instance = createInstance()
12        return instance
13      }
14    } // function ends here
15  } // end of return
16})()
17
18var object1 = singleton.getInstance()
19var object2 = singleton.getInstance()
20
21if (object1 === object2) {
22  console.log('They are same instance')
23}

How Object are protected

1/* JavaScript now provides three different levels of Protection directly to the object by;
2 1.) Making Object non extensible: So new properties can not be added
3 2.) Making Object sealed: So properties can not be reset or deleted
4 3.) Making Object frozen: So that it can be be made read only as well.
5  */

How to prevent extension to the objects? { First level of security }

1/* Once object is prevented by applying `preventExtension()` method it can be undone. In other words once locked for extension can not be unlocked for extension. Note preventing extension of the object does not provide any other security.
2 */
3var o = { x: 10 }
4Object.preventExtension(o)
5o.y = 20 //fails silently, but x can be reset or  deleted

How to make the object non configurable? { Second level of protection }

 1/* 
 2 When an object is non configurable its properties can not be reset or deleted. JS provides a `seal()` method to make object non configurable. 
 3 >Note: Non Configurable means that whatever the configuration it is created with can not be changed later on. If at the time of configuration its enumerable attribute was set to false it can no longer be reset.
 4 When an object is non configurable, it automatically becomes non extensible. Therefore when level 2 security is applied level one is automatically applied.
 5  */
 6var o = { x: 10 }
 7Object.seal(o)
 8o.x = 30 // o.k, b/c  by default its writable attribute is set to true.
 9o.y = 10 // not possible because it is also non extensible
10console.log(o) // { x: 30}

How to make object frozen { highest level of protection }

 1/* Once an object is frozen, it gets the highest level of protection. All existing properties becomes readable only.
 2 */
 3var o = { x: 20, y: 30 }
 4Object.freeze(o)
 5console.log(Object.isFrozen(o)) //true
 6// All below commands fails silently
 7o.x = 100 // can not be reset
 8delete o.y // can not be deleted
 9o.z = 200 // new properties can not be added
10console.log(o) // {x:20, y:30}

What are static function defined on Object

1/* In class based OOP languages static methods are defined to be used only with the class name and not with the instances of the class.Similarly in JS static method is used with the object constructor instead of a class name, since an object constructor acts like a class name. Following are static methods of Object which are used very often;
2 */
3var arrayProp = Object.getOwnPropertyNames(Object)
4var fun = arrayProp.filter(function (element) {
5  return typeof Object[element] === 'function'
6})
7console.log(JSON.stringify(fun))
8/* ["assign","create","freeze","getOwnPropertyDescriptor","getOwnPropertyNames","getOwnPropertySymbols","is","isExtensible","isFrozen","isSealed","keys","preventExtensions","seal","defineProperty","defineProperties","getPrototypeOf","setPrototypeOf"]
9 */

What is a default prototype object

1 /* JS has many standard built in objects. All of these objects descend from the one object known as `Object`. Thus giving them an identity of being objects. All these objects have their corresponding prototype e.g., an Array object would have its prototype set to `Array.prototype` which is regarded as its default prototype. Similarly this default prototype also has its prototype until reaches to `Object.prototype` which itself has no prototype thus set to `null`.
2 In other words object created from literal or Object constructor has default prototype of `Object.prototype`
3  */
4 var obj = {}; var arr = [];
5 console.log(Object.getPrototypeOf(obj) == Object.prototype) // true
6 console.log(Object.getPrototypeOf(arr) == Array.prototype) // true
7#

How to change the default prototype of any object

 1 /* JS provides two ways to change the default prototype . One is an old style using inherited property known as `__proto__`, the other is a new static function defined on Object known as `Object.setPrototype(object,"prototype")` as shown below.
 2  */
 3 function Form(){
 4  // Constructor function
 5 }
 6 //Add properties to Form prototype so that it can be shared among all
 7 Form.prototype.hasBoundries = true;
 8 var obj = {};
 9 obj.__proto__ = Form.prototype;
10 console.log(obj.hasBoundries); // true
11 // Another way of creating object with it prototype set to non default
12 var obj = {
13  __proto__ = // Set to anything you want
14 };
15 // Using ECMAScript-5 function
16 var p = { x : 10 };
17 var obj = {};
18 Object.setPrototypeOf(obj,p);
19 console.log(obj.x); // 10;

5.0 Adding Properties to objects

In How many ways properties can be added to JS objects

1/* Properties can be added to object, either using expando properties by extending the object or by using method provided by ECMAScript-5 `defineProperty()` for only one property, if more than one property needs to be added use `defineProperties()`
2 */
3var obj = {}
4Object.defineProperty(obj, 'x', {
5  /* define its attributes here*/
6})

When a property is defined what are the default attributes value set to

 1 /* It depends upon the environment where a property is declared and how it is declared as shown below:
 2 WORKING IN REPELL: when a variable is declared*/
 3  var x = 10;
 4     console.log(Object.getOwnPropertyDeiscriptor(global,"x"));
 5    { value: 10, writable: true, // can be updated
 6        enumerable: true, // can be enumerated when needed
 7        configurable: false // the above behaviour can not be changed
 8     }
 9     // When object is declared with a property.
10     var o = { z : 10};
11  console.log(Object.getOwnPropertyDescriptor(o,"z"));
12  { value: 10,writable: true,enumerable: true,configurable: true }

What are the default attributes value when declaring with Object.defineProperty() method

1/* The rule of thumb is that the attributes which are not set gets the default value set to false.If only value is set and the rest are not touched,all the other attributes are set to false. Thus the property  can not be changed, enumerated or reconfigured. In order to be changed their behaviour configurable must be set to true.
2 */
3var obj = {}
4Object.defineProperty(obj, 'x', { value: 200 })
5console.log(Object.getOwnPropertyDescriptor(obj, 'x'))
6//{ value: 200,writable: false,enumerable: false,configurable: false }

What is an instance indexer

1/* It is a name given, when accessing object's property using `[]`. This method is useful when the  property name is not known and calculated at run time. */
2var obj = { fName: 'Abdul', lName: 'Sayyed', book_1: 'ABC', book_2: 'DEF' }
3var prop = 'book_' + getPropertyValue() // either 1 or 2
4console.log(obj[prop]) // this[propertyName:String]:Object

6.0 Array

What does it mean to say JavaScript has an Array Class

1/* Array class terminology is used for referring to Constructor Function Array() by the programmer who comes from class based Object Oriented Language. Therefore all built in constructor whether Array , Object , Date , RegExp etc may be regarded as having their own class */

7.0 Date

How to create a Date object with formatting

 1var todayDate = function () {
 2  return new Date().toLocaleDateString('en-UK', {
 3    weekday: 'long',
 4    year: 'numeric',
 5    month: 'short',
 6    day: 'numeric',
 7    hour: '2-digit',
 8    minute: '2-digit'
 9  })
10}
11console.log(todayDate()) // Tuesday, Jan 10, 2017, 6:15 PM

Loops in JS

What is the difference b/w for…in and for…of loop

 1/* for...in iterates over a property names while for...of iterates over property values.
 2 */
 3var arr = ['one', 'two', 'three']
 4for (var i in arr) {
 5  console.log(i) // 0,1,2
 6}
 7
 8for (var i of arr) {
 9  console.log(i) // "one","two","three";
10}

Iterating objects in JS

If you run git status and it shows no change what does it mean

1 It simply means that there are no changes in three trees, namely `HEAD,Index and Working Directory`