Java Script Function Methods [duplicate] - javascript

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 8 years ago.
What is the different between following two methods of defining js function. I have seen this is some code some one given, but could not able to call the function inside of it.
1)
function sum () {
var i, sum = 0;
for (i = 0; i < arguments.length; i += 1) {
sum += arguments[i];
}
return sum;
};
2)
var sum = function () {
var i, sum = 0;
for (i = 0; i < arguments.length; i += 1) {
sum += arguments[i];
}
return sum;
};

The difference is that the var one is defined after the var is created, whereas the static one is defined without waiting for a var to get referenced.
You can call the "var one" only after you declare it since it is "known" at run-time.
example:
a(); // error - doesn't know a
var a = function(){alert('a')}
b(); // ok
function b(){ alert('b')}

First can be used before declaring but second can be used only after its declaration..

Related

Javascript Closure not taking inputs consistently

I have two javascript closures and I'm trying to understand why one will accept and input with a particular syntax and the other will reject.
function multiply(factor) {
var ace = (function(number) {
return number*factor;
});
return ace;
}
var yup = multiply(4);
console.log(yup(5));
This outputs 20 to the console as it should.
The second Closure I have is
var k = 3;
var add = (function () {
console.log(k);
var counter = k;
return function (j) {counter += 1; return counter*j}
})(k);
add();
console.log(add(5));
The output is 20 as it should be.
This issue I'm having that if I try to use the syntax of
(function() {
})(number);
In the first closure it does not work and outputs "number is not defined"
And if I try to input into the second closure
(function (k) {
var counter = k;
return function (j) {counter += 1; return counter*j}
});
I get out
function (j) {counter += 1; return counter*j}
to the console.
My question is, what am I not understanding about closers the () at the end of them.
The difference is whether you are creating the closure right away through an IIFE, or a function that makes the closure when called.
Your first snippet written in the second style would be
var yup = (function multiply(factor) {
return function ace(number) {
return number*factor;
};
})(4); // the multiply(4) call is inlined into the statement with the definition
console.log(yup(5));
Your second snippet written in the first style would be
function makeAdd(k) {
console.log(k);
var counter = k;
return function (j) {
counter += 1;
return counter*j;
}
}
var add = makeAdd(3);
add();
console.log(add(5));

When and why to use these various Java Script function declaration formats? [duplicate]

