Problem of best practice with function return - javascript

I am new about programming. I have some difficulties to undurstand function.
So I done practice. But, I don't know why use return.
My code work.
In this exemple :
the function name is reverse.
I return in my function an array [1, 2, 5, 8].
Console.log a new array named reversed.
function reverse(array) {
const reversed = [];
for (i = array.length - 1; i > -1; i--) {
reversed.push(array[i]);
}
console.log(reversed);
}
return reverse([1, 2, 5, 8]);
**
But why after validate exercice, it's say me false and send me this solution :**
function reverse(array) {
const reversed = [];
for (let i = array.length - 1; i > -1; i--) {
reversed.push(array[i]);
}
return reversed;
}
Thanks : )
I googling and use chat GPT to teach me why use return in my case. But, nothing about I can understand.. I need your help.
Thank all.

The variable reversed is defined inside the function body so it can only be accessed from inside of the function. In your code you tried to access the variable from outside of the function. return keyword is used inside the function to return a value, using return outside the function has no effect.

Some remarks:
The names reverse and reversed are very similar which can lead to confusion. I see it happening in another answer and in your comments. reverse is defined as a function, and reversed is a local variable that references an array. They are completely different objects.
In your code you have placed a return statement where it is not valid. A return statement can only occur inside a function body.
console.log(reversed) will output the result in the console window, but that is not what the purpose is of the exercise. Although console.log is very useful while you are debugging your code, it is not equivalent to a return value. The caller of your function will get as return value what the function has returned with a return statement, not what console.log has output.
Your code does not define i with let (or var) and so it is implicitly declared as a global variable. This is not good practice. Always define variables explicitly.
Your code calls the reverse function. This is what you typically would do to test your function, but in code challenges, this call is typically made by the person or framework that tests your implementation. And those tests will call it more than once, with different arrays as argument, often including boundary cases, like an empty array, or a very large array.
So when you debug code, you would call the function and print the value that it returns, like so:
function reverse(array) {
const reversed = [];
for (let i = array.length - 1; i > -1; i--) {
reversed.push(array[i]);
}
return reversed;
}
let result = reverse([1,2,3,4]);
console.log(result); // Should be [4,3,2,1]
result = reverse([1]);
console.log(result); // Should be [1]
result = reverse([]);
console.log(result); // Should be []
result = reverse(reverse([1,2,3,4])); // Reversing the result!
console.log(result); // Should be [1,2,3,4]
Maybe I should also mention that reverse is also a native method available for arrays. It will reverse the array itself instead of creating a new array (like above). If the purpose is to always create a new array, you can still make use of it: first create a copy of the given array, reverse the copy and return that:
function reverse(array) {
// The spread syntax creates a copy, and reverse is applied on the copy
return [...array].reverse();
}
let result = reverse([1,2,3,4]);
console.log(result); // Should be [4,3,2,1]
result = reverse([1]);
console.log(result); // Should be [1]
result = reverse([]);
console.log(result); // Should be []
result = reverse(reverse([1,2,3,4])); // Reversing the result!
console.log(result); // Should be [1,2,3,4]

Related

How do I assign my .reduce function output to a variable?

Given an object and a key, getElementsThatEqual10AtProperty returns an array containing all the elements of the array located at the given key that are equal to ten.
I want to assign what my .reduce method outputs to a variable then use that variable inside my if statement. My code evaluates to NaN.
function getElementsThatEqual10AtProperty(obj, key) {
var arrayTotal = 0;
obj[key].reduce(function(a,b){
arrayTotal = a + b;
});
if(arrayTotal === 10) {
return obj[key];
}
};
You're approaching reduce incorrectly. You're almost using it like Array#forEach. Remember that callbacks are functions. They expect to return an actual value.
When you read the docs, you'll see that reduce also needs an accumulator, that is an argument after the callback.
const sum = obj[key].reduce(function(a,b){
return a + b
}, 0)
Or if you want the newer and prettier version:
const sum = obj[key].reduce((a,b) => a + b, 0)
When you have a one liner, return is implicit, which means it's implied, as opposed to explicit.
The accumulator is what your value starts at while it totals up the values.
Array.reduce(callback, accumulator)

