Correct Syntax For Using The Returned Variable From A Function? - javascript

I have a function that returns a variable, I'd just like to know what's the correct syntax for doing something (such as doing math or writing a new variable using that returned variable.
Example Function:
function exampleFunction(number) {
var data_filter = number + number;
return data_filter;
}
The function returns data_filter, and I'd like to know what's the correct syntax for doing something with it, such as inputting it in another function.

What you have here is fine.
As one of the comment suggests typically you assign the result to a variable. Take a simple example here:
let myNumber = 10;
let myHalvedNumber = halveNumber(myNumber);
console.log(myNumber)
console.log(myHalvedNumber);
function halveNumber(numberToHalve){
return numberToHalve/2;
}
The best way to think about it in practice is to treat the function/input combination { f(x) } as a proxy for the result itself. This means that both of these examples are correct and how you choose to employ it is your own preference.
//These two approaches are identical and both valid:
//1) Assign to a variable for further use - typically better for variable re-use:
let myHalvedNumber = halveNumber(10);
aSecondFunction(myHalvedNumber);
//2) Use the result directly in a second call - typically shorter and arguably easier to maintain/read
aSecondFunction(halveNumber(10));
function halveNumber(myNumber){
return myNumber/2;
}
function aSecondFunction (myNumber){
console.log("the number is: " + myNumber)
}

Related

assign value to function parameter, is it safe to reuse function arguments?

Is it a bad practice to reuse function parameter variables?
const reformat = (phone)=>{
phone = phone.replace("-", ",")
//... more operation using phone
return phone;
}
is there any reason such reusage should be avoided? or is it always safe to continue such usage?
For strings, like in your example, it's fine. Some people may think it could get confusing if you're trying to debug and log that variable to the console sometime after it's been changed, but that's mostly subjective. Use your best judgement.
For objects, which are always passed by reference, you should avoid making changes in the function because those changes will still be present outside the function as well.
E.G.:
var myObject = {
message: "Hello, world"
};
function alertMessage(msgObj){
msgObj.message = "Hello moto";
alert(msgObj.message);
}
alertMessage(myObject);
// The object has changed.
console.log(myObject);
No it's not. And it's memory saving sometimes, since when you use another new variable, it will take up your memory. And the function process is much longer many transformations then it will be not a good practice to do. So according to your questions,
Yes, you can use the same variable inside the function (But make sure to consider what are the types that you refer when passing as arguments)
Re-usage should be avoided when you are using a object and that will change the content of the origin object.
different cases to take care:
// argument is not a reference ( string, numbers )
function add_5(num)
{
num += 5
return num
}
let initial_num = 10
let returned_num = add_5(initial_num )
console.log( `initial_num-> ${initial_num}, returned_num-> ${returned_num}`)
// argument is reference ( objects )
function directArgObj( obj)
{
obj.num += 5
}
let initial_obj = { num: 10, abc:'xyz' }
directArgObj(initial_obj )
console.log( `initial_obj-> ${JSON.stringify(initial_obj)} `)

specify the result of a function in javascript

Am not sure if functions in javascript are what we call methods in other programming languages.Methods in other programming languages can have their result specified just after the access-specifier like in C# for example i would do like
//method to return int
private int myinteger(){
int a=0;
return a;
}
//method to return string
private string mystring(){
string b="myreturn";
return b;
}
I just don't know how to do that with javascript functions, you think you can help me with a sample?Thank You very much :)
You don't need to provide the data types in javascript. The functions are pretty similar you just have to start it with the function keyword.
Also, we need to start the variables with const or let.
I use the console.log(myinteger()); below to log the value of the myinteger() function in the browser console. (Similar to c++'s cout)
//method to return int
function myinteger() {
const a = 0;
return a;
}
//method to return string
function mystring() {
const b = "myreturn";
return b;
}
console.log(myinteger());
console.log(mystring());
If you are someone who wants to use javascript but still want to assign the data type and many more thing then you can use TypeScript By Microsoft.
You cannot do this with javascript, but you still have two workarounds available:
Use eslint and use the https://eslint.org/docs/rules/consistent-return rule
Use typescript
Javascript has types for values (not variables)
so you can define a variable as
var name = "Hamond";
and to know it's type you have to use typeof
typeof name; // "string"
Side note: you can use let or const instead of var but let that be for another time.
so variables in javascript doesn't have types, values have.
You can add static typing using typescript so
var name: string = "Hamond";
and at dev time if you wanted to edit name and incorrectly deal with it as a non string type you will get an error
warning you immediately
name = 3; // error
name - 4; // error
// and so forth because `name` is of `string` type
so this type check is done at author or dev time and you don't have to wait until run time to get the error.
Why all the talk about variables and values?
Because Javascript function can return any value(even returning a variable is basically returning its value if it's scalar value or its reference if it's an object type)
so defining a function look like:
function doSomething(){
return 33;
}
notes:
no return type
can have no return statement(by default will return undefined)
with typescript
function doSomething(): number{
return 33;
}
typing problems solved at dev/write time
About function vs method:
I think developers in many times use these terms interchangeably, but in javascript we just have function, even a function defined inside a class in javascript is just a function. People like the name method when its defined inside some class.
references:
JS syntax
The Nature Of Functions

Is it good practice to override function parameter value?

In JavaScript consider I am trying to append a new value and return it.
I have below example regarding overriding parameter value
The below function receives a string value as param and overriding the param with new value and returning it.
function test(value) {
value = value + "hi";
return value;
}
console.log(test("Hello"));
The below function receives a string value as param. I would like to append a new value and return it. So I assigned value to a local variable and then appended strong to a new variable and returning it.
function test(value) {
let temp = value;
temp = value + "hi";
return temp;
}
console.log(test("Hello"));
I am calling it and passing value
test(“Hello”);
Which one is recommended from above?
It's purely a matter of style. Some people think you should leave parameter values alone, others think it's fine to change them.¹
From a practical perspective, it doesn't cause any harm. That is, there is no hidden side-effect to doing so. In particular, since JavaScript is purely pass-by-value, reassigning the parameter can't have any effect on whatever argument was used to fill in that parameter:
function test(value) {
value = value + "hi";
return value;
}
let a = "let's say ";
let b = test(a);
console.log(b); // "let's say hi"
console.log(a === b); // false, `a` was not modified
Your version with temp can be simpler, though:
function test(value) {
let temp = value + "hi";
return temp;
}
(or even
function test(value) {
return value + "hi";
}
but I figure it's highly simplified for the question.)
¹ (I happen to be in the latter camp, but that's neither here nor there.)
Yes, this is not at all wrong and is often done by many programmers across many languages. It is a common practice.
You can use it in cases where you want to use the parameter value inside the function but after making certain modifications to it.
For example, I might want to add two numbers using a function add(a, b) where a and b can be strings or integers or floats.
But just to be sure about it, I can define the add function in the following way:
function add(a,b) {
a = parseFloat(a);
b = parseFloat(b);
return a + b;
}
and this is perfectly fine. This way I can be always sure that there will be no exceptions thrown or in case parameters were passed as strings, it doesn't returns 12 (if I said add(1,2)) when really it should have been 3.
By making parameter overriding a common practice and incorporating it into your coding style, you spare the browser from creating or defining new variables just to modify those variable values. This might not mean much in small applications, but in large scale heavy applications, it might make a noticeable difference especially on low end devices.
The short answer is: it's only a matter of style.
However, this isn't always right. When passing objects, they will be passed by reference, meaning that every change you'll make to the parameter will affect the original object:
const obj = {originalValue: true};
function modifyObject(input) {
input.originalValue = false; // The change happens here
return input; // So it will take place regardless of this line
}
console.log('before:', obj);
modifyObject(obj); // See? we don't even retrieve the return value
console.log('after:', obj);
If we were talking about Java, then creating a new variable would be good practice. As there is something called the Garbage Collector that collects unused variables, etc. and discards them. So keeping a link to the original variable wouldn't allow the collector to discard the variable. (I read this somewhere, but some people said to me it doesn't really work this way, so read more about this online if you want)
In JavaScript, however, it doesn't really matter. It depends on you. Your style. It also depends on the situation as it can be useful sometimes. But really it doesn't really matter. Do as you like.
If you want to simplify it you can do as #T.JCrowder said:
function test(value){
return value+ “hi”;
}
That's about it.
Using ES6 Template literals
function test(value){
return `${value} hi`;
}

Trying to understand this function as value

I got this code from the Headfirst Javascript book. I changed the function names to be clearer. I'm trying to wrap my head around this.
I assigned add to the function outer with a number. That number remains for some reason - returns a reference to inner with n = num (which returns the added values?
Anytime I change outers n value, the inner will use that new value?
I believe I'm right on that. Is there anywhere I can read more about it? See better examples? Or can anyone explain this better?
function outer(n) {
var inner = function(x) { //or x = 0
return n + (x || 0); //added default 0 for testing to prevent NaN
}
return inner;
}
var num = 2;
var add = outer(num);
console.log(`Adding 2 to num(${num}): ${add(2)}`);
add = outer(5);
console.log(add());
console.log(add(2));
In JavaScript, functions can act as regular data. If you are OK with the idea of passing a number or string around, then passing a function around is no different. This allows you the ability to do some very cool and powerful things.
Here, instead of the add function simply giving you your numeric answer, it's giving you back a function with your number embedded into it. This means that add doesn't really add anything, add is a function for creating functions (similar to the idea of a "Factory" in class based programming).
Changing the names may make things easier:
function createAddFunction(numberThatWillBeHardWiredIntoReturnedFunction) {
var resultingFunction= function(x) { //or x = 0
return numberThatWillBeHardWiredIntoReturnedFunction + (x || 0);
}
return resultingFunction;
}
var num = 2;
// This will cause add to be a function that is hard-wired to add 2 to another number
var add = createAddFunction(num);
console.log(`Adding 2 to num(${num}): ${add(2)}`);
// This will cause add to be a function that is hard-wired to add 5 to another number
add = createAddFunction(5);
console.log(add());
console.log(add(2));
Let's rename the functions to make it even clearer. The outer function takes a parameter and uses it to create a new function. This new function is returned for future use.
function createFunctionThatAdds(n){
var adds_n = function(x) { return n + (x || 0); };
return adds_n;
}
var adds_2 = createFunctionThatAdds(2);
var adds_5 = createFunctionThatAdds(5);
console.log(adds_2(10));
console.log(adds_5(10));
The technique used is called currying. It's part of functional javascript.
You can read more about it here.
The idea behind it is that you can use a function to generate another function, which you can use further in your code.
Currying is made possible, because of a closure.
There are a lot of libraries that are built based on that principe, for example Ramda.

Function with sub-functions but also its own... function...?

Please: only pure vanilla JS code. No jQuery or other external things, thank you. :)
How can I create a function that contains sub-functions but also returns a value if no sub-function is called?
For example, let's take a number variable num.
I want to add a round() function to the number variable; if it's called directly, I want it to round up or down depending on the variable's actual value.
var num=4.12;
num.prototype.round=function(){return Math.round(this);}
Now I wand round() to have sub-functions that will round up or down, disregarding the decimal values.
num.prototype.round.up=function(){return Math.ceil(this);}
num.prototype.round.down=function(){return Math.floor(this);}
If I do that and log num.round() to console, it does what it's supposed to. But if I log num.round.up() to console, I get an error telling me that num.round.up() is not a function.
So I try putting the sub-functions into the main function declaration like this:
num.prototype.round=function(){
var n=this;
this.up=function(){return Math.ceil(n);}
this.prototype.round.down=function(){return Math.floor(n);}
return Math.round(n);
}
Then again, num.round() will return the correctly rounded value, but both num.round.up() and num.round.down() will return "not a function" errors.
I'm going nuts trying to figure this out... I didn't only try what I mentioned above, but I also tried doing this with immediately executing functions like this:
num.round=(function(){
return function(){
var that=this;
/* anything in here is already useless because this
is no longer num's value but [Object window]... */
}
})();
I guess part of the trouble is that I'm so weak at OOP that I just have no clue about the correct terminology... naturally, that doesn't help when searching for clues or when it comes to knowing any potential reasons why something like this should not work...
So is there any way at all to do this?
Well you can pass a parameter to the function. Not the exact implementation you want, just an alternative:
var num = function (defaultNumValue) {
var delegation = {
'up': 'ceil',
'down': 'floor'
};
return {
round: function (val) {
return Math[ delegation[val] || 'round' ](defaultNumValue);
}
}
};
var sth = num(1.5);
sth.round(); // 2
sth.round('up'); // 2
sth.round('down'); // 1
May be something like:
function num(n) {
this.num=n;
this.round=Math.round(n);
this.up=Math.ceil(n);
this.down=Math.floor(n);
this.up2=function(){return Math.ceil(n);}
}
var num = new num(4.12);
alert(num.num);
alert(num.round);
alert(num.up);
alert(num.down);
alert(num.up2());

Categories