Javascript simple function returning undefined after result - javascript

That's the function:
function randomNum(n) {
const numbers = [1,2,3,4,5,6,7,8,9,10]
if(numbers.includes(n)) {
console.log('ok')
} else {
console.log('Choose a value between 1 and 10')
}
}
console.log(randomNum(5))
Sorry if it's a simple problem, but i can't figure it out, i'm kinda new to programing. The function is returning 'undefined' after 'ok' or 'Choose a value between 1 and 10'.

Instead of using console.log(<value>);, try using a return <value>; statement.
At the moment, your code runs the function randomNum, prints the result to the console, then prints the return value from the function. Without an explicit return statement, this return value is undefined.
I hope this helps!

Your function doesn't return anything, it only logs. To fix add return.
function randomNum(n) {
const numbers = [1,2,3,4,5,6,7,8,9,10]
if(numbers.includes(n)) {
return 'ok';
} else {
return 'Choose a value between 1 and 10';
}
}

Related

the if statement is not running and returning the string [duplicate]

I have a function:
function myfunction() {
if (a == 'stop') // How can I stop the function here?
}
Is there something like exit() in JavaScript?
You can just use return.
function myfunction() {
if(a == 'stop')
return;
}
This will send a return value of undefined to whatever called the function.
var x = myfunction();
console.log( x ); // console shows undefined
Of course, you can specify a different return value. Whatever value is returned will be logged to the console using the above example.
return false;
return true;
return "some string";
return 12345;
Apparently you can do this:
function myFunction() {myFunction:{
console.log('i get executed');
break myFunction;
console.log('i do not get executed');
}}
See block scopes through the use of a label: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label
I can't see any downsides yet. But it doesn't seem like a common use.
Derived this answer: JavaScript equivalent of PHP’s die
function myfunction() {
if(a == 'stop')
return false;
}
return false; is much better than just return;
This:
function myfunction()
{
if (a == 'stop') // How can I stop working of function here?
{
return;
}
}
Using a little different approach, you can use try catch, with throw statement.
function name() {
try {
...
//get out of here
if (a == 'stop')
throw "exit";
...
} catch (e) {
// TODO: handle exception
}
}
if you are looking for a script to avoid submitting form when some errors found, this method should work
function verifyData(){
if (document.MyForm.FormInput.value.length == "") {
alert("Write something!");
}
else {
document.MyForm.submit();
}
}
change the Submit Button type to "button"
<input value="Save" type="button" onClick="verifyData()">
hope this help.
Using a return will stop the function and return undefined, or the value that you specify with the return command.
function myfunction(){
if(a=="stop"){
//return undefined;
return; /** Or return "Hello" or any other value */
}
}
I think throw a new error is good approach to stop execution rather than just return or return false. For ex. I am validating a number of files that I only allow max five files for upload in separate function.
validateMaxNumber: function(length) {
if (5 >= length) {
// Continue execution
}
// Flash error message and stop execution
// Can't stop execution by return or return false statement;
let message = "No more than " + this.maxNumber + " File is allowed";
throw new Error(message);
}
But I am calling this function from main flow function as
handleFilesUpload() {
let files = document.getElementById("myFile").files;
this.validateMaxNumber(files.length);
}
In the above example I can't stop execution unless I throw new Error.Just return or return false only works if you are in main function of execution otherwise it doesn't work.
I dislike answering things that aren't a real solution...
...but when I encountered this same problem, I made below workaround:
function doThis() {
var err=0
if (cond1) { alert('ret1'); err=1; }
if (cond2) { alert('ret2'); err=1; }
if (cond3) { alert('ret3'); err=1; }
if (err < 1) {
// do the rest (or have it skipped)
}
}
Hope it can be useful for anyone.
If you are using jquery. This should stop the function from bubbling up to so the parent function calling this should stop as well.
function myfunction(e)
{
e.stopImmediatePropagation();
................
}
exit(); can be use to go for the next validation.
type any random command that throws an error, for example:
exit
or
die:-)

Closure returns what is supposed to and also undefined

