How to deal with a NaN in JS? - javascript

I have the following:
var cID = parseInt(hash.match(/\d+/g)[1]);
I then want to do something like so:
if (cID !== undefined) {
alert('hello');
}
Problem is cID if it does not find a match, is returning NaN in the console when logged... How do I create an if Statement, meaning if there is an INT from the match or not based on: parseInt(hash.match(/\d+/g)[1])
Thanks

if (isNaN(cID)){
//do stuff here
}

You might be looking for the global isNaN() function.

if (cID !== undefined || !isNaN(cID)) {
alert('hello');
}

Use isNaN javascript function to check if return value of parseInt is number or not:
var cID = parseInt(somevar);
if (isNaN(cID)) { alert ('error') };
docs for isNaN: https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#isNaN_Function

Related

Javascript: Function returning last element of array

I'm taking Colt Steele's Udemy Course titled: "The Web Developer Bootcamp 2020". I have however become stuck on a certain coding exercise. The exercise objective is as follows: Please write a function called lastElement which accepts a single array argument. The function should return the last element of the array(without removing the element). If the array is empty, the function should return null.
I have tried coming up with a solution but cant seem to figure it out. My current best guess is this :
function lastElement (num) {
if (num !== undefined){
return num[num.length -1];
} return null;
}
I'm interested in knowing why the function I have written doesn't work and some pointers on how I should rethink the function, so that it does work.
Best Regards Andreas
Change to this condition.
if (num && num.length>0)
You can use this:
function lastElement(arr) {
if(arr.length>0){
return arr[arr.length-1];
} else{
return null;
}
change your condition to:
if(num && num.length>0)
additionally, if they decide to enter an argument that is not an array,
if(num && Array.isArray(num) && num.length>0)
The problem lies in the difference of truthy and falsy values:
Empty array is truthy but undefined is falsy, so []!==undefined is true, but:
num[num.length -1];
means:
num[-1];
which is undefined .
function lastElement(test) {
if (test.length == 0)
return null;
else
return test[test.length - 1];
}

what is the value of an ignored parameter in javascript?

I was wondering what is the value of an ignored parameter in JS. Lets say that a function takes 2 values as parameters and we only provide one on the call. What is the value of the other one? I thought it would be undefined but the following piece of code only displays "1".
var test = function(par1, par2){
document.write(par1.toString());
document.write(par2.toString());
if(typeof par2 === "undefined"){
document.write('undefined');
}
};
test(1);
the following code would work:
var test = function(par1, par2){
document.write(par1.toString());
document.write(par2);
if(par2 === undefined){
document.write('undefined');
}
};
test(1);
When parameter is not supplied, its value is undefined. Note that variable itself is available (after all, its name is already supplied to a function via arguments list, and it's the name that counts in JavaScript), so there's no need to check it via typeof var === 'undefined' to avoid those pesky ReferenceErrors.
undefined is a special value in JavaScript. While you cannot call any method on it (fails with undefined is not an object Error), you still can use it in expressions and function calls. In this particular case document.write will implicitly convert this value to String before displaying it; the result will be a String - 'undefined'.
Demo.
Try:
var test = function(par1, par2){
if(par2 === undefined){
document.write('undefined');
}
};
test(1);
Working demo
You can also check, if your attributes are set. Example:
var test = function(par1, par2){
if(par1 === undefined){
document.write('par1 is undefined');
}else{
document.write('par1 is set');
}
if(par2 === undefined){
document.write('par2 is undefined');
}else{
document.write('par2 is set');
}
};
test(1);
And output will be:
par1 is set
par2 is undefined
Demo 2
Hope it'll help :)

Javascript,doesn't show undefined number

I've created a variable with keys and values which looks like:
var e = new Array();
e[0] = "Bitte";
e[1] = "Danke";
Besides this I added a line in the variable which shows a text when the number is undefined.
e[NaN] = "Change Settings";
So when the variable e is NaN ("undefined"), I want that he doesn't displays the Number of the variable e in the input. I tried to achieve this as you can see, but it won't function.
if (neuezahl = NaN) {
document.getElementById("saveServer").value="";
} else {
document.getElementById("saveServer").value=""+neuezahl+"";
}
You have assigned neuzahl not compared it, aside that use the isNAN function:
if (isNAN(neuezahl))
{
document.getElementById("saveServer").value="";
}
else
{
document.getElementById("saveServer").value=""+neuezahl+"";
}
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/isNaN
NaN can't be compared directly (it's not even equal to itself NaN === NaN ==> false). Use isNaN() to detect NaN:
if (isNaN(neuezahl)) {...}
the condition in the if statement may not correct. Now you use "=" not "==", it is an assignment statement and the condition will always true. So if you want to check "neuezahl" is "NaN", function isNaN may help.
if (isNaN(neuezahl)){...}
else {}

How to check if string is present in variable in jquery

I have the variable like
var myVar = "The man is running"
pattern = "run"
I want to check via jquery that if it conatins words "run"
Like
if($(myVar).(:contains(pattern)))
return true
Is this possible
RegExp option...just because..RegExp.
var pattern = /run/;
//returns true or false...
var exists = pattern.test(myVar);
if (exists) {
//true statement, do whatever
} else {
//false statement..do whatever
}
You would use the Javascript method .indexOf() to do this. If you're trying to test whether the text of a DOM element contains the pattern, you would use this:
if($(myVar).text().indexOf(pattern) != -1)
return true;
If the variable myVar isn't a selector string, you shouldn't wrap it in the jQuery function, though. Instead, you would use this:
if(myVar.indexOf(pattern) != -1)
return true;
You do not need jQuery for this. Just check for the index of the string.
if (myVar.indexOf(pattern) !== -1) { ... }
Regex?
var hasRun = /run/i.test(myVar) // case insensitive

is there something like isset of php in javascript/jQuery? [duplicate]

This question already has answers here:
JavaScript isset() equivalent
(28 answers)
Closed 6 years ago.
Is there something in javascript/jQuery to check whether variable is set/available or not? In php, we use isset($variable) to check something like this.
thanks.
Try this expression:
typeof(variable) != "undefined" && variable !== null
This will be true if the variable is defined and not null, which is the equivalent of how PHP's isset works.
You can use it like this:
if(typeof(variable) != "undefined" && variable !== null) {
bla();
}
JavaScript isset() on PHP JS
function isset () {
// discuss at: http://phpjs.org/functions/isset
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: FremyCompany
// + improved by: Onno Marsman
// + improved by: Rafał Kukawski
// * example 1: isset( undefined, true);
// * returns 1: false
// * example 2: isset( 'Kevin van Zonneveld' );
// * returns 2: true
var a = arguments,
l = a.length,
i = 0,
undef;
if (l === 0) {
throw new Error('Empty isset');
}
while (i !== l) {
if (a[i] === undef || a[i] === null) {
return false;
}
i++;
}
return true;
}
typeof will serve the purpose I think
if(typeof foo != "undefined"){}
If you want to check if a property exists: hasOwnProperty is the way to go
And since most objects are properties of some other object (eventually leading to the window object) this can work well for checking if values have been declared.
Some parts of each of these answers work. I compiled them all down into a function "isset" just like the question was asking and works like it does in PHP.
// isset helper function
var isset = function(variable){
return typeof(variable) !== "undefined" && variable !== null && variable !== '';
}
Here is a usage example of how to use it:
var example = 'this is an example';
if(isset(example)){
console.log('the example variable has a value set');
}
It depends on the situation you need it for but let me break down what each part does:
typeof(variable) !== "undefined" checks if the variable is defined at all
variable !== null checks if the variable is null (some people explicitly set null and don't think if it is set to null that that is correct, in that case, remove this part)
variable !== '' checks if the variable is set to an empty string, you can remove this if an empty string counts as set for your use case
Hope this helps someone :)
Not naturally, no... However, a googling of the thing gave this: http://phpjs.org/functions/isset:454
http://phpjs.org/functions/isset:454
phpjs project is a trusted source. Lots of js equivalent php functions available there. I have been using since a long time and found no issues so far.
The problem is that passing an undefined variable to a function causes an error.
This means you have to run typeof before passing it as an argument.
The cleanest way I found to do this is like so:
function isset(v){
if(v === 'undefined'){
return false;
}
return true;
}
Usage:
if(isset(typeof(varname))){
alert('is set');
} else {
alert('not set');
}
Now the code is much more compact and readable.
This will still give an error if you try to call a variable from a non instantiated variable like:
isset(typeof(undefVar.subkey))
thus before trying to run this you need to make sure the object is defined:
undefVar = isset(typeof(undefVar))?undefVar:{};
Here :)
function isSet(iVal){
return (iVal!=="" && iVal!=null && iVal!==undefined && typeof(iVal) != "undefined") ? 1 : 0;
} // Returns 1 if set, 0 false
in addition to #emil-vikström's answer, checking for variable!=null would be true for variable!==null as well as for variable!==undefined (or typeof(variable)!="undefined").
You can just:
if(variable||variable===0){
//Yes it is set
//do something
}
else {
//No it is not set
//Or its null
//do something else
}

Categories