ReactJS: A guide to the Gotchas

Guess what I am a human being and I React exactly the same way you think. So obvious question winking here is

What is React?

  • Is it a framework?
  • How is this compare to Angular, Ember, Backbone, Dojo etc etc?
  • How do you make server calls?
  • From where is this Alien JSX comes from?
  • What is a component?

Please STOP STOP STOP.
Stop bugging yourself with thousand of questions.
A simple answer to all your questions is: React is ONLY the VIEW

React gives you a template language and some javascript function hooks that will help you to render your HTML and your bundle of HTML + javascript is known as component which is again a reusable piece of code which can store their own states and in the end they will out put as HTML.

Now I hope I make you clear and this time I won’t expect you to compare “React Vs Angular”, this doesn’t make sense at all.

I am pretty sure that you heard the concept of Virtual DOM Concept when you talked about React.

Are you excited? Let’s dig in.

Virtual DOM Concept

When your model object gets changed you need to render your DOM according to that. So there is two important things comes here:

  1. When your model object has changed
  2. And where to render that change / update the DOM

Unlike others React doesn’t use the concept of dirty checking instead it follows a smart way of updating a DOM element which is the Observer Model(i.e it doesn’t have to calculate what is changed, it knows immediately and update the element).

One important question here is: How it is managing the DOM Manipulation?
React create a tree like structure of DOM which you called as Virtual DOM and calculate which DOM element has to be updated. DOM manipulation is always a heavy things to do and React tries as much DOM element untouched as possible. So if a parent node got updated then whole child nodes has to be updated ( they have various method which can handle this deficiency: shouldComponentUpdate() ) but it won’t affect your parent node when your child got updated.

JSX

JSX is not a template language like Handlebar. It is somehow confusing and you might end up thinking in N number of ways but it is just another ways of writing HTML in javascript. Below is an example:

React.render(
    React.createElement('div', {}, 'Hello, React!'), 
    document.body
);

Of course, React.createElement itself is somewhat mystical, so let’s try to clear that up a bit. When you use React, you usually don’t deal with DOM elements directly. Instead, you create elements for a virtual DOM. These elements are really nothing but JSON objects. They represent the underlying DOM structure but don’t carry any of the weight of actual DOM elements. React converts these virtual elements into real DOM elements as necessary. React.createElement is just a method used to create these JSON objects. The signature is:

React.createElement(elementNameOrClass, props, children...)

Components

When designing interfaces, break down the common design elements (buttons, form fields, layout components, etc.) into reusable components with well-defined interfaces. That way, the next time you need to build some UI, you can write much less code. This means faster development time, fewer bugs, and fewer bytes down the wire.

Now go build something using React!!!

Happy Reading,
Kshirodra