I'm practicing closures and my assigment for now is to :
Write a function once that accepts a callback as input and returns a function.
When the returned function is called the first time, it should call the callback
and return that output. If it is called any additional times, instead of calling
the callback again it will simply return the output value from the first time it
was called.
My callback is:
const addByX = function (num1) {
let number = num1;
function adding(num2) {
console.log(number + num2);
}
return adding;
}
//addByX(2)(8);
let addByTwo = addByX(2);
And my main function is:
const once = function (func) {
let isFirst = true;
let firstOutput;
function inside(numberToPass) {
if (isFirst) {
firstOutput = func(numberToPass);
isFirst = false;
return func(numberToPass);
} else {
return firstOutput;
}
}
return inside;
}
It works, but when I invoke it
const onceFunc = once(addByTwo);
console.log(onceFunc(4)); //should log 6
console.log(onceFunc(10)); //should log 6
it returns my values and also undefined.
And I really can't understand why would it.
Maybe if it works I should not ask this kind of questions, but I'm really curious.
Debugger couldn't clearly answer my question.
I'm suspicious it has something to do with console.log, as abvious as it looks.
Here in JS Bin
The function addByX returns another function, adding. But adding doesn't return anything; it just logs. It's return value is undefined.
I think you intended it to look like this:
const addByX = function (num1) {
let number = num1;
function adding(num2) {
return number + num2;
}
return adding;
}
So the reason that it "worked" is because the callback was printing to the console, rather than where you are invoking it.

Writing recursive functions - Eloquent JS

I'm trying to write a function that checks if a number "N" is even or odd by subtracting 2 until it gets to 1 or 0. A final value of 0 represents even. The goal here is to use a recursive function to reach the final result, but I'm having some issues where all I have returned are undefined.
This is what I have so far.
function isEven(number) {
function subTwo(number) {
if (number == 0) {
return true;
}
else if (number == 1) {
return false;
}
else if (number > 0) {
number -= 2;
subTwo();
}
else {
console.log("bruh");
}
};
};
console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-1));
// → ??
Does anyone see what I'm doing wrong or have any advice for me?
Thanks.
EDIT:
Thanks for the help guys. It was suggested that I remove subTwo completely and use isEven as the recursive function, and that I had to use return isEven(number) within the second if/else statement.
Both of those suggestions together helped the code compile correctly.
Thanks a ton guys, although I'm not sure why I got downvoted lol.
Your problem is here:
subTwo();
You need to pass the current version of number into it: subTwo(number); and return it.
you could also fix the problem by omitting the parameter in the internal function, like so: function subTwo(){...} The internal function already has access to the parent function's parameter (closure), so you don't need to pass that into the internal one.
also, this is not returning anything, it's just logging. JavaScript always returns something. If you don't say return "something", it returns undefined.
else {
console.log("bruh");
}
Personally, I would also rework you code like so:
function subTwo(number) {
if (number > 0) {
number -= 2;
subTwo();
}
else if (number == 1) {
return false;
}
else if (number == 0) {
return true;
}
else {
console.log("bruh");
}
};
The statements are then in descending order, so you can quickly see the progression. It helps people look and see if anything has been missed.
The problem is that you define the function subTwo but it's never actually called when isEven is called. A simpler version would be to not even have another function and do it all with recursive calls of isEven
function isEven(number) {
if (number === 0) {
return true;
} else if (number === 1) {
return false;
} else {
return isEven(number - 2)
}
}
EDIT
Alternatively, if you really want the additional function, notice that you defined subTwo to take in a parameter but you did not pass in the parameter when recursively calling it via subTwo();. Also, when you recursively call subTwo(number), make sure you actually have return subTwo(number) so the value is returned at each recursive call. Additionally, you need to actually call the function and return the result when isEven(number) is called via a return statement and wrapping the function in brackets and calling it with number or manually calling it using return subTwo(number). See below for an example of how you would return at each stage so it passes it all the back up to the original call of isEven(number):
function isEven(number) {
return (function subTwo(number) {
if (number === 0) {
return true;
}
else if (number === 1) {
return false;
}
else if (number > 0) {
number -= 2;
return subTwo(number);
}
else {
console.log("bruh");
}
})(number);
};
As was said in the comments you never check for a value less than 0. What happens is when you enter the value -1 is it jumps down to the else part of your code. The part that says "console.log("bruh");" After completing that line the program keeps going and returns... nothing. You dont return anything, hence why you get undefined. You should set up your code to handle the case when a negative number is passed in.

