jquery/javascript missing ) after formal parameters - javascript

Hi there I have this code:
function getFullnameDetails(mainHeight,upperstyle,type=''){
setTimeout(function(){fullnameCenter(mainHeight,upperstyle,type='')},2000);
}
function fullnameCenter(mainHeight,upperstyle,type=''){
var distOfMainAndUpper = mainHeight - upperstyle;
var mainHalfHeight = mainHeight/2;
var imageHeight = jQuery("img[rel='fullname']").height(); //there is a delay
var imageHalfHeight = imageHeight/2;
var fromImageTopToMainHalf = mainHalfHeight - imageHeight;
var position = imageHalfHeight+fromImageTopToMainHalf-distOfMainAndUpper;
if(type == 'big'){ jQuery("#temp .test1").css("bottom",position+"px"); }
else { jQuery(".test1").css("bottom",position+"px"); }
}
It says that I'm missing ) after formal parameters.
This happens on this line:
function getFullnameDetails(mainHeight,upperstyle,type=''){ //IT HAPPENS HERE! :)
setTimeout(function(){fullnameCenter(mainHeight,upperstyle,type='')},2000);
}
What am I doing wrong here.
Thanks in advance for the help :)

Javascript does not support default function parameter values.
You can do things like this (but be wary of unintended 'falsey' values):
function getFullnameDetails(mainHeight,upperstyle,type){
type = type || ''; // if type is 'falsey' (null, undefined, empty string) assign ''
//...
}

As other answers have pointed out, JavaScript doesn't support default values in the function parameters. However, as also pointed out in the other solutions, using an inline || won't work when falsey values are passed (eg null, 0, '', NaN, false). A better solution is to check to see if the argument is undefined:
type = typeof(type) !== 'undefined' ? type : '';
or, more generally:
argument_name = typeof(argument_name) !== 'undefined' ? argument_name : default_value;
Of course, this means that passing undefined to a function will mean that the default value is used instead - but that should be pretty uncommon.

Are you trying to use like a default parameter or something?
type=''
That is not valid -- you can't have an equal sign in the parameter list of a function like that.

Related

JavaScript: Pass conditional condition as value

I have a function that finds elements using jQuery. I then take that element, get a value from it and assign it to a variable. However, sometimes an element will not exist on the document and the function will return undefined. This is expected and if the element returned is undefined then the variable that gets assigned should also be undefined. Since I am using this function to assign variables many times I wanted to make it neat and on one line. I thought using conditionals might be a solution, however, doing this leads to really messy long lines and needing to call the function twice:
let html = $(response.body);
let language = getRowElementFromText('Language', html) ? getRowElementFromText('Language', html).find('a').text() : undefined;
let pages = getRowElementFromText('Page', html) ? parseInt(getRowElementFromText('Page', html).text()) : undefined;
Is it possible to resolve those issues and somehow pass the condition of the conditional to be used as the value? For example, in this pesudo code this would be the value of the conditional:
let html = $(response.body);
let language = getRowElementFromText('Language', html) ? this.find('a').text() : undefined;
let pages = getRowElementFromText('Page', html) ? parseInt(this.text()) : undefined;
If this not possible is there another more readable way I can accomplish this on one line?
It is/will be with the optional chaining operator that's new in ES2020 (available via transpilation today). the code would look like this (it only helps so much with the parseInt cas):
let language = getRowElementFromText('Language', html)?.find('a').text();
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^
let pageText = getRowElementFromText('Page', html)?.text();
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^
let pages = pageText ? parseInt(pageText) : undefined;
language would be undefined if the element wasn't found.
If you can't use it (because your target environments don't have it yet and you're not transpiling), you could pass in a function that getRowElementFromText will call if the element is found:
let html = $(response.body);
let language = getRowElementFromText('Language', html, el => el.find('a').text());
let pages = getRowElementFromText('Page', html, el => parseInt(el.text()));
getRowElementFromText would look like this:
function getRowElementFromText(text, html, callback) {
const result = /*...existing logic...*/;
return result === undefined ? undefined : callback(result);
}
Or perhaps like this (callback is optional):
function getRowElementFromText(text, html, callback) {
const result = /*...existing logic...*/;
return !callback || result === undefined ? result : callback(result);
}
Note: In the above I'm assuming getRowElementFromText does actually return undefined in some cases ("not found"), and returns a jQuery object in other cases (found). I flag this up because if it always returns a jQuery object (which may be empty), jQuery objects are never falsy (not even empty ones).
Add the following function to jQuery prototype. It receives a fallback string as an argument and when element is not found, returns fallback string:
$.prototype.getText = function(fallback = undefined) {
return this.length > 0 ? this.text() : fallback
}
console.log($("#foo").getText())
console.log($("#bar").getText("If the element does not exists, returns given fallback string"))
console.log(`Fallback string default value is: ${$("#baz").getText()}`)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label id="foo">If the element exists, return its inner text</label>
Usage:
$(selector).getText(fallbackString);