Installing PHPUnit in XAMPP

 * First of all Installation of new PEAR Version needed for PHPUnit.
 * To install PEAR you need to download go-pear.php (http://pear.php.net/go-pear.phar) and save it to C:\xampp\php
Then follow the steps below :-
1. Open command prompt and go to C:\xampp\php
2. Type “php go-pear.phar” (To installs new PEAR)
3. Type “pear update-channels” (Updates channel)
4. Type “pear upgrade –alldeps” (It will upgrades all existing packages and pear)
5. Type “pear channel-discover components.ez.no” (This is needed for PHPUnit)
6. Type “pear channel-discover pear.symfony-project.com” (This is also needed for PHPUnit)
7. Type “pear channel-discover pear.phpunit.de” (This IS phpunit)
8. Type “pear install –alldeps phpunit/PHPUnit” (It will installs PHPUnit and all dependencies)
Reference :
I hope this will help you out during installation of PHPUnit. 🙂
Happy Reading,

JavaScript Inheritance Using Prototype

In others programming languages like c++, java etc has class concept and class inherits from another class. But javaScript doesn’t have a concept called class. So inheritance in javaScript is prototype-based.

JavaScript function contains a prototype property which is actually an object. During function invocation an object created which has a secrete link to the prototype object. This link is called __proto__ which allows the newly created object to use the methods and properties of prototype object.

This prototype object is just a normal object and therefore it also contain a link to prototype and so a chain is created and it’s called prototype chain.

Prototype-chaining is the default way to implement inheritance.

Lets define three function

function One(){
    this.name = 'one';
    this.propertiesOfOne = 'properties one';
    this.toString = function() {return this.name;};
}

function Two(){
    this.name = 'two';
    this.propertiesOfTwo = 'properties two';
}

function Three() {
    this.name = 'three';
    this.propertiesOfThree = 'properties three';
    this.getName = function(){return 'Function name is : ' + this.name; };
}

Now lets do inheritance using prototype:

Two.prototype = new One();
Three.prototype = new Two();

Here we are overwriting the function Two() prototype with One() and Three() prototype with Two(). You need to create an instance using the new One() constructor and after that you can inherit its properties; you don’t inherit from One() directly. Additionally, after inheriting, you can modify One(), overwrite it or even delete it, and this will have no effect on Two, because all you needed was one instance to inherit from.

When you are overwriting the prototype this has some -ve impact on constructor property. Therefore, it’s a good idea to reset the constructorafter inheriting.

Two.prototype.constructor = Two;
Three.prototype.constructor = Three;

var objThree = new Three();
objThree.getName(); // output: "Function name is : three"

Although objThree doesn’t have it’s own toString() method but it can still access this method as inheritance is done.

objThree.toString(); // output: "three"
objThree instanceof One; // output: true
objThree instanceof Two; // output: true
objThree instanceof Three; // output: true
objThree instanceof Array; // output: false

The same happen when we check isPropertyOf():

One.prototype.isPrototypeOf(objThree); //output: true
Two.prototype.isPrototypeOf(objThree); //output: true
Three.prototype.isPrototypeOf(objThree); //output: true
String.prototype.isPrototypeOf(objThree); //output: false

Now get the properties

objThree.propertiesOfOne; //output: "properties one"
objThree.propertiesOfTwo; //output: "properties two"
objThree.propertiesOfThree; //output: "properties three"

You can also play with hasOwnProperty() to see the difference between the own property versus a property coming down the prototype chain.

objThree.hasOwnProperty('name'); //output: true
objThree.hasOwnProperty('propertiesOfOne'); //output: false
objThree.hasOwnProperty('propertiesOfTwo'); //output: false
objThree.hasOwnProperty('propertiesOfThree'); //output: true

Hope this helps you 🙂

Happy Reading,
Kshirodra

Prototype in JavaScript

JavaScript is classified as prototype-based programming language.
Here we will look into

  1. Every function has a prototype property and it contains an object
  2. Adding properties to the prototype object
  3. Using the properties added to the prototype
  4. The difference between own properties and properties of the prototype
  5. Methods such as isPrototypeOf(), hasOwnProperty(), and propertyIsEnumerable()

Prototype Properties

Prototype is a properties of javaScript function.

function FunName(a, b) {
    return a*b;
}

FunName.length; //output: 2
FunName.constructor; //output: Function()
FunName.prototype; //output: FunName {}
typeof FunName.prototype; //output: "object"

//You can empty the prototype properties it wont have any impact on function FunName.
FunName.prototype = {}

Adding Method And Properties to Prototype

Let’s create a function which uses this add method and properties.

function FunName() {
    this.name = 'Kshirodra Meher',
    this.age = 25,
    this.sayHello = function() {
	return 'Hi ' + this.name;
    }
}
var obj = new FunName();
obj.name; //output: "Kshirodra Meher"
obj.sayHello(); //output: "Hi Kshirodra Meher"

Let’s add method and properties this existing function using prototype properties.

FunName.prototype.city = 'Bhubaneswar';
FunName.prototype.state = 'Odisha';
FunName.prototype.getInfo = function() {
  return 'I am from ' + this.city;
};

var obj = new FunName();
obj.name; //output: "Kshirodra Meher"
obj.sayHello(); //output: "Hi Kshirodra Meher"
obj.city; //output: "Bhubaneswar"
obj.getInfo(); //output: "I am from Bhubaneswar"

Another way of assigning methods and properties is overwriting prototype properties.

FunName.prototype = {
    city: 'Bhubaneswar',
    state: 'Odisha',
    getInfo: function() {
        return 'I am from ' + this.city;
    }
}

var obj = new FunName();
obj.name; //output: "Kshirodra Meher"
obj.sayHello(); //output: "Hi Kshirodra Meher"
obj.city; //output: "Bhubaneswar"
obj.getInfo(); //output: "I am from Bhubaneswar"

Own Properties Vs prototype Properties

Let’s take the above example.

var newObj = new FunName();

if you try to access newObj.name then javaScript engine will search for all the properties and if it find name then it will return the value.

newObj.name; //output: "Kshirodra Meher"

But if it is not(let say city) there on the properties then javaScript engine will search in prototype properties.

newObj.city; //output: "Bhubaneswar"

Overwriting Prototype’s Property with Own Property

As we have discuss if a properties doesn’t exist then javaScript engine search that properties in prototype chain, but what if the properties name is exist with in it’s own property as well as prototype properties, in this case own property takes precedence over the prototype’s.

function SayHello(name) {
  this.name = name;
}
SayHello.prototype.name = 'Kshirodra Meher';

var obj = new SayHello('John');
obj.name; //output: "John"

delete obj.name;
obj.name; //output: "Kshirodra Meher"

Enumerating Properties

If you want to list all properties of an object, you can use a for-in loops of an array

var a = [1, 2, 3];
for (var i in a) {
  console.log(a[i]);
}
//Arrays are objects, so you can expect that the for-in loop works for objects too:
var o = {a1: 1, a2: 2};
for (var i in o) {
  console.log(i + '=' + o[i]);
}
//This produces:
a1=1
a2=2
  1. Not all properties show up in a for-in loop. For example, the length (for arrays) and constructor properties will not show up. The properties that do show up are called enumerable. You can check which objects are enumerable with propertyIsEnumerable()
  2. Prototypes that come through the prototype chain will also show up, provided they are enumerable. You can check if a property is an own property versus prototype’s using the hasOwnProperty() method.
  3. propertyIsEnumerable() will return false for all of the prototype’s properties, even those that are enumerable and will show up in the for-in loop.
function User(name) {
  this.name = name;
  this.sayHello = function(){return 'hello ' . this.name;}
}
User.prototype.city = 'Bhubaneswar';
User.prototype.state = 'Odisha';

var obj = new User('Kshirodra');

for (var prop in obj) {
  console.log(prop + ' = ' + obj[prop]);
}

OUTPUT:
name = Kshirodra
sayHello = function (){return 'hello ' . this.name;}
city = Bhubaneswar
state = Odisha

obj.hasOwnProperty('name'); //output: true
obj.hasOwnProperty('city'); //output: false
obj.propertyIsEnumerable('name'); //output: true
obj.propertyIsEnumerable('city'); //output: false

Note, however, that such properties are enumerable if you reach the object contained
in the prototype and invoke its propertyIsEnumerable().

obj.constructor.prototype.propertyIsEnumerable('city'); //output: true

isPrototypeOf()

Every object also gets the isPrototypeOf() method. This method tells you whether that specific object is used as a prototype of another object.

Let’s take a simple object address.

var address = {  
  city: 'Bhubaneswar',  
  state: 'Odisha',  
  country: 'India'
};

//Now let's create a User() constructor function and set its prototype property to point to address.
function User(name) {  
  this.name = name;
} 
User.prototype = address;

var obj = new User('Kshirodra');
address.isPrototypeOf(obj); //output: true

Hope this helps you 🙂

Happy Reading,
Kshirodra

JavaScript Object and Usage

Here we will look into

  1. How to create and use objects
  2. What are the constructor functions
  3. What types of built-in JavaScript objects exist and what they can do for you

Array to Object

Array is just a list of values. Each value has an index (a numeric key) starting from zero and increment by one for each value.

var arr = ['computer', 'laptop', 'mobile', 'ipod'];
arr; //output: ['computer', 'laptop', 'mobile', 'ipod']
arr[0]; //output: "computer"
arr[3]; //output: "ipod"

An object is very similar to array but here you can define your own keys.

var myObj = {
	name: 'Kshirodra Meher',
  	age: '25',
  	gender: 'Male'
};

Elements, Properties, Methods

When we talk about array then we says they contains elements, when talking about object then we say they contain properties. But there is no difference these are all naming conventions people are following. JavaScript object can contain function as functions are data in JavaScript. These are called method.

var myObj = {
    name: 'Kshirodra Meher',
    age: '25',
    gender: 'Male',
    sayHello: function() {
        console.log('Hello Kshirodra');
    }
};
myObj.sayHello(); //output: "Hello Kshirodra"

Indexed or Enumerated, Hashes or Associative Arrays

  1. A normal array, also called indexed or enumerated (the keys are numbers)
  2. An associative array, also called a hash (the keys are strings)

Accessing Object’s Properties

There are two ways to accessing object’s properties

  1. Using square bracket notation, for example myObj['name']
  2. Using the dot notation, for example myObj.age
myObj['name']; //output: "Kshirodra Meher"
myObj.age; //output: "25"
myObj.address; //output: "undefined"

Accessing a non-existing property returns undefined

Using this value

this refers to the current object

var myObj = {
    name: 'Kshirodra Meher',
    age: '25',
    gender: 'Male',
    sayHello: function() {
        console.log('Hello ' + this.name);
    }
};
myObj.sayHello(); //output: "Hello Kshirodra Meher"

Constructor Functions

You can create a object of constructor function using new operator

function MyFun() {
    this.name = 'Kshirodra';
}
var myObj = new MyFun();
myObj.name; //output: "Kshirodra"

Benefits of using constructor function is they can accept parameters which can be used during the object creation.

function MyFun(name) {
    this.name = name;
    this.age = 25;
    this.sayHello = function() {
        return 'Hello ' + this.name + ', you are ' + this.age;
    }
}

var myObj1 = new MyFun('Kshirodra');
myObj1.sayHello(); //output: "Hello Kshirodra, you are 25"

var myObj2 = new MyFun('Ram');
myObj2.sayHello(); //output: "Hello Ram, you are 25"

When you will call that function without new, then it will behave as normal function.

var myObj3 = MyFun('Shyam');
typeof(myObj3); //output: "undefined"

The Global Object

JavaScript always runs on a host environment like browser. For browser global object is window that means all the global variable are properties of that global object.

//declare a glabal variable
var myVar = 1;

//access that global variable
myVar; //output: 1
window.myVar; //output: 1
window['myVar']; //output: 1

Note:If you are calling a constructor function without new operator then this refers to the global object.

function MyName(name) {this.name = name;}
var h = MyName('Kshirodra');
window.name; //output: "Kshirodra"

Because this inside MyName, a global variable (a property of the global object) called name was created.

Constructor Property

When an object is created, a special property is assigned to it behind the scenes—the constructor property.

function MyName(name) {this.name = name;}
var h = new MyName('Kshirodra');
h.constructor; //output: MyName(name)

You can also call a constructor function using following syntax:

function MyName(name) {
    this.name = name;
}
var h = new MyName('Ram');
var h1 = new h.constructor('Kshirodra');
h1.name; //output: "Kshirodra"

InstanceOf Operator

instanceof is used to test if an object was created with a specific constructor function.

function MyFun(){}
var h = new MyFun();
var h1 = {};
h instanceof MyFun; //output: true
h1 instanceof MyFun; //output: false

Built-in Objects

We have came across the Object() constructor function. It is returned when we create objects with the object literal notation and access their properties.

  1. Data wrapper objectsObject, Array, Function, Boolean, Number, and String.These objects correspond to the different data types in JavaScript. Basically, there is a data wrapper object for each different value returned by typeof with the exception of undefined and null.
  2. Utility objects — These are Math, Date, RegExp
  3. Error objects — The generic Error object as well as other, more specific objects that can help your program recover its working state when something unexpected happens.

Hope this help you. 🙂

Happy Reading,
Kshirodra

What Are JavaScript Closures?

General View

Before going into the details let me quickly run through function scope.
As you know earlier variables in javaScript have function scope not block scope(find details:here)

var outer = 1; 
function funName(){
    var inner = 1; 
    return outer;
}

funName(); //output: 1
inner; //output: inner is not defined

Note: Inside funName(), both inner and outer are visible where as outside funName(), outer is visible, but inner is not.

Scope Chain

If function innerFunc() is nested inside outerFunc(), then innerFunc() has the access to it’s own variables/properties as well as it’s parents. This is called Scope Chain.

var outerVariable = 1;
function outerFunc(){
    var innerVariable1 = 2;
    return inner = function innerFunc() {
        var innerVariable2 = 3;
        return outerVariable + innerVariable1 + innerVariable2;
    }
}

outerFunc(); //output: innerFunc()
inner(); //output: 6

Lexical Scope

In javaScript function create their scope when they are defined, not when they are execute. This is called Lexical Scope.

function outerFunc(){
    var outer = 1;
    return innerFunc();
}

function innerFunc(){
    return outer;
}

outerFunc(); //output: outer is not defined

One might think as innerFunction() is inside outerFunc(), so it should have access to all the variables of it’s parent function outerFunc(), but outerFunc() is a parent function during execution not during the function define. That’s why we are getting undefined for outer.
JavaScript also gives the flexibility to add/update/remove a variable from it’s function scope and function will return you the updated value.

function outerFunc(){
    var outer = 1;
    return innerFunc();
}

function innerFunc(){
    return outer;
}

outerFunc(); //output: outer is not defined

var outer = 10;
outerFunc(); //output: 10

outer = 20;
outerFunc(); //output: 20

delete outer; //output: true
outerFunc(); //output: outer is not defined

Break The Scope With Closures

Now we will move to closures, lets think of a global space/scope where all the functions and variables are present.
This will give you a picture like:
Function and Scope
If you are at:

  1. a then you have access to global space as it is inside global space.
  2. b which is inside F, then you have access to F-space and global space.
  3. c which is inside N, then you have access to N-space, F-space and global space.

But you can’t reach a to b, as b is inside F-space.
Still, if you want you can get c to b or from N to b. The interesting thing closure happens when somehow N breaks out of F and ends up in the global space.

Let’s see how N break the chain.

Closure #1

function funcName(){
    var outer = "outer";
    return function(){
        return outer;
    }
}

outer; //output: outer is not defined

Here the return value of funcName() is another function, think this as function N(see photo), now this function has access to funcName()-space and global space. So it can see b, because funcName() is callable from the global space(it’s a global function), you can call it and assign the returned value to another global variable.
Assign this funcName() to another variable and you are DONE!

var newFunc = funcName();
newFunc(); //output: "outer";

Closure #2

The final result will be same, but we will achieve the result with some other way.
funcName() doesn’t return a function, but instead it creates a new global function newFunc() inside its body.

var newFunc;
function funcName(){
    var outer = "outer";
    newFunc = function(){
        return outer;
    }
}

funcName(); //output: undefined

Now invoke funcName(), as the var statement is missing inside funcName() so it has a global scope. So it will now have access to both global and funcName() space.

newFunc(); //output: "outer";

Closure #3

When you pass an argument to a function it becomes available as a local variable. You can create a function that returns another function, which in turn returns its parent’s argument.

function funcName(arg) {
    var newFunc = function(){
        return arg;
    };
    arg++;
    return newFunc;
}

var f = funcName(10);
f(); //output: 11

arg++ was incremented after the function was defined but still when it is called, giving you the updated value. This is how closures work in javaScript.

Hope this help you. 🙂

Happy Reading,
Kshirodra

JavaScript Functions and Scope

Functions and general purpose

Function is a programming module which contain few lines of executable code (called function body), can take few input data(called parameters) and process them and can return some data as a result. Once it has been written can be used many times outside and inside(if you are using recursion) of that function.

As javaScript is a object-based programming language, so there is no such concept of class. Functions are treated as the class-object in javaScript and can be manipulated and passed as an object. So in other words you can say function have similar behavior like data in another languages.

Functions are not procedure, procedure always return a value where as function may or may not return a value. To return a value we need to write the return statement else in javaScript it will return undefined by default where as for constructor call it will return the value of this.

We will cover:

  • Define and use a function
  • Passing parameters to a function
  • Pre-defined functions in javaScript
  • Scope of variables in JavaScript
  • Concept that functions are special type of data in javaScript
//declare a function
function sum(a, b) {
    var c = a + b;
}

Here

  1. Function name is : sum
  2. Function parameters are : a, b (function may have zero or more then one parameters separated by comma)
  3. Function is returning : c (if return statement is not there then it will return undefined by default. Function always return single value, if you want to return more then one value then make an array and return it)

Function Call

To use a function you need to call/invoke a function using function name preceding by parenthesis.

 sum(1,2); //output: 3 

If you need you can assign this to a variable and can use it.

Parameters

During function declaration you can specify the parameters.

 sum(2); //output: NAN 

Note: When function have parameters and you forgot to pass any parameter/s value then javaScript automatically assign undefined to those parameter/s.
As you have passed only one parameter. So

a = 2; b = 'undefined'; And sum is: a + b = 2 + 'undefined' = NAN

If you passed some extra parameters then javaScript simply ignore them without giving any error.

sum(3, 6, 2, 1); //output: 9

You can also create function which is independent of input parameters. That can be possible using ‘arguments’ array that are present by default inside a function.

function independentArgs() {
    return arguments;
}
independentArgs(); //output: [] (blank array)
independentArgs( 1, 2, 3, true, 'name'); //output: [1, 2, 3, true, 'name']

So now the sum function can be modified as:

function independentArgSum() {
    var i, res = 0;
    var number_of_params = arguments.length;
    for (i = 0; i < number_of_params; i++) {
        res += arguments[i];
    }
    return res;
}
independentArgSum(); //output: 0
independentArgSum(2); //output: 2
independentArgSum(2, 3); //output: 5
independentArgSum(1, 2, 3); //output: 6

Note: arguments.length will return number of argument passed and arguments is an array-like object.

Pre-Defined Functions in JavaScript

Below are few inbuild functions in javaScript

  • parseInt()
  • parseFloat()
  • isNaN()
  • isFinite()
  • encodeURI()
  • decodeURI()
  • encodeURIComponent()
  • decodeURIComponent()
  • eval()

parseInt()

Convert string to integer

parseInt('1'); //output: 1
parseInt('ac1') //output: NaN
parseInt('1ac2') //output: 1
parseInt('12abc') //output: 12

parseFloat()

parseFloat() is same as parseInt()

parseFloat('13.1') //output: 13.1
parseFloat('1.23abc.00') //output: 1.23
parseFloat('a.bc1.23') //NaN

isNaN()

This function is use to check if a input is a valid number or not.

isNaN(NaN); //output: true
isNaN(123); //output: false
isNaN(1.23); //output: false
isNaN(parseInt('abc123')); //output: true
isNaN('1.23'); //output: false
isNaN('a1.23'); //output: true

Note: NaN === NaN is False

isFinite()

isFinite() is used to confirm a input value is a valid(not NaN) finite number(not Infinite).

isFinite(Infinity); //output: false
isFinite(-Infinity); //output: false
isFinite(12); //output: true
isFinite(1e308); //output: true
isFinite(1e309); //output: false

Note: In javaScript any number greater then 1.7976931348623157e+308(biggest number in javaScript) is infinite.

encodeURI()

The encodeURI() function is used to encode a URI. This will replaces the spaces and special characted with their sucequent UTF-8 enncoding characters.

var uri = 'my test message/?id=10';
encodeURI(uri); //output: my%20test%20message/?id=10

Note: encodeURI() will encode all the special characters except : , / ? : @ & = + $ #

decodeURI()

This function will decode the encoded URI.

decodeURI('my%20test%20message/?id=10'); //output: my test message/?id=10

encodeURIComponent()

This will encode all the special characters including , / ? : @ & = + $ #

encodeURIComponent('my test message/?id=10'); //output: my%20test%20message%2F%3Fid%3D10

decodeURIComponent()

This will decode all the characters which are encoded with encodeURIComponent().

decodeURIComponent('my%20test%20message%2F%3Fid%3D10');// output: my test message/?id=10

eval()

eval() takes a string as input and execute it as javaScript code.

eval("alert('hi')");// output: alert 'hi'
eval("var i= 10; var j = 20; sum = i+j;");// output: 30

Note: Sometimes it OK to use but, “Eval is Evil” it’s a mantra and there are security and performance concern with this. So try to avoid this.

Variables Scope

Variables in javaScripts are defined in a function scope not in block scope(like others languages). It means variable defined inside a function is not visible outside of that function. However, a variable defined inside an if or a for code block is visible outside the code block. Hence variable declared inside function is called local variable, where as variable declare out of the function is taken as global variable. The code inside a function has access to all global variables as well as to its own local variables.

var globalVariable = 1;
function name() {
    var localVariable = 2;
    globalVariable++;
    return globalVariable;
}

name(); //output: 2
name(); name(); //output: 3
localVariable; //output: localVariable is not defined

Note: When you are not using var to declare a variable then it will automatically goes into global scope / global variable.

var globalVariable = 1;
function name() {
    localVariable = 2;
    return globalVariable;
}

localVariable; //output: localVariable is not defined
name(); //output: 1
localVariable; //output: 2

Note: For the 1st time as localVariable is inside a function so it is not visible to outside, but after calling the function name() localVariable is created with a global scope as because var declaration is not there.

Functions are Data in JavaScript

Functions are special kind of data in javaScript. That means you can declare a function using as

function functionName(){return 1;}
functionName();//output: 1

var functionName = function(){return 1;}
functionName();//output: 1

You can also check a function with typeof operator

typeof(functionName);//output: function

You can also assign a function to another variable.

var anotherFunc = functionName;
anotherFunc();//output: 1

You can delete

delete functionName;//output: true
functionName();//output: functionName is not defined

Anonymous Functions

Anonymous functions are the function which doesnt have a name and in javaScript it wont throw you any error.

function(a){
    return a;
}

Note: You can pass anonymous function as a parameter to another function, or else you can execute that function right away to achive something. We will look into that.

Callback Functions

As functions are data in javaScript you can pass functions as argument.

function add(a, b){
    return a() + b();
}

function A() {
    return 1;
}

function B() {
    return 2;
}

add(A, B);//output: 3

Passing A() and B() as annonymous function.

add(function(){return 1;}, function(){return 2;}); //output: 3

Note: When function pass as an argument to another function and code gets executed then 1st function is called ‘callback function’. When 1st function doesn’t have a name then it is called ‘anonymous callback function’.

Self-invoking Functions

Function calls itself right away is called self invoking function.

(function(){
    return 'foo';
})(); //output: foo

(function(a, b){
    return a+b;
})(3, 4);//output: 7

Inner/Private Functions

Like anyother variables you can define a function inside another function.

function outer(param) {
    function inner(input) {
        return input * 2;
    };
    return inner(param);
};

outer(2);//output: 4
inner(2);//output: inner is not defined

Functions Return Functions

In javaScript you can return a function just like data/variables.

function outer() {
    console.log('outer');
    return function(){
        console.log('inner');
    };
}

outer();// output: outer and function()
outer()();//output: outer and inner

var f = outer();//output: outer
f();//output: inner

Function Rewrite Thyself

Function can be rewrite if you assign that to a variable with same name.

outer = outer();//output: outer and function()
outer();//output: inner

Hope this help you. Happy reading 🙂