Javascript scope issue on return function

I've created a function into backbone view that return true or false under some condition.
The issue is that the return value is evere undefined. I think it is a scope problem.
This issue is different from Ajax return because my return is inside an iteration and not in an ajx call. The previous Ajax call in my code is sync and not async.The console.log inside my iteration is correctly printed, only return statement seems doesn't work.
isAlreadyRegistered: function(){
this.checkUser = new Utenti();
this.checkUser.fetch({async:false});
_.each(this.checkUser.models, function (user) {
if(user.get("idTwitter") === this.utente.get('idTwitter')){
console.log("gia reg");
return true;
} else {
console.log("non reg");
return false;
}
}, this);
}
console.log(isAlreadyRegistered());//ever undefined
You don't want to use each, but every or some. They will return booleans depending on what your callback invocations did return.
isAlreadyRegistered: function(){
this.checkUser = new Utenti();
this.checkUser.fetch({async:false});
var id = this.utente.get('idTwitter');
return _.some(this.checkUser.models, function (user) {
return user.get("idTwitter") === id;
});
}

Early exit from function?

I have a function:
function myfunction() {
if (a == 'stop') // How can I stop the function here?
}
Is there something like exit() in JavaScript?
You can just use return.
function myfunction() {
if(a == 'stop')
return;
}
This will send a return value of undefined to whatever called the function.
var x = myfunction();
console.log( x ); // console shows undefined
Of course, you can specify a different return value. Whatever value is returned will be logged to the console using the above example.
return false;
return true;
return "some string";
return 12345;
Apparently you can do this:
function myFunction() {myFunction:{
console.log('i get executed');
break myFunction;
console.log('i do not get executed');
}}
See block scopes through the use of a label: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label
I can't see any downsides yet. But it doesn't seem like a common use.
Derived this answer: JavaScript equivalent of PHP’s die
function myfunction() {
if(a == 'stop')
return false;
}
return false; is much better than just return;
This:
function myfunction()
{
if (a == 'stop') // How can I stop working of function here?
{
return;
}
}
Using a little different approach, you can use try catch, with throw statement.
function name() {
try {
...
//get out of here
if (a == 'stop')
throw "exit";
...
} catch (e) {
// TODO: handle exception
}
}
if you are looking for a script to avoid submitting form when some errors found, this method should work
function verifyData(){
if (document.MyForm.FormInput.value.length == "") {
alert("Write something!");
}
else {
document.MyForm.submit();
}
}
change the Submit Button type to "button"
<input value="Save" type="button" onClick="verifyData()">
hope this help.
Using a return will stop the function and return undefined, or the value that you specify with the return command.
function myfunction(){
if(a=="stop"){
//return undefined;
return; /** Or return "Hello" or any other value */
}
}
I think throw a new error is good approach to stop execution rather than just return or return false. For ex. I am validating a number of files that I only allow max five files for upload in separate function.
validateMaxNumber: function(length) {
if (5 >= length) {
// Continue execution
}
// Flash error message and stop execution
// Can't stop execution by return or return false statement;
let message = "No more than " + this.maxNumber + " File is allowed";
throw new Error(message);
}
But I am calling this function from main flow function as
handleFilesUpload() {
let files = document.getElementById("myFile").files;
this.validateMaxNumber(files.length);
}
In the above example I can't stop execution unless I throw new Error.Just return or return false only works if you are in main function of execution otherwise it doesn't work.
I dislike answering things that aren't a real solution...
...but when I encountered this same problem, I made below workaround:
function doThis() {
var err=0
if (cond1) { alert('ret1'); err=1; }
if (cond2) { alert('ret2'); err=1; }
if (cond3) { alert('ret3'); err=1; }
if (err < 1) {
// do the rest (or have it skipped)
}
}
Hope it can be useful for anyone.
If you are using jquery. This should stop the function from bubbling up to so the parent function calling this should stop as well.
function myfunction(e)
{
e.stopImmediatePropagation();
................
}
exit(); can be use to go for the next validation.
type any random command that throws an error, for example:
exit
or
die:-)

Categories

Resources