Javascript - Why below function definition errors out? - javascript

var a = [3,5,2,6,8];
var i = 0;
function x(a[i]) { //This line errors out, why?
}
Please explain why above line errors out? and I am trying to print array elements in reverse order using recursion. If you can write the code also, would be fantastic!

you pass value to function definition. you have to give it when you call function, not when defining
function. you can pass a value when you call a function.
var a = [3,5,2,6,8];
var i = 0;
function x(t) {
}
x(a[i]);

You are defining a function with an argument incorrectly. You give a name to your function arguments, just like any other variable:
function x(array) {
//Do something with your array
}
And then you call the function:
var a = [1,2,3,4,5];
x(a);

As you can read on other answers, you are sort of mixing function declaration and function evaluation (call).
This declares the function x that accepts an a parameter:
function x(a) {
}
And this calls a function x with argument a:
var a = [3,5,2,6,8];
x(a);
or directly:
x([3,5,2,6,8]);
Regarding to the recursive function to reverse an array, this could be an option:
var a = [3,5,2,6,8];
function x(a) {
if (a.length === 0) {
return [];
}
return a.slice(-1).concat(x(a.slice(0, -1)));
}

Using recursion:
var a = [3,5,2,6,8];
function x(p, len) {
if(len >= 0){
alert(p[len-1]);
x(p, len-1);
}
}
// and call
x(a, 5);
DEMO

Related

How does this higher order function work in JavaScript?

This code is confusing me.
Where does the inner function get the value for x.
function createMultiplier(multiplier) {
return function(x) {
return x * multiplier
}
}
let doubleMe = createMultiplier(2);
This is called currying, what happens is that in the function createMultiplier you get a function and then when you execute that function you pass the parameter x
If you want to execute the function inside the function immediately, you can use this code createMultiplier(2)(5)
If you use console logs you can understand better what happens, I made an example bellow, so you can see first you only get a function and then you can pass the parameter x
function createMultiplier(multiplier) {
return function(x) {
return x * multiplier
}
}
const doubleMe = createMultiplier(2);
console.log(doubleMe)
const result = doubleMe(5)
console.log(result)
The inner function will get the value x. When you invoke: doubleMe(16), for example.
When you call createMultiplier(2) you are setting the multiplier value.
It might be helpful to try and visual what happens when you call createMultiplier(2).
This will create a function that would look like this:
function doubleMe(x) {
return x * 2; // 2 is the multiplier that we supplied to 'createMultiplier'
}
let answer = doubleMe(4);
// answer = 8;
another example:
let tripleMe = createMultiplier(3);
// is the same as writing this
function tripleMe(x) {
return x * 3;
}
let answer = tripleMe(3);
// answer = 9;

How to return a value from a callback that is passed a parameter

I have made a function square (that returns square of the number)and passed it into another function.
var num = 5;
function square(x){
return x*x;
}
function display(fn){
console.log(fn())
}
display(function(){square(num)});
It is not returning me that squared value in display function instead it is returning me 'undefined'.
Here. You just need to return the square(num) inside the display function.
var num = 5;
function square(x){
return x*x;
}
function display(fn){
console.log(fn());
}
display(function(){
return square(num);
});
You don't have to use function(){} to call your function.
It is only used to define a function.
Beside this you can just use the fn variable to log to the console, you don't have to use fn()
var num = 5;
function square(x){
return x*x;
}
function display(fn){
console.log(fn)
}
display(square(num));
It is also possible to return the value into a variable, if this makes it easier to read for you:
function square(x){
return x*x;
}
function display(fn){
console.log(fn)
}
var num = 5;
var calculationResult = square(num);
display(calculationResult);
You lose the returned value here:
display(function(){square(num)})
You either have to return it:
display(function(){ return square(num)})
or you use an arrow function
display(() => square(num));
or you bind the function:
display(square.bind(null, num));
display(function(){square(num)});
In your code just write return keyword .
display(function(){return square(num)});
Above code will work fine

In JavaScript, how to execute next function from an array of functions

