If/Else Statement Not Evaluating - javascript

I have a little helper function that is not evaluating on either the If or Else.
I know the function is being called because I have the nlapiLogExecution, which is how you debug in NetSuite. Notes on what is being logged are with the code.
How is this possible? I have tried to use == operator as well. I also tried to set it as a variable inside the function (which I don't think is necessary).
function convertUnit(unit, cubicMeters){
nlapiLogExecution('DEBUG','convertUnitFunction',typeof(unit))
// typeof is String
nlapiLogExecution('DEBUG','convertUnitFunction',unit)
// value is Each
if (unit === 'Each'){
return cubicMeters
nlapiLogExecution('DEBUG','equals Each', cubicMeters)
// does not log here
}
else {
nlapiLogExecution('DEBUG','else statements', 'equals else')
// Does not log here
}
}

You are entering the if statement, but the function returns before you can log anything. Try switching the order of the return and log statements:
function convertUnit(unit, cubicMeters){
nlapiLogExecution('DEBUG','convertUnitFunction',typeof(unit))
// typeof is String
nlapiLogExecution('DEBUG','convertUnitFunction',unit)
// value is Each
if (unit === 'Each'){
nlapiLogExecution('DEBUG','equals Each', cubicMeters)
// will log something now if you pass 'Each'
return cubicMeters
}
else {
nlapiLogExecution('DEBUG','else statements', 'equals else')
// will log something if the else branch is taken
}
}

You are returning before it gets to the nlapiLogExecution in the 'Each' section. Not sure why it isn't running on the else though, unless you are only passing 'Each'

Related

How to exit or break out from an else if

I've searched for a couple stackoverflow questions although couldn't find my answer.
I'm trying to break from an else if statement and was wondering if there was a more efficient way.
Heres a snippet:
var argument = "something";
if(argument == 'not_this'){
// this doesn't trigger
} else if(argument){
// this triggers although if the functions in here doesn't match what I want,
// how do I make It skip to the else statement without adding another else
// if statement?
} else {
// do something if both statements above fail
}
Is there something that I can do which exits from the else if(argument)... without adding another else statement? I've tried using switch and case although those don't seem to help.
Thanks.
You could set a flag that is by default true, and whenever the argument is valid you set it to false.
Then, to know when to execute the 'else' block, you can just check whether the flag is true or not:
var argument = "something";
let invalid = true
if (argument == 'not_this') {
// this doesn't trigger
invalid = false
} else if (argument) {
if (typeof argument != 'string') {
//valid
invalid = false
}
}
if (invalid) {
console.log('invalid')
}
Restructure the code to avoid confusing states, move out the if 'has value' check.
if (argument) {
if (argument === 'not_this') {
// this doesn't trigger
}
} else {
// do something if both statements above fail
}
For equality, it is safer to use strict equal === instead of loose equal ==
You could try using return; to break out of the statement, as that would stop all other code from being read.

Why is my prototype method returning undefined?

I have created a prototype method that return true and false. The problem is that it doesn't return the value. I know it reaches the statement because I have used console.log() when the condition is met but doesn't return the value.
I cant seem to figure this out. If anyone can help me out here I would really appreciate it. Below is my code
function Validation(){
this.checkRequired = function(){
$(".modifiers-group-cont").each(function(){
var select_opt_notify = $(this).find(".select-option-notify");
/*The radio buttons that are required are always going to be marked check,thats why we are only
* checking for the checkbox*/
if($(this).attr("data-is-checked") == "false" && $(this).attr("data-input-type") == "checkbox"){
select_opt_notify.show();
return false;
} else {
select_opt_notify.hide();
return "true";
}
});
}
function ModifierPost(){
(function(){
$("#add-to-cart").click(function(){
console.log(validation.constructor); //Shows undefined
if(validation.checkRequired()){
$.post("#",$("form").serialize()+ "&item_id=" + item_id);
}
});
})();
}
The return statements belong to the function in each:
$(".modifiers-group-cont").each(function(){
You'll need to expose the values you'd like to return to the outer scope and call return after the call to each.
You have created your function with Capital V and calling with Smaill v in the validation function name
That is the reason it is giving you undefined the place you have mentioned in your code.
console.log(validation.constructor); //Shows undefined
if(validation.checkRequired()){
it should be with Capital V like
console.log(Validation.constructor); //Shows undefined
if(Validation.checkRequired()){

What is the point of the return in Javascript?

I've recently been learning javascript and came across the return statement or whatever it is. I've watched tutorials on it and I still don't get the point of it. Do I ever need it for anything and can someone please explain in detail what it does? Thanks
The return statement has multiple uses:
1) Return early from your function before the end of the function body. This is often within a branch of the code as in:
function whatever()
// do some things
if (err) {
console.log(err);
return err;
}
// other code here that will not execute if there was an err
}
2) Return a specific value back to the caller as in:
function add(a, b) {
return a + b;
}
var sum = add(3,4);
console.log(sum); // will show 7
The return statement in javascript can be used by itself to just exit the current function call and not return a specific value or it can be used to return a specific value.
If no return statement is present in a function, then the function will execute to the end of the function body and will return automatically at the end of the function body.
The only point of it is to send a value (string, number, or other values) from your function so that is can be used outside the function. Instead you can use global variables but that takes up more code, so it's a shortcut instead.
jfreind00 above said that you can use it to branch off early but that's what break. Here is the syntax:
function HiThere(something) {
if (something === true) {
break;
}
alert("Hi");
}
In this case, if something is true, then exit the function, if not then say hi.
Return would be like this:
function HiThere(something) {
if (something === true) {
return "Value to return: " + something;
}
alert("Hi");
}
In this case, if something is true, then exit the function and return Value to return: true, if not then say hi but don't return anything back.
Here's the most common use of the return statement:
document.getElementById("demo").innerHTML = myFunction(5,3); // Call a function
// to set the "demo" element to the value of: 5 * 3
function myFunction(a,b) {
return a * b;
}
<p id="demo"></p>
Use it to return a value. Your value could be "Yes", "false", "hello world" or "eat dirt." You can then run certain code based on the returned value.
Hope this helps!

JSON crawler function returning undefined

I have a recursive JSON crawler function that looks for a specified function then returns it. However, it is returning undefined and I am not sure why.
Here is the script:
function get(what, where){
where = typeof(where) != 'undefined' ? where : user.object;
for(entry in where){
if(typeof(where[entry]) =="string"){
if (entry == what) {
result = where[entry];
console.log(result)
return result;
}
}else if(typeof(where[entry]) =="object"){
get(what, where[entry]);
}
}
}
the console.log returns correctly but the return statement below it fails.
It's because you're not returning your recursive branch of the code, this:
get(what, where[entry]);
should be:
return get(what, where[entry]);
So on that branch, though you're executing all the way down, you're not returning the result back up, so you get the default return: undefined.
If you dont write a return-statement in a JavaScript function, but it reaches its end anyway, then it returns undefined. That is (probably) what has happened here, since if you dont enter the if-statement with the return-statement, you will not get to return anything.
EDIT:
As a rule of thumb, you should ALWAYS return something in every bransch of your code. A static language compiler would have warned you about this, but here you have to make sure yourself.
Example:
function get(what, where){
where = typeof(where) != 'undefined' ? where : user.object;
for(entry in where){
if(typeof(where[entry]) =="string"){
if (entry == what) {
result = where[entry];
console.log(result)
return result;
}
}else if(typeof(where[entry]) =="object"){
get(what, where[entry]);
// Are you sure you don't want to return anything here?.. hm...
}
}
// Here be dragons! What will be returned from the function?
// Hint: Undefined! :)
}
Both those places could probably use return statements. The last one need one because what if the for-loop doesn't have any entries to enumerate over?
You probably want to modify the code:
get(what, where[entry]);
to
return get(what, where[entry]);
:-P

Is there a benefit to using a return statement that returns nothing?

I'm refactoring a large javascript document that I picked up from an open source project. A number of functions use inconsistent return statements. Here's a simple example of what I mean:
var func = function(param) {
if (!param) {
return;
}
// do stuff
return true;
}
Sometimes the functions return boolean, sometimes strings or other things. Usually they are inconsistently paired with a simple return; statement inside of a conditional.
The problem is that the code is complex. It is a parser that uses a multitude of unique RegEx matches, creates and destroys DOM nodes on the fly, etc. Preliminary testing shows that, in the above example, I could change the return; statement to become return false;, but I'm concerned that I may not realize that it had a negative impact (i.e. some feature stopped working) on the script until much later.
So my questions: Is there a benefit to using a blank return statement? Could this have been intentionally coded this way or was it just lazy? Can I change them all to return false;, or return null; or do I need to dig through every call and find out what they are doing with the results of those functions?
Using return without a value will return the value undefined.
If the value is evaluated as a boolean, undefined will work as false, but if the value for example is compared to false, you will get a different behaviour:
var x; // x is undefined
alert(x); // shows "undefined"
alert(!x); // shows "true"
alert(x==false); // shows "false"
So, while the code should logically return true or false, not true or undefined, you can't just change return; to return false; without checking how the return value is used.
"Blank return" statements can be used to transfer the control back to the calling function (or stop executing a function for some reason - ex: validations etc). In most cases I use blank return statement is when I'm doing some kind of a validation. However, I make it a point to set some indicator as to why the execution of the function is stopped. For example, set the "innerText" property on a DIV element with the error message.
In the code above, it looks like it is a validation. The function returns a "true" if everything went well. It looks like the calling function parses the return value, and if it is "true", next step of statements (in the calling function) are executed.
It is a good practice to return "false" instead of a blank return in the above example. That way you make it all uniform and make life easy for other programmers.
You could fix such inconsistencies; however, make sure you test all the changes thoroughly. It is a good practice to test each change you make to the code, however small it may be.
There is no difference at all between return; and return undefined;. The result of calling both functions is to receive the value undefined.
(There's a very small specification-level difference between a function body that terminates with return vs. just falling off the end of the code, but it's nothing that can be detected in code.¹ Calling a function where execution falls off the end of the code also results in the value undefined.)
"use strict";
// Implicit return of `undefined`
function x() {
return;
}
// Explicit return of `undefined`
function y() {
return undefined;
}
// Execution falls off the end
function z() {
}
console.log(typeof x() === "undefined"); // true
console.log(typeof y() === "undefined"); // true
console.log(typeof z() === "undefined"); // true
Unless, of course, something has shadowed undefined. Which is still sadly possible (though not, gladly, at global scope). In that very edgy edge case, there's a difference:
"use strict";
(function() {
const undefined = 42;
// ^^^^^^^^^^^^^^^---- shadowing `undefined`
// Implicit return of `undefined`
function x() {
return;
}
// Explicit return of `undefined`
function y() {
return undefined;
}
// Execution falls off the end
function z() {
}
console.log(typeof x() === "undefined"); // true, `x` returns the canonical `undefined`
console.log(typeof y() === "undefined"); // false, `y` returns 42
console.log(typeof z() === "undefined"); // true, `z` (effectively) returns the canonical `undefined`
})();
¹ Using return is an abrupt completion that [[Call]] converts to a normal completion w/value. Falling off the end of the code is a normal completion (spec) (that [[Call]] ensures supplies undefined for the value). But again, this is a specification level difference, not something that's observable in code.
What MIGHT be lost here (not direct with your example) is that you can then have a tri-state object:
var myfunc = function(testparam) {
if (typeof testparam === 'undefined') return;
if (testparam) {
return true;
}
else {
return false;
}
};
var thefirst = myfunc(true)
var thesecond = myfunc(false);
var thelast = myfunc();
alert("type:" + typeof thefirst+" value:"+thefirst);
alert("type:" + typeof thesecond+" value:"+thesecond);
alert("type:" + typeof thelast+" value:"+thelast);
these return:
> type:boolean:true
> type:boolean:false
> type:undefined:undefined
note: null would return false in this example myfunc(null);
Changing your functions will actually alter the code because return; and return false; output different data types.
var test = function (x) {
if (!x) {
return;
}
else {
return false;
}
};
var a = test(true), b = test(false);
console.log(typeof b); // undefined
console.log(typeof a); // boolean

Categories