This question already has answers here:
Export const arrow function or basic function?
(1 answer)
What are the advantages/disadvantages for creating a top level function in ES6 with arrows or without?
(2 answers)
Closed 4 years ago.
What are the differences between the following function declaration formats?
When is it more correct to use which?
From a beginner's perspective, and a high level (non-deep) point of view, they all three appear to work the same - hence it makes things feel confusing and demands the question.
1.
const counter1 = function(num) {
var x = 0;
while (x < num) {
console.log(x);
x ++;
};
return 0;
};
2.
function counter2(num) {
var x = 0;
while (x < num) {
console.log(x);
x ++;
};
return 0;
};
3.
const counter3 = (num) => {
var x = 0;
while (x < num) {
console.log(x);
x ++;
};
return 0;
};
All of them appear to behave the same.
There are more than a few differences between your three examples actually.
So, for one, you have to be careful using const for your function declarations.
counter1(5); // counter1 is undefined, this will fail
const counter1 = function(num) {
var x = 0;
while (x < num) {
console.log(x);
x ++;
};
return 0;
};
Whereas the function will be hoisted and available for use (Edit: technically let and const are also hoisted, but they aren't initialized so you cannot access them before they are declared, more info here.
counter2(5); // works fine
function counter2(num) {
var x = 0;
while (x < num) {
console.log(x);
x ++;
};
return 0;
};
Also note that const prohibits reassigning the variable, so you couldn't go say const counter1 = {} later down the line, whereas you could feasibly do so with the function example.
As far as the difference between function(num) { versus (num) => {, well in your example it makes no difference. But there are some differences... for example
const thisWillFail = () => {
console.log(arguments.length);
};
const thisWorks = function() {
console.log(arguments.length);
};
If you're unfamiliar with the arguments object, you can find info here.

Running functions using string name from array [duplicate]

This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed 5 years ago.
I have an array that has a bunch of function names. I am not storing the function in an object.
for (i = 0; i < view_functions.length; i++) {
view_functions[i]();
}
This doesn't work, any ideas?
Thanks.
The code you posted works, so perhaps the code that defines the functions isn't quite right. Here is a fully working example.
function yep() {
alert('Yep');
}
function again() {
alert('Again');
}
var view_functions = [
yep,
again
];
for (var i = 0; i < view_functions.length; i++) {
view_functions[i]();
}
If you wanted to get a bit of design help in your code, you could introduce a factory. This has the added benefit of making unknown function names explicit.
function yep() {
alert('Yep');
}
function again() {
alert('Again');
}
function functionFactory(name) {
switch (name) {
case 'yep':
return yep;
case 'again':
return again;
default:
throw `${name} not a known function in functionFactory`;
}
}
var view_functions = [
'yep',
'again'
];
for (var i = 0; i < view_functions.length; i++) {
var func = functionFactory(view_functions[i]);
func();
}
If you only have string names, I recommend not using string names... but you could go full-evil and use eval...
function yep() {
alert('Yep');
}
function again() {
alert('Again');
}
var view_functions = [
'yep',
'again'
];
for (var i = 0; i < view_functions.length; i++) {
var n = view_functions[i] + '()';
eval(n);
}
But why not store the actual functions in the array instead...

How to push a declared function into an array and later invoke it [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 5 years ago.
The following code works great. It pushes 10 unnamed functions into an array and then successfully executes the 7th item in the array.
var storeStuff = [];
for (let i = 0; i < 10; i++) {
storeStuff.push(function() {
console.log(i * i);
});
}
storeStuff[6]();
However the test function above is tiny. If I had a large function with many lines of code I'd likely want to declare it outside of the push.
For example what if I wanted to push a previously defined function and later invoke it like the example below?
var storeStuff = [];
function externalFunction(temp) {
console.log(temp * temp)
}
for (let i = 0; i < 10; i++) {
storeStuff.push(externalFunction(i));
}
storeStuff[6]();
Unfortunately this doesn't work as written and everything I've tried crashed and burned. What am I getting wrong?
Use function declaration as below
var storeStuff = [];
externalFunction = function(temp) {
console.log(temp * temp)
}
for (let i = 0; i < 10; i++) {
storeStuff.push(externalFunction);
}
storeStuff[6](6);

Javascript Function Call [duplicate]

This question already has answers here:
Javascript function scoping and hoisting
(18 answers)
Closed 6 years ago.
The question is really simple but i searched everywhere couldn't get an answer.
add();
function add()
{
//function code here
}
The above code works in JavaScript even though function call is before function definition but wouldn't work in language such as C or C++. Could anyone tell me why?
It's known as hoisting, and it's definitely a trap for beginners!
Basically, if you take this code:
var x = 21;
var y = add10(x);
function add10(n) { return n + 10; }
after hoisting, it is evaluated like this:
function add10(n) { return n + 10; }
var x;
var y;
x = 21;
y = add10(x);
Because the declarations are separated from the definitions, and "hoisted" to the top.
Funnily enough, this would fail:
var x = 21;
var y = add10(x);
var add10 = function (n) { return n + 10; }
because it is evaluated like this:
var x;
var y;
var add10;
x = 21;
y = add10(x); // add10 is not a function (yet...)!
add10 = function (n) { return n + 10; }
It's called hoisting.
The javascript engine first looks for function declarations and 'hoists' them to the top before your actual code starts running.
Here's the documentation: http://www.w3schools.com/js/js_hoisting.asp

Categories