JS function breaks upon entering no argument - javascript

Here is a simple function, that counts the price of engraving, based on the entered phrase length.
function engravePrice(phraseToEngrave) {
var pricePerWord = 11;
var wordsToEngrave = phraseToEngrave.split(' ');
if (phraseToEngrave.length === 0){
return 0;
} else if (phraseToEngrave.length > 0){
return wordsToEngrave.length * pricePerWord;
}
}
console.log(`Gift wrap and engraving price is: ${engravePrice('')} Q`);
It actually works pretty well:
engravePrice('Two words') //will return 22, as expected
engravePrice('') //will return 0, as expected
except for one specific situation:
engravePrice() //when it breaks, saying "cannot read property 'split' of undefined"
Is there a solution for that?
Thanks.

You need to check phraseToEngrave.for undefined, e.g.
function engravePrice(phraseToEngrave) {
if (!phraseToEngrave) return 0;
...
}
or in ES6, give it a default:
function engravePrice(phraseToEngrave = '') {
...
}

I would do it like this:
function engravePrice(phraseToEngrave) {
var phraseToEngrave = phraseToEngrave || '';
var pricePerWord = 11;
var wordsToEngrave = phraseToEngrave.split(' ');
if (phraseToEngrave.length === 0){
return 0;
} else if (phraseToEngrave.length > 0){
return wordsToEngrave.length * pricePerWord;
}
}
Which just converts it to an empty string if nothing is passed.

Related

Javascript How to check the length of multiple variables and return the result in an efficient way?

At the moment I have an if the condition that checks if any of the string variable lengths is greater than 2 if true check for another condition, else console.log the output.
var previous_data_change = 'last_changed on 10/01/2019 13:56:34';
var current_data_change= "";
var current_data_end = "";
var current_data_profile = "normal";
// check for changes
if (
previous_data_change.length >= 2 ||
current_data_start.length >= 2 ||
current_data_end.length >= 2 ||
current_data_profile.length >= 2
) {
if (previous_data_change.includes("last_changed")) {
console.log(`last change comments: ${previous_data_change}`)
}
} else {
console.log(`no change in previous record`)
}
i have tried refactoring it using some,
var previous_data_change = 'last_changed on 10/01/2019 13:56:34';
var current_data_change= "";
var current_data_end = "";
var current_data_profile = "normal";
var filter_col = [
previous_data_change,
current_data_change,
current_data_end,
current_data_profile
];
change_boolean = filter_col.some((element) => element.length >= 2);
if (change_boolean && previous_data_change.includes("last_changed")) {
console.log(`last change comments: ${previous_data_change}`);
} else {
console.log("no change in previous record");
}
is there any way to shorten it further?
Since you want any of them to be length greater than 2. You can simply merge them instead of writing 4 if conditions.
var previous_data_change = 'last_changed on 10/01/2019 13:56:34';
var current_data_change= "";
var current_data_end = "";
var current_data_profile = "normal";
var string_to_check = previous_data_change + current_data_start + current_data_end + current_data_profile;
// check for changes
if (string_to_check.length < 2) {
console.log(`no change in previous record`)
return false;
}
if (previous_data_change.includes("last_changed")) {
console.log(`last change comments: ${previous_data_change}`)
return true;
}

editing value of inputfield using Javascript

So I have this code:
function resetAll(einde) {
if(einde !=1) {
if(beurt == 0) {
spelerbolletje.gewonnen += 1;
document.getElementById("bolletje").value = spelerbolletje.gewonnen;
} else {
spelerkruisje.gewonnen += 1;
document.getElementById("kruisje").value = spelerkruisje.gewonnen;
}
}
setVakjes();
resetVakjes();
}
somehow this sets the value for the value of the winner from 0 to NaN.
does someone know how to solve this?
What you do seems correct. I think the problem is that XX.gewonnen has not been initialized.
var a = {};
a.gewonnen += 1; // => gewonnen = NaN
So, ensure gewonnen is defined:
if(XX.gewonnen == undefined) XX.gewonnen = 0;
// rest of your code