I have an array of functions, as in:
funcArray = [func1, func2, func3];
When in a given function, I want to execute the next function in the array. How do I do this? Here is my basic skeleton:
function func1() {
// I get current function caller
var currentFunc = func1.caller;
// I want to execute the next function. Happens to be func2 in the example.
}
I cannot use indexOf function, as one would for an array of strings or numbers.
NOTE: This question appears to be similar to this and the one it refers to. However, it is a different question.
I want to alter the sequence of processing by merely modifying the array. That's the goal. A possibly more efficient approach would be appreciated.
Clarification: Based upon some of the comments:
funcArray is global.
The goal is to implement middleware for a Node.js HTTP module in as simple and efficient a manner as possible without using any third-party modules.
Unless func1 closes over funcArray, you cannot have it reach out and find func2 and execute it, nor should you. Even if func1 does close over funcArray, it would be poor separation of concerns for func1 to reach out and find itself in funcArray and then execute func2.
Instead, have other code that's in charge of running the functions.
If they're synchronous
If the functions complete their work synchronously, then it's simply:
funcArray.forEach(fn => fn());
or
for (const fn of funcArray) {
fn();
}
or if the result of one function should be passed to the next, you can use reduce:
const finalResult = funcArray.reduce((previousResult, fn) => fn(previousResult), undefined);
...where undefined is the value to pass to func1.
If they're asynchronous
If they don't do their work synchronously, you'll need to provide them a way to notify their caller that they've completed their work. Promises are a good, standard way to do that, but you could use simple callbacks instead.
If you make them return promises, for instance, you can use the old promise reduce trick:
funcArray.reduce((p, fn) => {
return p.then(() => {
fn();
});
}, Promise.resolve());
or if the result of one function should be passed to the next:
funcArray.reduce((p, fn) => {
return p.then(fn);
}, Promise.resolve());
You can provide an argument to Promise.resolve to set the value to pass to func1 (without one, it'll receive undefined).
You can bind to the function the index where it is in the array so you can use this index to get and call the next function:
var funcArray = [func1, func2];
var boundFuncArray = funcArray.map((f, i) => f.bind(null, i));
boundFuncArray[0]();
function func1(nextFunctionIndex) {
console.log('func1 called');
// Execute next function:
var nextFunc = boundFuncArray[nextFunctionIndex + 1];
nextFunc && nextFunc();
}
function func2(nextFunctionIndex) {
console.log('func2 called');
// Execute next function:
var nextFunc = boundFuncArray[nextFunctionIndex + 1];
nextFunc && nextFunc();
}
As T.J Crowder stated in the comment below, you can also bind the next function to the current one:
var funcArray = [func1, func2];
var boundFuncArray= funcArray.map((f, i, arr) => f.bind(null, arr[i + 1]));
boundFuncArray[0]();
function func1(nextFunc) {
console.log('func1 called');
// Execute next function:
nextFunc && nextFunc();
}
function func2(nextFunc ) {
console.log('func2 called');
// Execute next function:
nextFunc && nextFunc();
}
You can get the current function's name with arguments.callee.name, loop through the array of functions, and call the next function:
funcArray = [func1, func2, func3];
// Only func1() and func2() will be documented since the others have repeating code
function func1() {
// show the current function name
console.log(arguments.callee.name);
// loop the array of functions
for(var i = 0; i < funcArray.length; ++i)
{
// when the current array item is our current function name and
// another function exists after this then call it and break
if(funcArray[i] === arguments.callee && funcArray[i+1])
{
funcArray[i+1]();
break;
}
}
}
function func2() {
console.log(arguments.callee.name);
// some logic which switches our next function to be func4()
funcArray[2] = func4;
for(var i = 0; i < funcArray.length; ++i)
{
if(funcArray[i] === arguments.callee && funcArray[i+1])
{
funcArray[i+1]();
break;
}
}
}
function func3() {
console.log(arguments.callee.name);
for(var i = 0; i < funcArray.length; ++i)
{
if(funcArray[i] === arguments.callee && funcArray[i+1])
{
funcArray[i+1]();
break;
}
}
}
function func4() {
console.log(arguments.callee.name);
for(var i = 0; i < funcArray.length; ++i)
{
if(funcArray[i] === arguments.callee && funcArray[i+1])
{
funcArray[i+1]();
break;
}
}
}
// call the first function
funcArray[0]();
Output:
func1
func2
func4
I have solved it this way:
// Adding next options to array
function addNext(array) {
array.last = 1
Object.defineProperty(array, 'next', {get:
function() {
if(this.last < this.length) {
this.last++
return this[this.last-1]
} else {
this.last = 1
return () => {}
}
}
});
}
// The functions for array (has to be function and not arrow function)
function first(param) {
console.log('first',param)
return this.next(param)
}
function second(param) {
console.log('second',param)
return this.next(param)
}
function third(param) {
console.log('third',param)
return this.next(param)
}
// The array
let fns = [first,second,third]
// Adding next option to array
addNext(fns)
// Run first function from array
fns[0]('test')
I dont know if your functions require certain parameters but this is the first thing that came to my mind.
var functArray = [
function() {
console.log("function1 executed");
},
function() {
console.log("function2 executed");
},
function() {
console.log("function3 executed");
},
function() {
console.log("function4 executed");
}];
functArray.forEach(function(x){
x();
});
The accepted answer and other comments did help me, but the way I implemented it is as follows:
//The functions are defined as variables.
//They do not get hoisted, so must be defined first.
func1 = function (arg1, arg2) {
//Code to do whatever...
...
//Execute the next function.
//The name of the function is returned by executing nextFunc()
global[nextFunc()](arg1, arg2, arg3);
}
func2 = function (arg1) { //Note different type of args
...
}
//Note that this is an array of strings representing function names.
funcArray = ["func1", "func2", "func3",...]
//Start the execution...
func1(arg1, arg2);
function nextFunc() {
var currentFuncName = nextFunc.caller.name;
var index = funcArray.indexOf(currentFuncName);
if (index < funcArray.length)
return funcArray[index+1];
}
The sequence of functions to be executed is easily managed through the array funcArray. The number or type of arguments is not fixed for each function. Additionally, the functions control if they should stop the chain or continue with the next function.
It is very simple to understand requiring basic Javascript skills. No overheads of using Promises.
"global" gets replaced by "window" for browser. This is a Node.js implementation. The use of function names in the array will, however, break if you minify the JS code. As I am going to use it on the server, I do not expect to minify it.
You can do it in this way with promise.all if your functions to be executed in parallel.
let toBeExecutedList = [];
toBeExecutedList.push(() => this.addTwoNumber(2, 3));
toBeExecutedList.push(()=>this.square(2));
And Then wherever you want to use them, do it like this:
const resultArr = await Promise.all([
toBeExecutedList.map(func => func()),
]);

Runtime error when executing simple closure in Javascript

Im new to JS and trying to learn. The spec requires the following:
Write a function that takes another function* as an argument and creates a version of the function that can only be called one time. Repeated calls to the modified function will have no effect, returning the value from the original call. How could you do this without using a closure? Is it even possible? How could you do this with a closure? *Note: This original input function should not have any parameters.
This is what I have:
var divide = function () {
var x = 2;
var y = 6;
return y/x;
}
var mainFunc = function (func) {
return func(){
return y/x + 1;
}
}
var output = mainFunc(divide);
console.log(divide());
console.log(output());
console.log(output());
I'm getting an "Unexpected token{" error at "return func(){" I don't quite understand what i'm doing wrong? Per the spec, I am passing divide() to mainFunc() and setting it to a reference variable output. I then call the divide() and output() multiple times to test if the closure works and that modified function only happens once. What am I missing or not understanding?
Thanks for the help.
Here you go:
function runonce(func) {
return (function(func) {
var ran = false;
var retval;
return function() {
if (!ran) {
ran = true;
retval = func();
}
return retval;
}
})(func);
}
function realfunction() {
console.log('really running');
return 5;
}
var realfunctionrunner = runonce(realfunction);
realfunctionrunner();
realfunctionrunner();
realfunctionrunner();
Study the code, the whole trick is a "self contained library" which result is returned from the runonce function

Is this the right way to call a function in javascript?

This is a part of my document:
function MyFunction() {
var x=""
if (x=1) {
OnBtnPbDemo_SwitchChn1(1); //This is a function
} else {
OnBtnPbDemo_SwitchChn1(0); //This is another function
}
}
I want to know if this is the right way to call the functions inside the condition.
Thank you very much.
Not entirely sure what you mean about the "right" way of calling, but you can call functions wherever as long as they're available in the scope.
You can actually shorten what you've written to this too:
function MyFunction () {
var x = "";
OnBtnPbDemo_SwitchChn1(x === 1 ? 1 : 0);
}
Unless you're actually changing the x variable inside your function however, it'll never run with 1 as the param.
Yes, calling functions is the same no matter where you are calling it.
You need to use == in if condition instead use of =
if (x==1) {
instead of
if (x=1) {
if you are going to call same function for the different x value, Try this
function MyFunction() {
var x = 1;
OnBtnPbDemo_SwitchChn1(x); //you can pass the x value directly to that function.
}
if you are going to call different function for the different x value, Try this
function MyFunction() {
var x="";
if (x==1) {
OnBtnPbDemo_SwitchChn1(1); //This is a function
} else {
OnBtnPbDemo_SwitchChn1_another(0); //This is another function
}
}
You are calling same function twice, Instead just call the function once with the value 1/0 in it.
function MyFunction() {
//Check and find value of x
if(x=="somevalue") //true condition
{
x=1;
}
else{
x=0;
}
OnBtnPbDemo_SwitchChn1(x);
}

Categories

Resources