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

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
}
}

Related

JavaScript objects update function not working

im studying JavaScript and im trying to solve the problem in this test exercise:
FreeCodeCamp Record Collection
I can't understand why it doesnt work. The object details and the problem description are in the link above.
function updateRecords(object, id, prop, value) {
if (value === '') {
delete object[id][prop];
} else if (prop === 'tracks') {
if (object[id][prop].hasOwnProperty('tracks') == false) {
object[id][prop] = [value];
} else if (value !== '') {
object[id][prop].push(value);
}
} else if (prop !== 'tracks' && value !== '') {
object[id][prop] = value;
}
return object;
}
This is the error i get:
// running tests
After updateRecords(collection, 5439, "tracks", "Take a Chance on Me"), tracks should have Take a Chance on Me as the last element.
After updateRecords(collection, 2468, "tracks", "Free"), tracks should have 1999 as the first element.
// tests completed
Thank you for your support.
Let's take a look at this line:
if (object[id][prop].hasOwnProperty('tracks') == false) {
If we replace the variables with their values, we get:
if (object[5439]['tracks'].hasOwnProperty('tracks') == false) {
^ ^
... which is always going to fail. Here is a simplified version:
function updateRecords(object, id, prop, value) {
if (value === '') {
delete object[id][prop];
} else if (prop === 'tracks') {
if (!object[id].hasOwnProperty('tracks')) {
object[id][prop] = [];
}
object[id][prop].push(value);
} else {
object[id][prop] = value;
}
return object;
}

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!
}

Getting strange error when running the following function

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);

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 if statement question

function valid()
{
begin_checked = false;
end_checked = false;
alert("begin_checked: " +begin_checked);
alert("end_checked: " +end_checked);
if (document.dd.begin.checked.length == undefined || document.dd.end.checked.length == undefined )
{
alert("In undefined");
}
alert("end");
}
When the if statement is false, it never gets to alert("end") ? When it is true, it executes properly. Why?
There is probably a null pointer exception and you do not have errors outputting to your browser.
You need some output to check:
alert(document);
alert(document.dd);
alert(document.dd.begin);
alert(document.dd.begin.checked);
alert(document.dd.end);
alert(document.dd.end.checked);
If you get undefined from any of those, then your code will not execute properly.
Edit: Also, the other answers here all have good information. Read those as well.
Edit2: Alternative - Surround your code in a try/catch block and alert the error:
function valid(){
try{
begin_checked = false;
end_checked = false;
alert("begin_checked: " +begin_checked);
alert("end_checked: " +end_checked);
if (document.dd.begin.checked.length == undefined || document.dd.end.checked.length == undefined ){
alert("In undefined");
}
alert("end");
} catch (e) {
alert(e);
}
}
Are there any errors in your browsers error console? I'm guessing it's because it's trying to evaluate a property that doesn't exist, this causing it to fail (never getting to the == undefined). You can just check that the property exists or use the typeof to check if it's undefined.
if (!document.dd.begin.checked.length || !document.dd.end.checked.length)
{
alert("In undefined");
}
if (typeof document.dd.begin.checked.length == 'undefined' || typeof document.dd.end.checked.length == 'undefined' )
{
alert("In undefined");
}
http://getfirebug.com/

Categories