javascript function return "undefine" from jsp page

i have a jsp page and call a JS function which is in some abc.js file from this JSP page.
i have included this js file to jsp page.
JSP JavaScript Code:-
function doFinish(tableId, col, field)
{
var oldselectedCells = "";
var selItemHandle = "";
var selRightItemHandle = "";
var left = -1;
var right = -1;
// Get the table (tBody) section
var tBody = document.getElementById(tableId);
// get field in which selected columns are stored
var selectedCellsFld = document.getElementById(tableId + datatableSelectedCells);
selectedCellsFld.value = oldselectedCells;
for (var r = 0; r < tBody.rows.length; r++)
{
var row = tBody.rows[r];
if (row.cells[col].childNodes[0].checked == true)
{
selectedCellsFld.value = oldselectedCells +
row.cells[col].childNodes[0].id;
selItemHandle = row.cells[col].childNodes[0].value
oldselectedCells = selectedCellsFld.value + datatableOnLoadDivider;
left = selItemHandle.indexOf("=");
right = selItemHandle.length;
selRightItemHandle = selItemHandle.substring(left+1,right);
var index=getColumnIndex(tBody,"Name");
if(index!=null)
{
if(field == 1)
{
window.opener.document.TemplateForm.eds_asbactionscfg_item_handle_child_physpart.value = selRightItemHandle;
window.opener.document.TemplateForm.ChildPhysicalPart.value = row.cells[index].childNodes[0].innerHTML;
}
else if (field == 2)
{
window.opener.document.TemplateForm.eds_asbactionscfg_dev_doc_item_handle_name.value = selRightItemHandle;
window.opener.document.TemplateForm.DeviationObject.value = row.cells[index].childNodes[0].innerHTML;
}
else if (field == 3)
{
window.opener.document.TemplateForm.eds_asbactionscfg_dev_doc_item_handle_name.value = selRightItemHandle;
window.opener.document.TemplateForm.DeviationObject.value = row.cells[index].childNodes[0].innerHTML;
}
}
}
}
window.close();
}
JS Code:-
function getColumnIndex(tBody,columnName)
{
var cells = tBody.parentNode.getElementsByTagName('th');
for (var i=0;i<cells.length; i++)
{
if(cells[i].hasChildNodes())
{
if(cells[i].childNodes[0].innerHTML.replace(/(\r\n|\n|\r)/gm ,"").trim() == columnName)
{
return i;
}
}
}
}
i had debug this code with firebug & calling getColumnIndex(tBody,columnName) function works fine but when it return to caller the var index=getColumnIndex(tBody,"Name"); the index value is "undefine".
suggest some solution.
getColumnIndex(tBody,columnName) function works fine.
as if it matches this if condition
if(cells[i].childNodes[0].innerHTML.replace(/(\r\n|\n|\r)/gm ,"").trim() == columnName)
{
return i;
}
so that it returns something.
but when you replace this
var index=getColumnIndex(tBody,"Name"); so that coulmnName would be "Name" in String.
And it doesn't match with any columnName so that your condition going to be wrong and function doesn't return anything.
var index=getColumnIndex(tBody,"Name"); the index value is "undefine".
suggestion is put some else condition on that and return some error message like this :
if(cells[i].childNodes[0].innerHTML.replace(/(\r\n|\n|\r)/gm ,"").trim() == columnName)
{
return i;
} else{
// put some error message
// return null
}
i had debug this code with firebug & calling getColumnIndex(tBody,columnName) function works fine
From this, I'm assuming that there isn't anything wrong with the implementation of your getColumnIndex function, so your issue with getting an undefined value must have to do with when this function is returning a value.
but when it return to caller the var index=getColumnIndex(tBody,"Name"); the index value is "undefine".
This leads me to assume that your tBody variable is not being set correctly, given that the "function works fine".
I'm assuming there is a case in your code where the conditions of your getColumnIndex function is not met.
function getColumnIndex(tBody,columnName)
{
var cells = tBody.parentNode.getElementsByTagName('th');
for (var i=0;i<cells.length; i++)
{
if(cells[i].hasChildNodes())
{
if(cells[i].childNodes[0].innerHTML.replace(/(\r\n|\n|\r)/gm ,"").trim() == columnName)
{
return i;
}
}
}
// If your code reaches this point, then the prior conditions have not been met
// You can choose to do something else here for return false/undefined etc.
return undefined;
}