Confused about the `return` statement in javascript. Explanation needed

I posted a question not too long ago this morning regarding a kata that I was trying to solve. In that question, (found here if interested Kata Question) I needed to add a return statement to my function so that I would avoid the following error Value is not what was expected.
Now I have my second iteration of my kata solution to try out and here it is:
function isMerge(s, part1, part2) {
var pointer = 0
splitString = s.split('');
splitString.forEach(function(character) {
if (part1.includes(character) || part2.includes(character)) {
pointer++;
return true;
} else {
return false;
}
});
}
isMerge('codewars','cdw','oears')
I am still getting Value is not what was expected errors when I try to execute the code and this time I'm confused as to why in particular this happens.
For starters, taken from the MDN guide
The return statement ends function execution and specifies a value to be returned to the function caller.
expression
The expression to return. If omitted, undefined is returned instead.
Look at my if/else logic I am specifying a return true and return false condition in my forEach loop to see if all the chars from part1 and part2 are in the string. I am returning something so why is it that I have a Value is not what was expected?.
Second of all, by definition of the return statement, the function is supposed to stop when it reaches that keyword. However, when I place a console.log(character) in the logic, I can see on my console that all of the characters are being outputted so the function is not breaking at all when return true is executed. Why is that?
Third, I am confused as to when to use the return keyword in general. Consider these examples from the MDN docs for ForEach.
Example 1:
function logArrayElements(element, index, array) {
console.log('a[' + index + '] = ' + element);
}
// Notice that index 2 is skipped since there is no item at
// that position in the array.
[2, 5, , 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9
Example 2:
function Counter() {
this.sum = 0;
this.count = 0;
}
Counter.prototype.add = function(array) {
array.forEach(function(entry) {
this.sum += entry;
++this.count;
}, this);
// ^---- Note
};
var obj = new Counter();
obj.add([2, 5, 9]);
obj.count
// 3
obj.sum
// 16
Not a single return statement to in these examples.
Now look at this .every example.
function isBigEnough(element, index, array) {
return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough);
And finally, from my previous question, I need to add a second return statement like this to avoid the value error.
function isBigEnough(element, index, array) {
return element >= 10;
}
function whenToUseReturn(array) {
return array.every(isBigEnough);
}
whenToUseReturn([12, 5, 8, 130, 44]);
So....... in conclusion, for my original function that started this how am I supposed to exit the loop when I reach false and return it and likewise when all the characters are in the string, how do I return a 'cumulative' true and avoid a Value error. I hope this makes sense and I can clarify with edits to better illustrate my point.
I am returning something so why is it that I have a Value is not what was expected?.
The return statement returns from the callback you pass to forEach, not from isMerge. return statements don't cross function boundaries. isMerge doesn't contain a return statement, hence it returns undefined. If we rewrite the function slightly it might become clearer:
function doSomething(part1, part2) {
return function(character) {
if (part1.includes(character) || part2.includes(character)) {
return true;
} else {
return false;
}
}
}
function isMerge(s, part1, part2) {
splitString = s.split('');
splitString.forEach(doSomething(part1, part2));
}
isMerge('codewars','cdw','oears')
This is equivalent to your code. As you can see, there is no return statement in isMerge.
Not a single return statement to in these examples.
There are no return statements in the forEach examples because forEach doesn't do anything with the return value of the callback, so there is no point in returning anything.
forEach is just a different way to iterate over an array, but it doesn't produce a value like reduce or every.
how am I supposed to exit the loop when I reach false and return it and likewise when all the characters are in the string, how do I return a 'cumulative' true and avoid a Value error.
You cannot exit a forEach "loop". If you have to stop the iteration early, you need to use a normal for (for/in, for/of) loop.
To return and produce a value, you can use your original solution that uses every.
My friend, since you decided to go the "callback way" using .each and the like, you should consider using callbacks, since you cannot return anything in this case. If you do not wish to go the callback way, just use standard javascript, such as:
splitString.forEach(function(character) {
Replace with
for(var i = 0 ; i < splitString.length; i++){
And now you can return. Using "each" to loop an array is just plain unnecessary and prevents you to return.

Checking for collisions using filter()?

Normally I don't have too much trouble figuring out a problem in JS but this time I really need some help understanding this block of code. Mary Rose Cook used this logic in her space invaders game to filter through the bodies array to find collisions with other bodies.
var bodies = [];
...
update: function () {
// bodies is an array of all bodies in the game
var bodies = this.bodies;
var notCollidingWithAnything = function (b1) {
return bodies.filter(function(b2) { return colliding(b1, b2); }).length === 0;
};
this.bodies = this.bodies.filter(notCollidingWithAnything)
// ...insert function to draw the bodies that are in the new bodies array...
}
Can someone please explain how this.bodies.filter(notCollidingWIthAnything) works without passing in any parameters to the argument function? How does the the compiler know to check each element of the array against each other element of the array? Please guide me through what exactly happens in the compiler so that I can understand this.
Can someone please explain how this.bodies.filter(notCollidingWIthAnything) works without passing in any parameters to the argument function? How does the the compiler know to check each element of the array against each other element of the array?
The compiler (well, the JavaScript engine) doesn't know how to call notCollidingWIthAnything with the elements; Array#filter does.
notCollidingWIthAnything is a reference to the function. (Functions are proper objects in JavaScript, so we have references to them just like we have references to other objects.) The code passes that reference into Array#filter, and then Array#filter calls that function once for each element in the array, passing in the element value (and index, and array; it passes three args although we usually only use the first). Then it uses the return value of the callback to decide whether to include the element in the new array it builds.
Here's simplified code for Array#filter so you can see what's going on:
function arrayFilter(callback) {
// Remember this is called with `this` referring to an array-like object
// Create a new, empty array for the result
var result = [];
// Loop through the items
for (var index = 0; index < this.length; ++index) {
// Get the value for this entry
var value = this[index];
// Call the callback
if (callback(value, index, this)) {
// Got a truthy return value, include the value in the result
result.push(value);
}
}
// Return the new array
return result;
}
Again, that's simplified, not perfectly correct; for the perfectly correct steps, see the algorithm in the spec.
Here's an example with logging showing exactly who's doing what:
function arrayFilter(callback) {
console.log("Starting arrayFilter");
var result = [];
for (var index = 0; index < this.length; ++index) {
var value = this[index];
console.log("arrayFilter calling callback with value " + value);
if (callback(value, index, this)) {
console.log("arrayFilter got truthy result, include the value");
result.push(value);
} else {
console.log("arrayFilter got falsy result, don't include the value");
}
}
console.log("arrayFilter done");
return result;
}
function isOdd(value) {
var retval = value % 2 == 1;
console.log("isOdd called with " + value + ", returning " + retval);
return retval;
}
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log("calling `arrayFilter` with `a` as `this`, using `isOdd` callback");
var odds = arrayFilter.call(a, isOdd);
console.log("Resulting array: ", odds);

Check if a function takes an array or single valued input

I am attempting to write a function that takes an array and another function as an input. The only thing I know about the supplied function though is that it either
takes a single number argument and returns a new number or
takes an array of numbers and returns a new array of numbers.
In my function, I want to check whether it's the first or second case to determine whether or not to call the supplied function with Array.prototype.map().
So with these two functions...
var unknownFunction = function( unknownInput ) {
//Does stuff with input
//returns number or array of numbers...
return someValueOrValues
}
and
var mainFunction = function( anArray, preFunction ){
// SOME CODE TO CHECK IF ARG NEEDS TO BE NUMBER OR ARRAY
// ...
// ...
**ANSWER WOULD FIT HERE**
if( argIsNumber === true ){
// function takes NUMBER
anArray = anArray.map( preFunction )
}else{
// function takes ARRAY
anArray = preFunction(anArray)
}
// DO STUFF WITH ARRAY AFTER USER FUNCTION HAS MADE IT'S MODIFICATIONS
// ...
// ...
// ...
return anArray;
}
is there any way to poke inside the first function to figure out how best to call it?
Since JavaScript is a dynamically-typed language, function's input parameters have type once some calls it with some argument.
One elegant and possible approach is adding a property to the whole given function to hint the input parameter type:
var func = function() {};
func.type = "number"; // a function decorator
var mainFunction = function(anArray, inputFunc) {
if(typeof inputFunc != "function") {
throw Error("Please supply a function as 'inputFunc'!");
}
switch(inputFunc.type) {
case "number":
return anArray.map(preFunction);
case "array":
return preFunction(anArray);
default:
throw Error("Type not supported");
}
};
mainFunction([1,2,3], func);
When you work with dynamically-typed languages you need to think about coding using convention over configuration and/or using duck typing. Type safety provided by strongly-typed languages is replaced by a good documentation.
For example:
Provide a function as second parameter with a type property to tell
the mainFunction what's the expected type of the predicate
function.
I would use the try-catch approach but test the actual functions, and if one fails to try the next one.
Let's say these are your functions that are passed in as your unknow function. They each only modify a number by adding 1 to it.
function onlyTakesNumber(num) {
return num + 1;
}
function onlyTakesArray(arr) {
return arr.map(num => num + 1);
}
Now, here is your main function. The reason for the additional map inside of the try is to test to make sure you didn't get a string back if an array was passed to the onlyTakesNumber function. The additional test map will again reveal if the code needs to hop into the catch.
var mainFunction = function (anArray, preFunction) {
try {
// the map on the end checks to make sure you did not get a string back
anArray = preFunction(anArray).map(test => test);
}
catch (e) {
anArray = anArray.map(preFunction);
}
// Do whatever else with anArray
return anArray;
};
console.log(mainFunction([1, 2, 3], onlyTakesArray)); // [2, 3, 4]
console.log(mainFunction([7, 8, 9], onlyTakesNumber)); // [8, 9, 10]
Here is a JSFiddle you can test this on
The shortest answer is: "you can't".

What is the meaning of check for this.length into a function?

I'm following an online course about Javascript Functional Programming
at the Exercise 16 it show you how reduce is actually implemented, in order to help you understand how to use it, but into this implementation there is something i don't actually get, i'll show the code:
Array.prototype.reduce = function(combiner, initialValue) {
var counter, accumulatedValue;
// If the array is empty, do nothing
if (this.length === 0) {
return this;
}
else {
// If the user didn't pass an initial value, use the first item.
if (arguments.length === 1) {
counter = 1;
accumulatedValue = this[0];
}
else if (arguments.length >= 2) {
counter = 0;
accumulatedValue = initialValue;
}
else {
throw "Invalid arguments.";
}
// Loop through the array, feeding the current value and the result of
// the previous computation back into the combiner function until
// we've exhausted the entire array and are left with only one value.
while(counter < this.length) {
accumulatedValue = combiner(accumulatedValue, this[counter])
counter++;
}
return [accumulatedValue];
}
};
I don't understand the first if statement, when it check for this.length what this actually mean?
Take note this is different from the reduce in ES5, which returns an value instead of an Array, this is used just as a sample for the learning purpose.
Array.prototype.reduce = function(...
is saying, "create a function on the prototype of Array" - this means that the new reduce function will be callable on all arrays, eg:
[1, 2, 3].reduce(...
This means you can also call it on empty arrays, eg:
[].reduce(...
Building on the comment:
If the array is empty, do nothing
You're working on an array, and when the function is called, this is set to the array that reduce was called on. This implementation of reduce assumes that if that array is empty (ie this.length === 0), you can't logically reduce it any further - there's nothing to reduce, so you can return the same empty array.
As pointed out by #Alnitak in the comments, this implementation of reduce is flawed as compared to the specification. A different implementation is available on the MDN for polyfilling older browsers.

Categories