Expressions in ternary operators as functions - javascript

3>4?function1():function2()
Is it allowed to use functions in ternary operators?
I know you can use it for values, but for functions I am not certain.

You can. But like this
var func = 3 > 4 ? function(){
console.log("3 is not greater than 4");
} : function(){
console.log("3 IS greater than 4");
};
Now func has a function reference that has been set conditionally. Calling it func() will result in "3 IS greater than 4"
However, if you already have created the function, then just reference would be enough. You should not call it. Just pass the reference.
var func = 3 > 4 ? func1 : func2;

you can do
var f = 3>4?function(){console.log("left")}:function(){console.log("right")}
or with your edit
var f = 3>4?function1:function2
then f will be the function ( not the result of the function )
f()
or if you want the value that those functions return
var v = 3>4?function1():function2()
v will now be whatever those functions returned

This is valid JavaScript:
var b = true;
var a = b == true ? function(){ return 1; } : function(){return 2; }
a is a function that depended upon the ternary condition, exactly as you'd (hopefully) expect.
If you're wanting a to instead be the return value of the function - call it.
var b = true;
var a = b == true ? (function(){ return 1; }()) : (function(){return 2; }())

Related

Getting undefined value when trying to use with inner functions

Following is my code snippet :
function executorFunc(input){
return input();
}
function mainFunc(){
var a = 100;
function innerFunc(){
var b = 20;
return a + b;
}
executorFunc(innerFunc);
}
var finalVal = mainFunc();
console.log(finalVal);
I was in the assumption that innerFunc gets created within mainFunc and will be aware of outer/enclosing functions data like a = 100. To my surprise, it's not. There is something that is doing it wrong or there is something which I have misunderstood in basics of JS.
The final output is undefined where I was expecting 120.
Expected result as you are not returning the value from mainFunc function().
Use
return executorFunc(innerFunc);
function executorFunc(input){
return input();
}
function mainFunc(){
var a = 100;
function innerFunc(){
var b = 20;
return a + b;
}
return executorFunc(innerFunc);
}
var finalVal = mainFunc();
console.log(finalVal);
The problem here is that mainFunc does not return any value. So finalVal remains undefined.

Javascript run a function against a variable usnig dot notation

I think I'm using the wrong terminology but here is what I would like to do. Using a function like this one:
function isNumeric(){
if (isNaN(this)) { return false; }
var x = parseFloat(this);
return (x | 0) === x;
};
I know this function won't work as is. I removed the parameter that was originally passed in and replaced it inside the function with this. I would like to call it like so:
var tmp1 = 10;
var tmp2 = "10";
if( tmp1.isNumeric() == true && tmp2.isNumeric() == true ){
...
}
Instead of this:
if( isNumeric(tmp1) == true && isNumeric(tmp2) == true ){
...
}
The way to achieve that is not considered a good option, but it's to modify the prototype chain for the types of data you want your function to work with, e.g. for number and string like your example you could have:
Number.prototype.isNumeric = String.prototype.isNumeric = function() {
// ...
}
What you have currently is the preferred option because it won't contaminate the prototype chain for inbuilt types, risk conflicts with other libraries, potentially overwrite functionality you didn't know existed, etc. You could meet halfway with something like:
class Val {
constructor(value) {
this.value = value;
}
isNumeric() {
if (isNaN(this.value)) { return false; }
var x = parseFloat(this.value);
return (x | 0) === x;
}
}
Used like:
var tmp1 = new Val(10);
var tmp2 = new Val('10');
console.log(tmp1.isNumeric(), tmp1.isNumeric());
try to add this function to Object.prototype
Object.prototype.isNumeric = function () {
return parseFloat(this) == this;
};
Below may be a better option for the class function if you are wanting "10" to return that is it not a number.
isNumeric() {
return typeof this.value === 'number';
}
isNumeric is just a function - what you are looking for is an object method. Right now, tmp1 and tmp2 are a Number, and String respectively, and neither of those have a function called isNumeric. You can restructure those variables like this if you want:
function TmpValue (initValue) {
this.value = initValue
}
TmpValue.prototype.isNumeric = function() {
if (isNaN(this.value)) { return false; }
var x = parseFloat(this.value);
return (x | 0) === x;
}
var tmp1 = new TmpValue(10);
var tmp2 = new TmpValue('10');

How do I replace variables with values inside a stringified function (Javascript)?