How to indicate that new RegExp() constructed by undifined value?

I have this JavaScript row:
var matcherName = new RegExp(filterValueName);
The filterValueName variable has some string but, might be situation when filterValueName is undifined .
My question is how can I know if matcherName was constructed by filterValueName = undifined?
Why not testing filterValueName first?
Something like
var matcherName = null;
if( filterValueName != undefined ) {
var matcherName = new RegExp(filterValueName);
}
...
if( matcherName === null ) {
// filterValueName was undefined
} else {
// filterValueName was ok
}
In Firefox and Chrome at least the regex defaults to /(?:)/. But just compare the strings to be sure:
function is_regex_undefined(regex) {
var undefined;
return String(regex) === String(new RegExp(undefined));
}
According to MDN the pattern should not be absent. I would not doubt that there might be a JS engine where new RegExp(undefined) equals /undefined/. Then this solution would fail if you really have an expression that should match the string "undefined". #RiccardoC's answer is the safer choice.
I would recommend having an if statement before, since you can't easily extract what you constructed it with. Is there anything preventing you from testing the values before you work with them?
var matcherName = new RegExp("foo");
var matcherName2 = new RegExp(undefined);
console.log(matcherName)
VM522:2 /foo/
console.log(matcherName2)
VM527:2 /(?:)/

Setting a Javascript if statement with 2 requirements to one line

