Extensions of Javascript function shorthand - javascript

I know it's possible to define a function this way:
x=y=>y*y
which corresponds to:
function x(y){ return y*y; }
But I was wondering, is it possible to extend this to two or more arguments?
i.e. x=y,z=>y+z or similar to correspond to function x(y,z){ return y*z; }
Is there a similar convention to the very first example that allows for two or more arguments? I know that the x=y,z=>y+z syntax isn't right as I get errors regarding the definitions of at least one of variables... So how can it be done, or rather... can it be done??

yes try
x=(z,y)=>z*y
haha :D
http://jsfiddle.net/FaSv2/

Related

"use strict" and naming arguments in function calls

A colleague advised me to add "use strict"; to the top of my JS code to highlight any gaps in my definitions and potential reference errors, etc. I am very happy with it because it has identified several pieces of code which might have been a problem down the line.
However, another colleague advised me that when calling functions which take multiple arguments, it can be helpful to name the arguments as they are specified, especially if it's something like a bunch of booleans. To illustrate, here's a couple of function calls:
logData(data, target, preserveLog=true, changeClass=false, wrapLine=false);
...is a whole lot clearer than:
logData(data, target, true, false, false);
But "use strict"; hates this. everywhere I've done this, I get a reference error in the console. It still runs fine, as would be expected, but the console is now cluttered with all these apparently non-defined references.
Does anyone know if there's a way around this so that I can keep my coding conventions which my colleagues appreciate, or am I going to have to either stop using "use strict"; or go through all my code and remove the names of arguments?
Thanks.
However, another colleague advised me that when calling functions which take multiple arguments, it can be helpful to name the arguments as they are specified, especially if it's something like a bunch of booleans.
This is terrible advice!
Javascript doesn't actually support passing arguments by name this way. Each of the arguments you pass "by name" is actually being treated as an assignment to a global variable with that name, and "use strict" is correctly identifying this as an error.
If you want to be more clear about what values you're passing, assign the values to real local variables and pass those, e.g.
var preserveLog = true;
var changeClass = false;
var wrapLine = false;
logData(data, target, preserveLog, changeClass, wrapLine);
If you really wanted to keep using your original pattern, you could even assign to those variables in the function call, so long as you declare them as local variables first:
var preserveLog, changeClass, wrapLine;
logData(data, target, preserveLog=true, changeClass=false, wrapLine=false);
(With a hat-tip to dav_i for this answer, which I based my recommendation off of.)
Duskwuff has already provided an excellent answer and I won't add anything to that, other than to say I fully agree with it, but he didn't mention any conventions that arose due to ES6.
In ES6, you still don't have named parameters, but you have the next best thing, which is Object destructuring assignment.
This allows us to pass what appears to be named parameters, but are really just destructured object properties of an object that is never directly used.
In the context of the example you provided, it would look something like this:
logData({data, target, preserveLog:true, changeClass:false, wrapLine:false});
Where the function is defined as:
function logData({data, target, preserveLog, changeClass, wrapLine}) { ... }
I've seen a lot of libraries that prefer this calling convention where ES6 is available, and it's very convenient too because the order of the parameters is also no longer important.

Why use the parameters if we can use variables?

Firstly, I'm a beginner, so don't be mad if what I'm saying is stupid.
So, this is the code that is using parameters:
function simpleExample (x) {
document.write ("I love " + x);
}
simpleExample ("my mom.");
And this is the code that doesn't use the parameters:
function simpleExample () {
var x = ("my mom");// Does not use the parameters
document.write ("I love " + x);
}
simpleExample ();
So, the result is the same and... the global and local thing is also the same [both is local right?] So what does the difference?
Sorry if it's a dumb question.
You maybe right if you just want to say you're loving your mom. But, what if you also want to say other persons that you love? You write all that hard code everytime?
the answer is : no.
You just call that function with a parameter. And that's it. Nothing more.
simpleExample("my mom");
simpleExample("my dad");
simpleExample("justin bieber"); //we all hope you don't.
Why use the parameters if we can use variables?
The point is that often we cannot use static (global) or constant variables. Consider your first function:
simpleExample("my mom.");
simpleExample("my dad.");
We are calling the same function multiple times with different arguments. This requires parametrisation of the code in the function that is otherwise the same for all cases.
Using a parameter for a function allows the result of the function (be it a process or a result value) to differ based on an input that is not fixed at the time of writing the function.
Even with your simple example it should be obvious that the simpleExample(x) function with a parameter can be easily reused like so:
simpleExample('my mom');
simpleExample('and my dad too!');
simpleExample('my sister not so much');
This wouldn't be as easy with the variable approach.
Using parameters is the essence of functions.
In the second case, the variable x is local to the scope of the fonction and will never change. That is, the execution of your function simpleExample will always have the same effect (logging "I love my mom" in the console).
The use of parameters allows your function to have an effect dependent to the input. In this case, the person you love can be changed depending of the parameter x.

