Getting strange error when running the following function - javascript

I am trying to do something like
HTML('slider1') = someimage;
But my HTML() function is not returning document.getElementById('slider1');
function HTML(id){
if(typeof value !== undefined){
return document.getElementById(id).innerHTML;
}
}

typeof allows the identifier to never have been declared before.
function HTML(id){
if(typeof value == "undefined")
{
//do nothing
}else{
return document.getElementById(id).innerHTML;
}
}
You can also try
if(typeof neverDeclared === typeof undefined) //also no errors and no strings

I think you are trying to assign some image through innerHTML, you may update your function to something like this
function HTML(id){
if(typeof value !== undefined){
return document.getElementById(id);
}
}
HTML('slider1').innerHTML = someimage;
//OR
function HTML(id, htmlChunk){
if(typeof value !== undefined){
document.getElementById(id).innerHTML = htmlChunk;
}
}
HTML('slider1',someimage);

Related

how to check a deeply nested object is undefined? [duplicate]

This question already has answers here:
How to avoid 'cannot read property of undefined' errors?
(18 answers)
How can I check for "undefined" in JavaScript? [duplicate]
(16 answers)
Closed 2 years ago.
I would like to check whether an object is undefined
this.state.data.value[0].name
I attempted the following
and these will say Type error this.state.data.value is undefined in the console.
if(typeof this.data.value[0].name=== "undefined"){
//do something
}
if(this.data.value[0].name == undefined){
//do something
}
if(!!this.data.value[0].name){
//do something
}
if(!this.data.value[0].name){
//do something
}
if(this.data){
if(this.data.value){ // It says type error, this.state.value is undefined in the console.
}
}
How shall I check the object this.state.value[0].name is undefined?
I attempted this
if (typeof (this.data) !== undefined) {
debugger;
if (typeof (this.data.value) !== undefined) {
debugger;
if (typeof (this.data.value[0].name != undefined)) {//cannot read value [0]
debugger;
}
}
}
My Solution, thanks to pranav-c-balan
if (this.data && this.data.value && this.data.value[0] && this.data.value[0].name) {
return true;
} else {
document.getElementById("myDIV").innerHTML =
"<b>Custom Error Text</b>";
return false;
}
A working Example
let data={};
data.value=[{name:123}];
function checkValue(){
if(data && data.value && data.value[0] && data.value[0].name){
return true;
}else{
return false;
}
}
let correct=checkValue();
if(correct){
console.log("This is valid, data.value[0].name Exist");
}else{
console.log("This is invalid,data.value[0].name do not Exist");
}
function checkValue2(){
if(data && data.value && data.value[0] && data.value[0].names){
return true;
}else{
return false;
}
}
let correct2=checkValue2();
if(correct2){
console.log("This is valid, data.value[0].names Exist");
}else{
console.log("This is invalid,data.value[0].names do not Exist");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.0/react-dom.min.js"></script>
You can check your object by using optional chaining (?.).
This will check every part of your chain. Say if it is undefined the data inside the state then it returns undefined excepts throwing an error.
let state = {
data: {
value: [
{name: 'value'}
]
}
}
console.log(typeof state?.data?.value?.[0]?.name);
console.log(typeof state?.data?.value?.[1]?.name);
console.log(typeof state?.datum?.value?.[0]?.name); // In this case it returns 'undefined' for dutum stage.
Note
Optional chaining has poor browser support until now. So you have to use Babel or any other Javascript compiler for browser support.
Just use the same typeof operator:
if(typeof(this.state) != 'undefined'){
if(typeof(this.state.value) != 'undefined') {
// next source
}
}

strict equality check for undefined

I cant seem to figure this answer out so maybe you could help shed some light. In my defense, undefined is a message returned when a variable, key, value etc could not be found. A message should be a string? No?
let foo = [{id: 1, you: "me"}]
let undif = foo.find(i => i.he === 1)
if (typeof undif === "undefined") {
console.log(undif) // not fired
}
if (typeof undif == undefined) {
console.log(undif) // not fired
}
if (typeof undif == 'undefined') {
console.log(undif) // fired!
}
Why cant I use typeof undif === 'undefined?
triple equals looks for both value and type;
hence undefined === 'undefined' will return false
for same reason your first case returns true
This is a wonderful article on double equals and triple equals along with falsy value comparsion
Your code had syntax errors (missing the opening braces after every if), but once those are fixed, the first and third are both fired.
let foo = [{id: 1, you: "me"}]
let undif = foo.find(i => i.he === 1)
if (typeof undif === "undefined") {
console.log('1', undif) // fired
}
if (typeof undif == undefined) {
console.log('2', undif) // not fired
}
if (typeof undif == 'undefined') {
console.log('3', undif) // fired!
}

Shorthand to avoid falsy 0 value

I have a server response that sends back an object like so:
{
success: integer
}
On the client, I have
return body && body.success;
the problem is that the integer might be zero, in which case the above would return body instead of body.success.
What is the best shorthand I can use to always return the value?
You should always initialize your property in the back end. I would set as "-1".
function ajaxCall() {
return { success: true, id: 10 };
//return null;
}
function GetData() {
var myData = ajaxCall();
if (typeof myData === "undefined"
|| myData == null
|| typeof myData.success === "undefined"
|| myData.success == null) {
return { success: false, id: 0 };
}
return myData;
}
var body = GetData();
// init
(function(){
document.getElementById("MyMessage").innerHTML = ((body.success) ? "Success - " + body.id : "Failed") ;
})();
<div id="MyMessage"></div>
Would this work:
return body && (typeof body.success !== "undefined" ? body.success : false);
The parenthesis may be incorrect, but this should check is body defined? If so, is body.success defined? If not return body.
If body.success is defined, return body.success. If not, return body.
It could be written this way:
If (body)
return (typeof body.success !== "undefined" ? body.success : body);
else return false;

JavaScript isset() function [duplicate]

This question already has answers here:
JavaScript isset() equivalent
(28 answers)
Closed 6 years ago.
How to check isset in javascript.
I have used in the following way.
var sessionvalue = document.getElementById('sessionvalue').value;
if(Here I have to check if isset the sessionvalue or not){
if(sessionvalue == "" || sessionvalue == null)
{
document.getElementById('sessionvalue').style.borderColor="red";
return false;
}
else
{
document.getElementById('sessionvalue').style.borderColor="#ccc";
}
}
When javascript variables are not declared and you try to call them, they return undefined, so you can do:
if (typeof sessionvalue == "undefined" || sessionvalue == null)
You can just do:
if(sessionvalue)
The above will automatically check for undefined, null (And NaN ,false,"")
You can even make it a global function if you need it like you're used to in php.
function isset(_var){
return !!_var; // converting to boolean.
}
if(typeof(data.length) != 'undefined')
{
// do something
}
if(empty(data))
{
// do something
}
if(typeof(data) == 'undefined' || data === null)
{
//do something
}
you can just do if(sessionvalue) that's it you don't need anything else and remember you can compare apples with cars in javascript, you can check if value is null or undefined with if(sessionvalue) or if(!sessionvalue), your code will be :
document.getElementById('sessionvalue').style.borderColor= sessionvalue ? "red" : "#CCC";
Try Code as below
var sessionvalue=document.getElementById('sessionvalue').value;
if(typeof sessionvalue != 'undefined'){
if(sessionvalue=="" || sessionvalue == null)
{
document.getElementById('sessionvalue').style.borderColor="red";
return false;
}
else
{
document.getElementById('sessionvalue').style.borderColor="#ccc";
}
}

Javascript isset function

I created an isset function to check if a variable is defined and not null.
Here's my code:
isset = function(a) {
if ((typeof (a) === 'undefined') || (a === null))
return false;
else
return true;
};
var a = [];
// Test 1
alert(isset(a['not']); // Alerts FALSE -> works OK
// Test 2
alert(isset(a['not']['existent'])); // Error: Cannot read property 'existent' of undefined
Any suggestion to make my function work for test 2?
Thanks.
You are trying to check property of an undefined object. It doesn't make any sense. You could write like this:
alert(isset(a['not']) && isset(a['not']['existent']));
that won't work, and you can't make it work.
what happens is this:
the js engine tries to evaluate a['not'] and get's "undefined", then it tries to evaluate the property 'existent' of the undefined and you get that error.
all of that happens before the call to your function...
what you can do is something like:
var isset = function(obj, props) {
if ((typeof (obj) === 'undefined') || (obj === null))
return false;
else if (props && props.length > 0)
return isset(obj[props.shift()], props);
else
return true;
};
then you call it like this:
var a = [];
// Test 1
alert(isset(a, ['not']);
// Test 2
alert(isset(a, ['not', 'existent']));
(**this just a pseudo code, you might need to modify it a bit to actually work)
Test 2 will not work because "a['not']['existent']" value resolution precedes "isset" function call, and results in a runtime error.
Well, You can do right this:
1) as we do in php:
$vara = "abc";
$a =0;
while(isset($vara[a]){
a++;
}
2) as I do in javascript:
vara = "abc";
while (vara[a] != null){
a++;
}

Categories