var status = result.locations[index].status;
var operator = result.locations[index].operator;
var original = result.locations[index].original;
var produced = result.locations[index].produced;
var href = result.locations[index].more;
I have the above which each need to be an if statement to check if there is content and my output is the below code.
if (result.locations[index] && result.locations[index].status){
var status = result.locations[index].status;
} else {
var status = '';
}
I would need to reproduce this per line from the code at the top of the post. What would be the best method to simplify each down to keep the code neater and not produce 5 lines of if statement when 1 or 2 would do.
var status = (result.locations[index] && result.locations[index].status ? result.locations[index].status : '');
Not sure why you want to, but:
var status = (result.locations[index] && result.locations[index].status) ? result.locations[index].status : ""
Your problem is trying to access a property of a "deep" javascript object using its path.
This is a common question :
Javascript: Get deep value from object by passing path to it as string
Accessing nested JavaScript objects with string key
There is no built-in way to do this in javascript.
There are plenty of libraries to do that, for example, with selectn, this would become something like (I have not tested it, so I don't know if the index part will work, but you get the idea) :
var status = selectn("locations." + index + ".status", result) || ''
If the structure of your objects is always the one above (that is, the property is just at one level of depth), and you're not expecting 'falsy', you could simply write the 'test' function yourself :
function safeGet(instance, propertyName, defaultValue) {
// As pointed by AlexK, this will not work
// if instance[propertyName] can be anything Falsy ("", 0, etc...)
// If it's possible, get a library that will do
// the full series of insane checks for you ;)
if (instance && instance[propertyName)) {
return instance[propertyName];
} else {
return defaultValue;
}
}
var location = result.locations[index]; // Potentially undefined, but safeGet will deal with it
var status = safeGet(location, "status", "");
var operator = safeGet(location, "operator", "DEFAULT_OPERATOR");
...
var status = result.locations[index] && result.locations[index].status || '';
However, better maje sure before, if result.locations[index] exists... else do whatever is to be done in your code..

My function returns empty. why?

I know that this is a basic question but I am stuck with it somewhere in my code. I got that code from somewhere but now I am modifying it according to my need.
What does jQuery('#selector') do? In my code it always return empty.
Here is my code
query: function (selector, context) {
var ret = {}, that = this, jqEls = "", i = 0;
if(context && context.find) {
jqEls = context.find(selector);
} else {
jqEls = jQuery(selector);
}
ret = jqEls.get();
ret.length = jqEls.length;
ret.query = function (sel) {
return that.query(sel, jqEls);
}
return ret;
}
when I call this query function then I pass selector as parameter. When I do console.log(selector) it does have all the selectors which I need in this function. But the problem is on this line jqEls = jQuery(selector);. when I do console.log(jqEls) after this it returns empty thus the whole function returns empty.
Can I use something different then this to make it work?
jquery('#selector') is the equivalent of document.getElementById('selector'). If there is no DOM node with an id of selector, you get an empty result.
e.g.
<div id="selector">...</div>
would return the dom node corresponding to this div. Do you have jquery loaded?
jQuery(selector) is looking for a DOM element that meets the selector criteria.
$('#example') == jQuery('#example')
Both will look for something with id "example"
$(selector).get() will return undefined if no element is found. This is why your function returns undefined. To fix this, you could use a default value if there is no element found:
ret = jqEls.length ? jqEls.get() : {};
This way your function will always return an object that has your length and query properties, but it will not have an element if jQuery did not find one.
After reading your code I have a question : do you put the # in your variable selector ?
A solution to solve this by replacing the bad line by jqEls = jQuery("#" + selector);
If the problem isn't due to that can you say the type of selector ? string ? object ? jQueryObject ?

In JavaScript, how can I create a function with an optional parameter?

Question: What is the proper way to define a function in JavaScript that takes optional parameters?
For example:
function myFunc(optionVar1) {
if(optionVar1 == undefined) {
...
} else {
...
}
}
myFunc('10'); // valid function call
myFunc(); // also a valid function call
Is it proper to use a ? mark like Ruby in the function declaration like so to denote optional parameters:
function myFunc(optionVar1?) {...} // <--- notice the ? mark
There is no syntax in Javascript that specifies that a parameter is optional (or required). All parameters are optional. If they aren't specified they're undefined so you need to check for that. For example, this function will in effect create a default value of 10 for the parameter:
function myfunc(someParam) {
if (someParam === undefined) {
someParam = 10;
}
...
}
Also you can access the parameters programmatically using the arguments property.
Lastly, if you have more than about 3-4 parameters it's generally advisable to use an anonymous object instead.
Actually, all parameters are optional in JS functions. There is no warning or error if you omit a parameter.
You can set defaults like
function throw_cat(dist){
dist = typeof dist=='undefined' ? 20 : dist;
//OR
dist = dist || 20; //this will assign it to 20 if you pass 0 or another 'falsy' value, though. May be good if you expect a string. String '0' stays, '' or null assigns the default
//etc...
}
You can use annotation such as {Object=} or {number=} in the comment section when using a doclet:
/**
* #param {object=}xyz
*/
Modern IDE knows to recognize annotations for JavaScript and shows you indications about potential problems in your code.
Example:
/**
*
* #param query
* #param callback
* #param {number=} ttl optional time-to-leave
*/
loadByJSONP:function loadByJSONP(query, callback, ttl) {
...do some work
}
In this example 'ttl' is optional. the annotation {number=} indicate to IDE that this parameter is optional. Accordingly when you call this function with two parameters only, you will not get warning.
Annotations can also be used for designating the expected type. this makes your code better and less prone to bugs. Here is the link for annotations:
https://developers.google.com/closure/compiler/docs/js-for-compiler
First, everyone who writes JavaScript, do yourself a favor and go through Learning Advanced JavaScript from John Resig.
function myFunc(arg1, arg2 /* varargs... */) {
var optional = Array.prototype.slice.call( arguments, 2 );
Every parameter to a function is "optional", even those you declare in the parameter list of the function declaration.
Just consider documenting them well.
Some sources will tell you to skip parameters altogether and instead make use of the arguments array. This lets you take any input that's provided to your function, and you can decide how to respond to the arguments passed to your function as you see fit.
You can read more about it here:
http://www.devguru.org/technologies/ecmascript/quickref/arguments.html
cletus and Damovisa have made good suggestions. I would also add that some (like myself) might prefer a notation like this:
function foo(/*bar*/) {
if (arguments.length == 1) {
var bar = arguments[0];
...
}
}
This serves to document to developers of your code base that the argument is optional and also documents the name, but it also prevents the argument from showing up in the function name in a debugger (the example would show up as foo() rather than foo(optional_argument). Otherwise, developers who are consuming the API might assume that it was required.
Edit: This is especially useful for optional arguments that are intended to be used internally.
function connect(hostname, port, method) {
hostname = hostname || "localhost";
port = port || 80;
method = method || "GET";
}
Important URL Optional Parameters in Javascript
The first google response I discovered:
http://www.tipstrs.com/tip/354/Using-optional-parameters-in-Javascript-functions
I haven't seen any instances where a question mark is used to alert a caller to an optional parameter. While it's done in other languages, I don't think it's necessary in javascript.
In fact, it seems that you can't use a question mark in the variable name. Only letters, numbers, $ and _.
Just don't define the function with any parameters and access the special arguments array from within the function where you want the optional parameters to be. Example below.
<HTML>
<HEAD>
<SCRIPT Language="JavaScript">
function foo() {
var argv = foo.arguments;
var argc = argv.length;
for (var i = 0; i < argc; i++) {
alert("Argument " + i + " = " + argv[i]);
}
}
</SCRIPT>
</HEAD>
<BODY onload="foo('hello', 'world');">
</BODY>
</HTML>
Is it proper to use a ? mark like Ruby in the function declaration
No, there's no language-based way denote an optional arg. I definitely think it's worth indicating in a comment, though:
function myFunc(var1, var2 /* optional */, var3 /* optional */) {
if (var2===undefined) ...
(Note the triple-equals for exact equality testing. Otherwise a passed null value will also match. You generally want === for most comparisons in JS, as the double-equals is undesirably weakly-typed.)
For when you've got an indeterminate number of optional arguments, you generally omit them from the function statement, and again a comment is polite:
function myFunc(var1 /* , optional var2..varN */) {
for (var i= 1; i<arguments.length; i++) ...
// 1. best way
function sum1(x = 1, y = 2) {
console.log(x + y)
}
sum1() // x=1,y=2
sum1(4, 5) // x=4,y=5
sum1(8) // x=8,y=2
// 2. Ternary way
function sum2(x) {
x = x !== undefined ? x : 1; // if x define x=x, if undefine x=1
console.log(x)
}
sum2(1)
sum2(5)
sum2('foo')
sum2()
// logical way
function sum3(x) {
x = x || 1; // x = either x if x is true or 1 if x is not false
console.log(x)
}
sum3(1)
sum3(5)
sum3('foo')
sum3()
For history sake: You can loop in your arguments with a != null check. For instance :
function container(param1, param2, param3, param4){
var param1, param2, param3, param4 = 0 // or other data types.
for (var i = 0; i < arguments.length; i++){
if(i != null) {
console.log(i); // or put default values to your parameters if you need to.
}
}
Now, all arguments become optional.

Categories