If statements in javascript, which is better? [duplicate] - javascript

This question already has answers here:
Is returning early from a function more elegant than an if statement?
(14 answers)
Is it good style (or more efficient) to "return early" at the top of a function?
(2 answers)
Invert "if" statement to reduce nesting
(25 answers)
Closed 3 years ago.
When writing javascript or PHP for that matter I use two ways to write if statements.
Return as soon as possible
Below I try to end the function as soon as possible. If the value is not what I expect, return it. The benefit I see here is that I don't need {} and I don't need to nest anything.
function hello(value = null) {
if(!value) return;
console.log("I'm still here!");
console.log("End of function");
}
Do something on match
In this case I don't return at all. Instead I do something if I get a "match". The upside here is that I don't need to return anything.
function hello(value = null) {
if(value) {
console.log("I'm still here!");
console.log("End of function");
}
}
So which is better? One of them or equally good?

Related

Javascript recursive function seemingly working but returning 'undefined' object [duplicate]

This question already has answers here:
Recursive function returns undefined
(3 answers)
Function with forEach returns undefined even with return statement
(5 answers)
Closed 7 months ago.
I wrote a recursive function such as:
Note : you might not need to understand the nuts and bolts to help as it already looks like it does what I want
const rec = (arg_array, an_array, condition_state_out, state = 0) => {
if (state < condition_state_out) {
an_array.forEach((ele) => {
an_array.shift();
return rec([...arg_array, ele], an_array, condition_state_out, state + 1);
});
} else {
console.log(arg_array);
return arg_array;
}
};
When I run it,
const returned = rec([], an_array, condition_state_out, 0)
through the log, I see that it builds exactly what I want, so it is seemingly correct.
But when I check the returned object
console.log(returned)
It is undefined
I really can't figure out what is wrong as the complex part looks like it is working...
Many thanks for any help

How to use a local variable in javascript function [duplicate]

This question already has answers here:
Javascript: Object Literal reference in own key's function instead of 'this'
(5 answers)
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 1 year ago.
Apologies if the terminology is off - javascript isn't my thing.
I have a function:
var input = {
getVal: function () {
return $(this).attr("data-current-val");
},
setVal: function () {
$(this).attr("data-current-val", $(this).val());
},
valHasChanged: function () {
return $(this).val() !== $(this).attr("data-current-val");
}
};
As you can see there is some repetition. Firstly, I repeat the data attribute name several times; secondly, I select a jquery object numerous times.
I've tried to remove the repetition. For instance, in respect of the data attribute, by adding node: "data-current-val" at the top and then calling it with this.node in place of the string. That causes an error, as does trying to define and then use the jquery objectin the same way.
Similarly part of the boolean in valHasChanged $(this).attr("data-current-val"), logically could be replaced by this.getVal but that doesn't seem to work either. Where am I going wrong?!
Any help appreciated.

Two javascript functions not working as same way [duplicate]

This question already has answers here:
What are the rules for JavaScript's automatic semicolon insertion (ASI)?
(7 answers)
Closed 6 years ago.
I have written 2 javascript function but they are not working as same.
console.log(func2()); is undefined. Can anyone tell me why and how to solve this?
function func1()
{
return {
bar: "hello"
};
}
function func2()
{
return
{
bar: "hello"
};
}
console.log(func1());
console.log(func2());
It's because of automatic semicolon insertion. Never put a newline after return and prior to what you want to return, it's treated as though it terminates the return statement (e.g., a ; is inserted after return), and your function ends up effectively returning undefined.
I know this one. It's semicolon insertion. func2 is translated to
function func2()
{
return;
{
bar: "hello"
};
}
And return undefine.

Avoid using functions inside if condition - Javascript [duplicate]

This question already has answers here:
Function declarations should not be placed in blocks. Use a function expression or move the statement to the top of the outer function
(2 answers)
Closed 6 years ago.
Why should we avoid call functions inside if conditions in functions? For instance:
var numberChoice = function(number){
if (number == 1){
alert("You have choosen 1");
nextLevel();
}
else if(number == 2){
alert ("You have choosen 2");
nextLevel2();
}
else{
alert("Please choose a number within range 1-2");
guessAgain();
}
};
var number = prompt("What is your number?");
I could possible have missunderstood what's going on. Are you able to give an explanation of it?
function example(){
function a() {} // Okay
if (something) {
function b() {} // Danger!
}
}
Haverbeke, Marijn (2014-12-04). Eloquent JavaScript: A Modern Introduction to Programming (Kindle Locations 1168-1169). No Starch Press. Kindle Edition.
Unless your function (within if condition) is asynchronous there is no problem.
The functions that you are using is synchronous - meaning your script will finish executing it and return a value first before going to next task - in this case it will work fine.
For asynchronous function (which is executed in parallel to the other lines of instructions), then the results from that function is not returned yet and your script will continue without the right value (returned value) from it - this will cause problem.
In your two sample there is no issue.
there is no rule that don't allow you to call function in a if condition.
the only point is a warning when you have several if on the same checking :
if (number === 1) {
function1();
}
if (number === 2 ) {
function2();
}
in that case if you don't put return at the end of your function when the function will be called other condition will be evaluate.
better code is using else or switch
In your case there are no issue.

Return statement not stopping function [duplicate]

This question already has answers here:
Javascript function fails to return element
(2 answers)
Closed 8 years ago.
I'm sure this is a noob issue but I'm a little confused. My understanding is that when a return statement is reached it should stop the function, however in the example below it doesn't seem to. Would someone please explain what's going on?
Fiddle
var hasTerm = function(obj,term){
$.each(jsonObject,function(key, value){
if (value == term){
console.log("conditional");
return true;
console.log("conditional after return");
};
if(typeof value == (Object || array)){
hasTerm(value,term);
}
});
return false;
}
The $.each is looping through all of the object collections passed in "jsonObject". Likely it is stopping on an object and then restarting on the next object. Does the console window ever show "conditional after return"?
Use "return false" to stop the iteration.

Categories

Resources