localStorage loadVote when refresh page (broken)

I cannot show voteUp/Down when I refresh page, because if I do voteUp/Down(+1 or -1) and refresh page, this return voteUp/Down (0) again. In this past I was using JSON, but the community recommended without JSON. So I have it, in this moment. Thanks.
var voteUp = document.getElementById('vote-up');
var voteDown = document.getElementById('vote-down');
var handUp = once(function() {
var total = Number(voteUp.innerHTML);
total += 1;
voteUp.innerHTML = total;
saveVote();
});
voteUp.addEventListener('click', handUp);
var handDown = once(function() {
var total = Number(voteDown.innerHTML);
total -= 1;
voteDown.innerHTML = total;
saveVote();
});
voteDown.addEventListener('click', handDown);
function once(fn, context) {
var result;
return function() {
if(fn) {
result = fn.apply(context);
fn = null;
}
return result;
};
}
function saveVote() {
var votes = voteUp, voteDown;
localStorage.setItem('data', votes);
console.log('saveVote');
}
function loadVote() {
var votes = localStorage.getItem('data');
if(!votes){
return;
}
console.log(localStorage.getItem('data'));
}
loadVote();
var voteUp = document.getElementById('vote-up');
function handUp() {
var total = Number(voteUp.innerHTML);
total += 1;
voteUp.innerHTML = total;
}
voteUp.addEventListener('click',handUp,false);
It increments each one value by a click.
There's no such thing as an =+ operator, there is an += operator, however.
+=
Addition assignment.
Also, I'm pretty sure the typeof val is undefined since it's value is never defined in the argument passing of the method.
A variable which's type is undefined can certainly not contain a value which's a number (it's NaN) and thus the error message makes sense.

Javascript undefined error on last iteration

When looping through this string, the alert prints out test 4 times (correctly) but then also prints "undefined" at the end. How do I make it doesn't return undefined.
This returns - undefinedCAFE ::
alert(match("abcdef", "CAfe"));
function match(string, pattern) {
var patternUpperCase = pattern.toUpperCase();
var stringUpperCase = string.toUpperCase();
var stringConcatenate;
var answer;
for (var i = 0; i < patternUpperCase.length; i++) {
if (patternUpperCase.charAt(i) != undefined) {
if (patternUpperCase.charAt(i) >= 'A' && patternUpperCase.charAt(i) <= 'Z') {
stringConcatenate += patternUpperCase.charAt(i);
alert("test");
}
}
}
return stringConcatenate;
}
The match function doesn't have a return statement, so it returns undefined. This means that
alert(match("abcdef","CAfe"));
will always show an alert of "undefined" at least once. To not show the alert, call the function without using alert:
match("abcdef","CAfe");
Alternatively you can make the function return something, such as stringConcatenate, which would be computed for no reason otherwise.
try this
alert(match("abcdef", "CAfe"));
function match(string, pattern) {
var patternUpperCase = pattern.toUpperCase();
var stringUpperCase = string.toUpperCase();
var stringConcatenate;
var answer;
var i = 0;
for (var i = 0; i < patternUpperCase.length; i++) {
if (patternUpperCase.charAt(i) != undefined) {
if (patternUpperCase.charAt(i) >= 'A' && patternUpperCase.charAt(i) <= 'Z') {
stringConcatenate = stringConcatenate + patternUpperCase.charAt(i);
alert("test");
}
}
}
return stringConcatenate;
}
Last "undefined" valie is result of your function:
alert(match("abcdef", "CAfe"));
http://jsfiddle.net/sava/Dw7jm/

Categories

Resources