Both of the following snippets print "arrow". I would like to know why. Do arrow functions have a sort of higher priority than the normal functions if they both have the same name?
function increment(){
alert("normal")
}
var increment = () => {
alert("arrow")
}
increment(); //prints arrow
var increment = () => {
alert("arrow")
}
function increment(){
alert("normal")
}
increment(); //prints arrow
This has nothing to do with arrow functions. Rather, regular functions (and var declarations) are hoisted; regardless of where you write them, they are moved to the top of their scope. Effectively, both code samples are completely identical, and they look like this:
var increment; // hoisted
function increment() { // hoisted
alert("normal")
}
increment = () => { // the assignment itself is unaffected
alert("arrow")
}
increment(); //prints arrow
The assignment portion of var increment = ... occur after the hoisted function and var declaration, in both cases. Regardless of where you actually wrote the function increment() { } declaration, it is hoisted above the line performing assignment to the increment variable.
This is why the following code still works, despite the function apparently being defined after it is used:
increment(); //prints normal
function increment(){
console.log("normal")
}
If you want to compare like with like, you need to compare var increment = () => { ... } with var increment = function () { ... }, that is, two assignments. The results look like this:
var increment = () => { console.log('arrow'); }
var increment = function () { console.log('normal'); }
increment(); # normal
vs
var increment = function () { console.log('normal'); }
var increment = () => { console.log('arrow'); }
increment(); # arrow
In both cases there is a single hoisted var increment; declaration, and then the assignments occur in the order in which they're written, meaning the last assignment wins.
As an aside, this is one of the chief reasons to prefer let x = () => { } over "old" style function declarations. let is not hoisted, so the function exists from the point in time you would naturally expect it to, instead of jumping to the top of your scope.
Related
I want to understand the way anonymous self invoking function is able to maintain the last updated state of variable but why is it not possible in case of normal anonymous functions .Both functions are closures
still are behaving differently while maintaining the previous state of variable.
ex:
var selfInvokingfunc= (function () {
var a=2;
var myprivatefunction = function () {
a=a+2;
console.log(a);
}
return {
mypublicfunction : function () {
myprivatefunction();
}
}
})();
selfInvokingfunc.mypublicfunction() ;//a is 4
selfInvokingfunc.mypublicfunction(); // a is 6
var nonSelfInvokingAnonymousFunction = function () {
var a=2;
var myprivatefunction = function () {
a=a+2;
console.log(a);
}
return {
mypublicfunction : function () {
myprivatefunction();
}
}
};
nonSelfInvokingAnonymousFunction().mypublicfunction(); //a is 2
nonSelfInvokingAnonymousFunction().mypublicfunction(); //a is 2
Same works fine for non self invoking if invoked as :
var temp=nonSelfInvokingAnonymousFunction();
temp.mypublicfunction() ; // a is 4
temp.mypublicfunction(); // a is 6
Please help me understand the same.
Every time the main body of the outer function is executed and the lines:
var a=2;
var myprivatefunction = function () {
// ...
are run, a new binding for those variables are created in memory.
With the self-invoking function, since it's executed immediately and once, there then exists one binding for the a variable, which the mypublicfunction property can see via the closure.
In contrast, with your nonSelfInvokingAnonymousFunction, every time you invoke it, you create a separate binding for a:
nonSelfInvokingAnonymousFunction().mypublicfunction(); //a is 2
// ^^^ creates an a ^^^^
nonSelfInvokingAnonymousFunction().mypublicfunction(); //a is 2
// ^^^ creates a SEPARATE a ^^^^
When you have two separate bindings for the a variable, calling mypublicfunction on a function that closes over one of the bindings will have no effect on the other binding.
In your last code, when you do
var temp = nonSelfInvokingAnonymousFunction();
// ^^^ creates an a ^^^^
temp.mypublicfunction() ; // a is 4
temp.mypublicfunction(); // a is 6
You create a single a, and a temp whose mypublicfunction function closes over that one a, so calling mypublicfunction multiple times results in that a changing multiple times.
Shouldn't the value of research be undefined as it has been declared as var research in the end. And hence the output be a type error. But I am getting the output as 'hello'. Any idea why?
function newFunc() {
function research() { console.log('hello') };
research();
var research;
}
newFunc();
Because of hoisting, what actually happens is more like this:
function newFunc() {
var research;
research = function() { console.log('hello') };
research();
}
newFunc();
The variable declarations and function definitions are hoisted - moved to the top of the function scope. So even though you are declaring it at the end, the compiler will move it to the top of the function so it ends up like:
function newFunc() {
var research = function () { console.log('hello') };
research();
}
newFunc();
JS only hoists declarations, not initializations. JS also hoists the actual function definition.
JavaScript only hoists declarations, not initializations. Documentation
So values will be assigned in the order they are placed, for instance:
x = 2;
console.log(x); //2
x = 3;
console.log(x); //3
var x ;
or in your case:
var x = 2;
console.log(x); //2
var x = 3;
console.log(x); //3
var x ;
Another thing is that, research in the var research; part is not undefined; it's rather a function expression till you override it by another assignment, like var research = '';
So in your case, it's like the following:
function newFunc() {
function research() { console.log('hello') };
research(); //'hello'
var research;
console.log(research) //function research(){console.log('hello');}
}
Hey so I have a function that takes a string from an input box and splits it up to numbers and letters, seen here:
function sepNsLs() {
"use strict";
var letterArray = [];
var numberArray = [];
separatorSpacerator();
var L = 0;
var listResult = document.getElementById("listInput").value;
var splitResult = listResult.split(separator.sep);
for (; L < splitResult.length; L++) {
if (isNaN(splitResult[L])) {
letterArray.push(splitResult[L]);
} else if (Number(splitResult[L])) {
numberArray.push(splitResult[L]);
}
}
}
My program has to pass through JSLint perfectly, meaning I need to use my functions in strict mode. I've only put them in strict mode now, meaning that my later functions that try to call the letterArray and numberArray that I declared and filled in the SepNsLs function no longer call those arrays and the arrays come up undeclared. Here's the code for one of them:
function addNumbers() {
"use strict";
var sum = 0;
var i = 0;
sepNsLs();
while (i < numberArray.length) {
sum = sum + Number(numberArray[i]);
i++;
}
As you can see, I call the sepNsLs function in the addNumbers function, but because of strict mode, I can't use the arrays sepNsLs creates. How do I fix this? Also, is there a website like the javascript beautifier that will fix my current code to fit strict mode conventions?
EDIT: Separator is declared a global variable here:
var separator = {
sep: 0
};
separatorSpacerator makes it so that if I choose to split my input strings at a space, the input box to tell my program to split at the spaces declares the word "Space" so I can see it is a space I'm splitting my string at.
function separatorSpacerator() {
"use strict";
var list = document.getElementById("listInput").value;
if (document.getElementById("separatorInput").value === "space") {
separator.sep = " ";
} else if (document.getElementById("separatorInput").value === " ") {
separator.sep = " ";
document.getElementById("separatorInput").value = "space";
} else {
separator.sep = document.getElementById("separatorInput").value;
}
if (list.indexOf(separator.sep) === -1) {
alert("Separator not found in list!");
clearResults();
}
}
I can't use the arrays sepNsLs creates. How do I fix this?
One way of fixing this would be to return arrays sepNsLs creates with e.g. a tuple - return [numberArray, letterArray]; , and then use it like:
a) es6 syntax:
var [numberArray, letterArray] = sepNsLs();
b) pre-es6 syntax:
var split = sepNsLs(),
numberArray = split[0],
letterArray = split[1];
Your addNumbers function should also probably return sum - otherwise, it doesn't produce any meaningful results as it stands.
Although not relevant to the question and is more of a matter of naming convention preference - you might want to explore on Hungarian notation and its' drawbacks.
Your problem is one of scope. When you try to access numberArray inside of addNumbers it doesn't exist.
You have a couple of options:
Make all the variables that need to be accessed in each function global.
Wrap all of your functions in an outer function and place the 'global' variables into that outer scope.
The better option is #2, because you won't actually be polluting the global scope with variables. And you can declare "use strict" at the top of the outer function and it will force everything in it into strict mode.
Something like this:
(function() {
"use strict";
// These are now in-scope for all the inner functions, unless redclared
var letterArray = [], numberArray = [], separator = {sep: 0};
function sepNsLs() {
// code goes here
}
function addNumbers(){
// code goes here
}
function separatorSpacerator(){
//code goes here
}
// ...more functions and stuff
// and then call...
theFunctionThatKicksOffTheWholeProgram();
}());
The variables letterArray and numberArray are declared local to the function sepNsLs, they are only accessed in that scope (strict mode or not). Here is an example:
function foo() {
var fooVar = 5;
console.log(fooVar);
}// fooVar get destroyed here
function bar() {
console.log(fooVar); // undefined because fooVar is not defined
}
foo();
bar();
A scope usually is from an open brace { to it's matching close brace }. Any thing declared inside a scope is only used withing that scope. Example 2:
var globalVar = 5; // belongs to the global scope
function foo() {
var fooVar = 6; // belongs to the foo scope
function bar1() {
console.log(globalVar); // will look if there is a globalVar inside the scope of bar1, if not it will look if there is globalVar in the upper scope (foo's scope), if not it will in the global scope.
console.log(fooVar); // same here
var bar1Var = 7; // belongs to bar1 scope
}
function bar2() {
var globalVar = 9; // belongs to the bar2 scope (shadows the global globalVar but not overriding it)
console.log(globalVar); // will look if there is a globalVar in this scope, if not it will look in one-up scope (foo's scope) .... untill the global scope
console.log(bar1Var); // undefined because bar1Var doesn't belong to this scope, neither to foo's scope nor to the global scope
}
bar1();
bar2();
console.log(globalVar); // prints 5 not 9 because the serach will be in foo's and the global scope in that order
}
foo();
What you need to do is to decalre the variables letterArray and numberArray where they can be access by both sepNsLs and addNumbers (one scope above both of them). Or return the value from sepNsLs and store it in a variable inside addNumbers. Like this:
function sepNsLs() {
// logic here
return numberArray; // return the array to be used inside addNumbers
}
function addNumbers() {
var arr = sepNsLs(); // store the returned value inside arr
for(var i = 0; i < arr.length; ... // work with arr
}
I don't quite understand this bit of code.
$('div').click((function () {
var number = 0;
return function () {
alert(++number);
};
})());
My understanding is:
An anonymous function is defined and assigned to the click handler.
When I click on div, this function is invoked.
What the function does is:
Define a variable number = 0
Return ++number
So why does the number in alert increment every time I click? Shouldn't number be reset to 0 every time I click?
Here you've got a self-invoking function, which returns a function. Watch out for the brackets at the end:
(function () {
var number = 0;
return function () {
alert(++number);
};
})()
So the callback of the click handler is only the returned inner function:
function () {
alert(++number);
};
This inner function has access to the variable number, which is in the scope of the outer function.
So your code can also be written as follows:
function outerFunction() {
var number = 0;
return function () {
alert(++number);
};
};
var innerFunction = outerFunction();
$('div').click(innerFunction);
If we used (ugly) names for the anonymous functions, your code could be rewritten as:
$('div').click((function makeIncrementer() {
var number = 0;
return function incrementAndAlert() {
alert(++number);
};
})());
More verbose code retaining similar semantics would be:
var makeIncrementer = function() {
var number = 0;
return function() { alert(++number); };
};
var incrementAndAlert = makeIncrementer(); // function() { alert(++number); }
$('div').click(incrementAndAlert);
makeIncrementer is a function that, when called, defines a number variable in its scope, and returns a function - note that makeIncrementer doesn't increment, nor alert the number variable, instead it returns another function that does just that.
Now incrementAndAlert is bound to this returned function
function() { alert(++number); }
that captures makeIncrementer's number variable, which enables it to keep number's state between incrementAndAlert calls triggered by $('div') clicks.
This is not an "answer", but hopefully it will show a different way of looking at the problem.
First off, note that JavaScript functions are just objects and are thus just values that can be bound to variables. As such,
$('div').click((function () {
var number = 0;
return function () {
alert(++number);
};
})());
can be, with a simple expression substitution, rewritten as
var f = function () {
var number = 0;
return function () {
alert(++number);
};
};
// $('div').click((f)()); and when removing extra parenthesis ->
$('div').click(f());
Then, after one more simple expression substitution
var g = f()
$('div').click(g);
it should be clear that the (outer) function, f, is invoked first and it is the resulting (inner function) value, g, that is used as the handler.
Aside from introducing variables, the above substitutions are semantically equivalent to the original code.
Hi still i'm not sure about the exact usage of using closures in javascript.I have idea about closures "A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain".But i don't know why we are using closures in javascript.
It allows you to succinctly express logic without needing to repeat yourself or supply a large number of parameters and arguments for a callback function.
There is more information available here: javascript closure advantages?
Imagine if instead of
alert("Two plus one equals" + (2+1) );
you'd be forced to declare a variable for every constant you ever use.
var Two = 2;
var One = 1;
var myString = "Two plus one equals";
alert(myAlert + (Two + One) );
You'd go crazy if you had to define a variable for every single constant before you can ever use it.
The access to local variables in case of closures is an advantage, but the primary role - usefulness - is the use of a function as a primary expression, a constant.
Take
function Div1OnClick()
{
Counter.clickCount ++;
}
$('#Div1').click(Div1OnClick);
versus
$('#Div1').click(function(){ Counter.clickCount++; });
You don't create a new function name in the "above" namespace just to use it once. The actual activity is right there where it's used - you don't need to chase it across the code to where it was written. You can use the actual function as a constant instead of first defining and naming it and then calling it by name, and while there are countless caveats, advantages and tricks connected to closures, that's the one property that sells them.
In general, the main use of closures is to create a function that captures the state from it's context. Consider that the function has the captured variables but they are not passed as parameters.
So, you can think of it of a way to create families of functions. For example if you need a series of function that only differ in one value, but you cannot pass that value as a parameter, you can create them with closures.
The Mozilla Developer Network has a good introduction to closures. It shows the following example:
function init() {
var name = "Mozilla";
function displayName() {
alert(name);
}
displayName();
}
init();
In this case the function displayName has captured the variable name. As it stand this example is not very useful, but you can consider the case where you return the function:
function makeFunc() {
var name = "Mozilla";
function displayName() {
alert(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();
Here the function makeFunc return the function displayName that has captured the variable name. Now that function can be called outside by assigning it to the variable myFunc.
To continue with this example consider now if the captured variable name were actually a parameter:
function makeFunc(name) {
function displayName() {
alert(name);
}
return displayName;
}
var myFunc = makeFunc("Mozilla");
myFunc();
Here you can see that makeFunc create a function that shows a message with the text passed as parameter. So it can create a whole family of function that vary only on the value of that variable ("Mozilla" in the example). Using this function we can show the message multiple times.
What is relevant here is that the value that will be shown in the massage has been encapsulated. We are protecting this value in a similar fashion a private field of a class hides a value in other languages.
This allows you to, for example, create a function that counts up:
function makeFunc(value) {
function displayName() {
alert(value);
value++;
}
return displayName;
}
var myFunc = makeFunc(0);
myFunc();
In this case, each time you call the function that is stored in myFunc you will get the next number, first 0, next 1, 2... and so on.
A more advanced example is the "Counter" "class" also from the Mozilla Developer Network. It demonstrates the module pattern:
var Counter = (function() {
var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(1);
},
decrement: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
}
})();
alert(Counter.value()); /* Alerts 0 */
Counter.increment();
Counter.increment();
alert(Counter.value()); /* Alerts 2 */
Counter.decrement();
alert(Counter.value()); /* Alerts 1 */
Here you can see that Counter is an object that has a method increment that advances the privateCounter variable, and the method decrement that decrements it. It is possible to query the value of this variable by calling the method value.
The way this is archived is with an auto-invocation of an anonymous function that creates a hidden scope where the varialbe privateCounter is declared. Now this variable will only be accessible from the functions that capture its value.
Closures are a powerful construct used to implement a lot of additional features in JavaScript. For instance a closure can be used to expose private state as follows:
function getCounter() {
var count = 0;
return function () {
return ++count;
};
}
var counter = getCounter();
alert(counter()); // 1
alert(counter()); // 2
alert(counter()); // 3
In the above example when we call getCounter we create a private variable count. Then we return a function which return count incremented. Hence the function we return is a closure in the sense that it closes over the variable count and allows you to access it even after count goes out of scope.
That's a lot of information stuffed in a few lines. Let's break it down?
Okay, so variables have a lifetime just like people do. They are born, they live and they die. The beginning scope marks the birth of a variable and the end of a scope marks the death of a variable.
JavaScript only has function scopes. Hence when you declare a variable inside a function it's hoisted to the beginning of the function (where it's born).
When you try to access a variable which is not declared you get a ReferenceError. However when you try to access a variable which is declared later on you get undefined. This is because declarations in JavaScript are hoisted.
function undeclared_variable() {
alert(x);
}
undeclared_variable();
When you try to access an undeclared variable you get a ReferenceError.
function undefined_variable() {
alert(x);
var x = "Hello World!";
}
undefined_variable();
When you try to access a variable which is declared later in the function you get undefined because only the declaration is hoisted. The definition comes later.
Coming back to scopes a variable dies when it goes out of scope (usually when the function within which the variable is declared ends).
For example the following program will give a ReferenceError because x is not declared in the global scope.
function helloworld() {
var x = "Hello World!";
}
helloworld();
alert(x);
Closures are interesting because they allow you to access a variable even when the function within which variable is declared ends. For example:
function getCounter() {
var count = 0;
return function () {
return ++count;
};
}
var counter = getCounter();
alert(counter()); // 1
alert(counter()); // 2
alert(counter()); // 3
In the above program the variable count is defined in the function getCounter. Hence when a call to getCounter ends the variable count should die as well.
However it doesn't. This is because getCounter returns a function which accesses count. Hence as long as that function (counter) is alive the variable count will stay alive too.
In this case the function which is returned (counter) is called a closure because it closes over the variable count which is called the upvalue of counter.
Uses
Enough with the explanation. Why do we need closures anyway?
As I already mentioned before the main use of closures is to expose private state as is the case with the getCounter function.
Another common use case of closures is partial application. For instance:
function applyRight(func) {
var args = Array.prototype.slice.call(arguments, 1);
return function () {
var rest = Array.prototype.slice.call(arguments);
return func.apply(this, rest.concat(args));
};
}
function subtract(a, b) {
return a - b;
}
var decrement = applyRight(subtract, 1);
alert(decrement(1)); // 0
In the above program we had a function called subtract. We used partial application to create another function called decrement from this subtract function.
As you can see the decrement function is actually a closure which closes over the variables func and args.
That's pretty much all you need to know about closures.
It is because of information hiding.
var myModule = (function (){
var privateClass = function (){};
privateClass.prototype = {
help: function (){}
};
var publicClass = function (){
this._helper = new privateClass();
};
publicClass.prototype = {
doSomething: function (){
this._helper.help();
}
};
return {
publicClass: publicClass
};
})();
var instance = new myModule.publicClass();
instance.doSomething();
In javascript you don't have classes with ppp (public, protected, private) properties so you have to use closures to hide the information. On class level that would be very expensive, so the only thing you can do for better code quality to use closure on module level, and use private helper classes in that closure. So closure is for information hiding. It is not cheap, it cost resources (memory, cpu, etc..) so you have to use closures just in the proper places. So never use it on class level for information hiding, because it is too expensive for that.
Another usage to bind methods to instances by using callbacks.
Function.prototype.bind = function (context){
var callback = this;
return function (){
return callback.apply(context, arguments);
};
};
Typical usage of bound function is by asynchronous calls: defer, ajax, event listeners, etc...
var myClass = function (){
this.x = 10;
};
myClass.prototype.displayX = function (){
alert(this.x);
};
var instance = new myClass();
setTimeout(instance.displayX.bind(instance), 1000); //alerts "x" after 1 sec