Consider the following :
var a = 5;
var b = function ()
{
console.log (a + 5);
};
var c = b.toString();
after the above has been executed, c will be equal to :
"function ()
{
console.log (a + 5);
}"
How can I have c be equal to :
"function ()
{
console.log (5 + 5);
}"
instead?
I tried the following :
var a = 5;
var b = function ()
{
console.log ('<%a%>' + 5);
};
var c = b.toString().replace('<%a%>', a);
But the above obviously makes c equal to :
"function ()
{
console.log ('5' + 5);
}"
Is there some other way of achieving this (javascript + RegEx) without using libraries like underscore (with the known template function) ?
Basically I'm trying to come up with a neat function that will convert a function into a string while at the same time replacing all variables (that have a hardcoded value) present in that function with their respective values, without the use of any variables.
Thanks
You can fix your snippet by changing the first argument of .replace:
var a = 5;
var b = function ()
{
console.log ('<%a%>' + 5);
};
var c = b.toString().replace("'<%a%>'", a);
For more generic solution you may need smarter parser with syntactical analysis.

What do I have to do with the variable count in order to pass this tutorial about JavaScript function scopes?

The tutorial says:
Define a function named callFunc that takes one argument, a function
f. It should return an array containing the values f(0), f(0), f(1),
f(1). You can only call f twice.
This is what the tutorial gives:
var count = 0;
var f = function (x) {
count += 1;
return x + 2;
};
var callFunc = function (f) {
};
I have no idea how to use count to pass this tutorial.
Any suggestions?
You don't need to use count. Just call f() twice and put the return values into an array:
var callFunc = function (f) {
var f0 = f(0);
var f1 = f(1);
return [f0, f0, f1, f1];
};

Default argument values in JavaScript functions [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I make a default value for a parameter to a javascript function
in PHP:
function func($a = 10, $b = 20){
// if func() is called with no arguments $a will be 10 and $ b will be 20
}
How can you do this in JavaScript?
I get a error if I try to assign values in function arguments
missing ) after formal parameters
In javascript you can call a function (even if it has parameters) without parameters.
So you can add default values like this:
function func(a, b){
if (typeof(a)==='undefined') a = 10;
if (typeof(b)==='undefined') b = 20;
//your code
}
and then you can call it like func(); to use default parameters.
Here's a test:
function func(a, b){
if (typeof(a)==='undefined') a = 10;
if (typeof(b)==='undefined') b = 20;
alert("A: "+a+"\nB: "+b);
}
//testing
func();
func(80);
func(100,200);
ES2015 onwards:
From ES6/ES2015, we have default parameters in the language specification. So we can just do something simple like,
function A(a, b = 4, c = 5) {
}
or combined with ES2015 destructuring,
function B({c} = {c: 2}, [d, e] = [3, 4]) {
}
For detailed explanation,
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/default_parameters
Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.
Pre ES2015:
If you're going to handle values which are NOT Numbers, Strings, Boolean, NaN, or null you can simply use
(So, for Objects, Arrays and Functions that you plan never to send null, you can use)
param || DEFAULT_VALUE
for example,
function X(a) {
a = a || function() {};
}
Though this looks simple and kinda works, this is restrictive and can be an anti-pattern because || operates on all falsy values ("", null, NaN, false, 0) too - which makes this method impossible to assign a param the falsy value passed as the argument.
So, in order to handle only undefined values explicitly, the preferred approach would be,
function C(a, b) {
a = typeof a === 'undefined' ? DEFAULT_VALUE_A : a;
b = typeof b === 'undefined' ? DEFAULT_VALUE_B : b;
}
You have to check if the argument is undefined:
function func(a, b) {
if (a === undefined) a = "default value";
if (b === undefined) b = "default value";
}
Also note that this question has been answered before.
I have never seen it done that way in JavaScript. If you want a function with optional parameters that get assigned default values if the parameters are omitted, here's a way to do it:
function(a, b) {
if (typeof a == "undefined") {
a = 10;
}
if (typeof b == "undefined") {
a = 20;
}
alert("a: " + a + " b: " + b);
}
function func(a, b)
{
if (typeof a == 'undefined')
a = 10;
if (typeof b == 'undefined')
b = 20;
// do what you want ... for example
alert(a + ',' + b);
}
in shorthand
function func(a, b)
{
a = (typeof a == 'undefined')?10:a;
b = (typeof b == 'undefined')?20:b;
// do what you want ... for example
alert(a + ',' + b);
}
You cannot add default values for function parameters. But you can do this:
function tester(paramA, paramB){
if (typeof paramA == "undefined"){
paramA = defaultValue;
}
if (typeof paramB == "undefined"){
paramB = defaultValue;
}
}

Categories

Resources