JS - Call function by name (in object notation)

I want to clean up some old code and optimize it, which often uses the same code. (with only different names of functions to call)
I make a easier example and no, I don't write on a game. But this example looks more comprehensible to explaination of my issue.
character.sleep(1);
character.changeName(name);
character.useItm(1423);
Easier Example:
object.function(parameters)
Target was something like this:
myFunc(funcName,value) {
character.{funcName}(value);
}
$('.btn_sleep') { myfunc('sleep','1'); }
$('.btn_cName') { myfunc('changeName','Harold'); }
$('.btn_uItem') { myfunc('useItem','1423'); }
First I thought about to use eval(), because no user-input will come near of this functions. But I dislike this idea because of the performance lost.
Then I looked around for alternatives and found window[] and new function() as solution.
But I dont get an idea how to use it, when I want to dynamcially call a function by name in an object-notation. (Or in worser cases, when you've to get the result for an if-condtion from a function, which you called with object-notation.)
Could anyone help?
The best way I know how to dynamically call functions is using bracket notation because it allows you to set your object path with a variable
function myFunc(funcName,value) {
character[funcName](value);
}
myfunc('sleep','1');

Is it possible to give a type/class to JavaScript functions?

I wonder if it's possible to give a a type/class to JavaScript functions.
Of course, the Object class/type of function is 'Function/function'.
http://bonsaiden.github.io/JavaScript-Garden/#types.typeof
However, in my project, somehow I want to define class for function to group them.
It's similar concept HTML/CSS DOM element class.
I have a function which args is a function, and I want to distinguish which type or class of function is passed to the function.
It does not work with any object method, just a function, but it can be distinguished like obj.hasOwnProperty('someClass') .
I just wonder if there's smart way, if you think impossible, please insist so.
Thanks.
PS. I do not why someone vote -1 and to close this question.
This is the matter of reflection of Javascript. It's ok if find some reflection factor of JS is limited. and I think it's not wise to avoid to make it clear that something is impossible in a certain language.
A function is an object. You can add your own custom properties to any function. So, if you want to set your own type on several different functions so you can test for that, you can just add the same custom property (with different values assigned to it) to each of those functions.
function myFunc1() {}
myFunc1.myType = "whatever1";
function myFunc2() {}
myFunc2.myType = "whatever2";
function myFunc3() {}
myFunc3.myType = "whatever3";
function callMe(cb) {
if (cb.myType === "whatever1") {
// code here
} else if (...) {
// code here
}
}
callMe(myFunc1);
Note, this is a bit unusual and if you explained the actual problem you were trying to solve, there is probably a more common design pattern that might help you.
#jfriend00 has suggested the answer.
FYI, functions are objects so they can have your own custom properties so you could make your own custom property.
He's right, so to add a class/property to any functions, simply do
var myFunction = function(foo){...};
myFunction['someClass'] = true;
//To distinguish
if (someFunction.hasOwnProperty('someClass'))
{
console.log('someFunction is someClass');
}

Is a wrapper function syntax invalid in JavaScript?

In this article, the replier offers a correct and well structured solution to a problem.
However, he also argues that the suggested approach (i.e. making a wrapper for a callback function) isn't a valid JavaScript. That begs three questions.
Is that so?
What bad things can happen if applied?
What would be a valid JavaScript to resolve that issue?
The ... is not valid syntax. There are two solutions:
First, you could manually list out a lot of parameters:
callback: function (jq1, jq2, jq3, jq4, jq5, jq6) {
return pageselectCallback(your1, your2, jq1, jq2, jq3, jq4, jq5, jq6);
}
This of course won't work if there are more than six parameters. To fix this, you can use the .apply method, which takes an array of parameters:
callback: function () {
return pageselectCallback.apply(null,
Array.prototype.concat.call([your1, your2], arguments));
}
The example code in the answer is not valid. (, ...,)
But the solution is valid.

Categories