I am beginner in Javascript
I am always getting true returned whatever the values of my variables,
It should return true if a and b are both even, but false otherwise.
Thanks for your help.
https://repl.it/9nH/1675
var a = 4;
var b= 5;
function areBothEqual (a, b) {
if(a===b) {
return true;
}else {
return false
}
}
var result = areBothEqual();
document.write(result)
you are not passing the arguments to your function:
areBothEqual(a,b)
you had:
areBothEqual()
cheers
The issue is that you are requesting the arguments a and b in the line function areBothEqual (a, b), but they are never actually passed. Just replace the (a, b) with empty brackets (), as you can use the previously defined a and b instead.
var a = 4;
var b= 5;
function areBothEqual() {
if(a===b) {
return true;
} else {
return false
}
}
areBothEqual()
var a = 4;
var b= 5;
function areBothEqual (a, b) {
console.log(a);
console.log(b);
if(a===b) {
return true;
}else {
return false
}
}
areBothEqual();
They are 'undefined' both are equals...
Related
I have a higher order function , though the first case multiply(4,5) works as expected but is it possible to pass multiple argument like multiply(2)(4, 5). In this case the answer is 8, but can a curried function be created in such a way so that it gives 40 as result
function multiply(s) {
return function(b) {
return s * b;
}
}
console.log(multiply(4)(5))
console.log(multiply(2)(4, 5))
You could use rest parameters ... and collect all arguments on both functions and return the reduced result.
function multiply(...a) {
return function(...b) {
return [...a, ...b].reduce((a, b) => a * b);
};
}
console.log(multiply(4)(5)); // 20
console.log(multiply(2)(4, 5)); // 40
console.log(multiply(3, 2)(4, 5)); // 120
function multiply(s) {
return function(b) {
for(key in arguments)s*=arguments[key];
return s;
}
}
console.log(multiply(4)(5))
console.log(multiply(2)(4, 5))
I think its best to use arguments property in your case.
You could do something like this using arguments:
function multiply(s) {
return function () {
return Array.from(arguments).reduce(function(accumulator, currentValue) {
return accumulator * currentValue;
}, s);
}
}
You could do it this way if you have one or more b arguments :
function multiply(s) {
// Will contain the multiplication of all b arguments
var result = 1;
// ...b will return an the array arguments passed
return function(...b) {
// Loop through each of this array and update result
for (var i = 0; i < b.length; i++) {
result *= b[i];
}
// return the final result
return s * result;
}
}
console.log(multiply(4)(5))
console.log(multiply(2)(4, 5))
Is it possible to have a function that checks if any of arguments provided to it is undefined? I am trying out the following
function isDefined() {
for (var i = 0; i < arguments.length; i++)
if (typeof (arguments[i]) === "undefined") return false;
return true;
}
However, It gives me an error if I pass an undefined argument:
Uncaught ReferenceError: b is not defined
Update
Sample usage:
let a = 5;
let c = "hello";
isDefined(a, b, c); // gives false
isDefined(a, c); // gives true
function isDefined() {
return !Array.from(arguments).includes(undefined);
}
The only way I see it working is if you wrap isDefined in a try/catch. Your example usage would have to be modified as follows:
let a = 5;
let c = "hello";
try{
isDefined(a, b, c); // gives false
}catch(e){
// ... some code that can return false
}
try{
isDefined(a, c); // gives true
}catch(e){
// ... some code
}
Here's a working example:
let a = 5;
// b isn't a thing
let c = 'hello';
let d = null;
let e;
function isDefined() {
!arguments;
for (arg in arguments) {
if(arguments[arg] === null || arguments[arg] === undefined) {
return false;
}
}
return true;
}
console.log(`isDefined(a, c): Result: ${isDefined(a, c)}`);
//you'd have to wrap isDefined in a try/catch if you're checking for this
try{
console.log(`try{isDefined(a, b, c)}catch(e){...}: Result: ${isDefined(a, b, c)}`);
}catch(err){
console.log('try{isDefined(a, b, c)}catch(e){...}: Result: false');
}
console.log(`isDefined(d) Result: ${isDefined(d)}`);
console.log(`isDefined(e): Result: ${isDefined(e)}`);
undefined has the value null.
Any undefined elements in an array return null.
function isDefined() {
for (var i = 0; i < arguments.length; i++)
if (arguments[i]==null) return false;
return true;
}
Function that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times that must multiply the digits in num until it reach a single digit.
var persistenceCount = 0;
function persistence(num) {
var arr = _parseToNumericArray(num);
if (_checkLength(arr)) {
return persistenceCount;
} else {
persistenceCount++;
var newNum = _getMultiple(arr);
persistence(newNum);
}
}
function _parseToNumericArray(num) {
var n = num.toString().split("");
return n.map(function(elem) {
return parseInt(elem);
});
}
function _checkLength(arr) {
return arr.length === 1;
}
function _getMultiple(arr) {
return arr.reduce(function(a, b) {
return a * b;
});
}
console.log(persistence(39)); // Getting output as undefined
Like #Keith said, you forgot to return the value.
var persistenceCount = 0;
function persistence(num) {
var arr = _parseToNumericArray(num);
if (_checkLength(arr)) {
return persistenceCount;
} else {
persistenceCount++;
var newNum = _getMultiple(arr);
return persistence(newNum);
}
}
function _parseToNumericArray(num) {
var n = num.toString().split("");
return n.map(function(elem) {
return parseInt(elem);
});
}
function _checkLength(arr) {
return arr.length === 1;
}
function _getMultiple(arr) {
return arr.reduce(function(a, b) {
return a * b;
});
}
console.log(persistence(39)); // Outputs 3
There is no return statement in the else. So return undefined.
By default, in JavaScript, a function always return undefined if nothing is returned.
I have tried writing the below code to find sum of 'n' numbers using sum function. I am getting the correct response in output. But i am unable to return that using sum function, as i always have to return a function, which is required for curried effect.
Please help. Thanks in advance.
var output = 0,
chain;
function sum() {
var args = Array.prototype.slice.call(arguments);
output += args.reduce(function(a, b) {
return a + b;
});
sumCurried = sum.bind(output);
sumCurried.val = function() {
return output;
}
return sumCurried;
}
debugger;
document.getElementById('demo').innerHTML = sum(1, 2)(3)(4);
// document.getElementById('demo').innerHTML = sum(1)(3)(4);
<p id='demo'></p>
enter code here
You can add a stop condition to the curried function, for example - if the function is called without an argument return the output:
var output = 0,
chain;
function sum() {
var args = Array.prototype.slice.call(arguments);
if(args.length === 0) {
return output;
}
output += args.reduce(function(a, b) {
return a + b;
});
sumCurried = sum.bind(output);
return sumCurried;
}
console.log(sum(1, 2)(3)(4)());
<p id='demo'></p>
The returned curry function has a val property, which is a function that returns the current value:
var output = 0,
chain;
function sum() {
var args = Array.prototype.slice.call(arguments);
output += args.reduce(function(a, b) {
return a + b;
});
sumCurried = sum.bind(output);
sumCurried.val = function() {
return output;
}
return sumCurried;
}
console.log(sum(1, 2)(3)(4).val());
<p id='demo'></p>
Why would you use currying at all? However, here is a shorter version:
const sum = (...args) => {
const func = (...s)=> sum(...args,...s);
func.value = args.reduce((a,b)=>a+b,0);
return func;
};
//usable as
sum(1,2).value,
sum(1,1)(1).value,
sum(1,1)(1,1)(1,1).value
And you always need to end the currying chain. However, it can be shortified:
func.valueOf = ()=> args.reduce((a,b)=>a+b,0);
//( instead of func.value = ... )
So when called you can do:
+sum(1,2,3)
+sum(1)(1)(1)
My code looks like this:
function x(a,b)
{
return a + b;
}
var f = x;
function x(a,b)
{
return a - b;
}
var res = f(2,1);
I expect that the result is 3 as f is pointing to function x before modifying it, but it isn't the case, how can I keep a reference to a function that is foing to be redefined?
Function declarations are processed before expressions. Therefore, from the point of view of the interpreter, your code is interpreted as this:
function x(a,b)
{
return a + b;
}
function x(a,b)
{
return a - b;
}
var f = x;
var res = f(2,1);
The solution is to re-assign the function using a function expression instead of a function declaration. This is because as I mentioned above expressions are processed after declarations:
function x(a,b)
{
return a + b;
}
var f = x;
x = function (a,b) // <--------- this fixes your problem
{
return a - b;
}
var res = f(2,1);
Note, that since declarations are processed before expressions, the following would work as well:
var f = x;
x = function (a,b)
{
return a - b;
}
var res = f(2,1);
function x(a,b) // this is processed first
{
return a + b;
}
Functions and variable declarations (but not variable assignments) are "hoisted" to the top of their containing scope.
So your code is equivalent to this:
function x(a,b) {
return a + b;
}
function x(a,b) { //this overwrites the previous function declaration
return a - b;
}
var f;
var res;
f = x;
res = f(2,1); //1
It should now be clear why f(2,1) is 1 instead of 2.
You can overcome this by creating functions as variables instead:
var x = function(a, b) {
return a + b;
}
var f = x;
console.log(f(2, 1)); //3
var x = function(a, b) {
return a - b;
}
var f = x;
console.log(f(2, 1)); //1
Assign your functions to variables when creating them:
var f1 = function(a, b) {
return a + b;
}
var f2 = f1;
f1 = function(a, b) {
return a - b;
}
alert( f1(2,1) ); // < Will subtract
alert( f2(2,1) ); // < Will add
This allows you to easily clone the function.