JavaScript "Cannot Read Property "Bar" of Undefined

JavaScript cannot read property bar of undefined

If an object's property may refer to some other object then you can test that for undefined before trying to use its properties:

if (thing && thing.foo)
alert(thing.foo.bar);

I could update my answer to better reflect your situation if you show some actual code, but possibly something like this:

function someFunc(parameterName) {
if (parameterName && parameterName.foo)
alert(parameterName.foo.bar);
}

TypeError: Cannot read property 'bar' of undefined

My guess is you shouldn't use @ViewChild at all. @ViewChild property decorator makes possible to look for element or the directive matching the selector in the view DOM, but your code looks like there is no barchart directive or selector in html. So this.barchart is always undefined. Though, you have a class barchart that can be used. You should create an instance of barchart and call bar:

// home.component.ts
// import your barchar class
import { barchart } from './pathtobarchart';

_barchart: barchart;

constructor(private service : ServiceService) {
// create an instance of barchart class,
// so you can use it inside the methods of
// your HomeComponent
this._barchart = new barchart();
}

drop(event :CdkDragDrop<string[]>) {
if (event.previousContainer === event.container) {
moveItemInArray(event.container.data, event.previousIndex,
event.currentIndex);
} else {
transferArrayItem(event.previousContainer.data, event.container.data , event.previousIndex, event.currentIndex);
this._barchart.bar(event.container.data,event.container.id);
}
}

Detecting an undefined object property

The usual way to check if the value of a property is the special value undefined, is:

if(o.myProperty === undefined) {
alert("myProperty value is the special value `undefined`");
}

To check if an object does not actually have such a property, and will therefore return undefined by default when you try to access it:

if(!o.hasOwnProperty('myProperty')) {
alert("myProperty does not exist");
}

To check if the value associated with an identifier is the special value undefined, or if that identifier has not been declared:

if(typeof myVariable === 'undefined') {
alert('myVariable is either the special value `undefined`, or it has not been declared');
}

Note: this last method is the only way to refer to an undeclared identifier without an early error, which is different from having a value of undefined.

In versions of JavaScript prior to ECMAScript 5, the property named "undefined" on the global object was writeable, and therefore a simple check foo === undefined might behave unexpectedly if it had accidentally been redefined. In modern JavaScript, the property is read-only.

However, in modern JavaScript, "undefined" is not a keyword, and so variables inside functions can be named "undefined" and shadow the global property.

If you are worried about this (unlikely) edge case, you can use the void operator to get at the special undefined value itself:

if(myVariable === void 0) {
alert("myVariable is the special value `undefined`");
}

Cannot read property *******' of undefined

This actually solved the problem.
to use the keyword "root"

passwordMatch(control: AbstractControl): ValidationErrors | null {
const pass = control.root.get('pass');
const cpass = control.root.get('cpass');

if (pass != null && cpass != null) {
console.log("Pass : ", pass.value);
console.log("cpass : ", cpass.value);
if (pass.value != cpass.value) {
console.log("MISMATCH");
return { PasswordMismatch: 'Password Mismatch' }
} else {
console.log("MATCH");
return null;
}
} else {
console.log("MISMATCH2");
return { PasswordMismatch: 'Password Mismatch' };
}
}

How to avoid 'cannot read property of undefined' errors?

Update:

  • If you use JavaScript according to ECMAScript 2020 or later, see optional chaining.
  • TypeScript has added support for optional chaining in version 3.7.
// use it like this
obj?.a?.lot?.of?.properties

Solution for JavaScript before ECMASCript 2020 or TypeScript older than version 3.7:

A quick workaround is using a try/catch helper function with ES6 arrow function:

function getSafe(fn, defaultVal) {
try {
return fn();
} catch (e) {
return defaultVal;
}
}

// use it like this
console.log(getSafe(() => obj.a.lot.of.properties));

// or add an optional default value
console.log(getSafe(() => obj.a.lot.of.properties, 'nothing'));

Cannot read property 'map' of undefined using D3 Bar Chart in Angular 7

The code inside the .subscribe() function runs AFTER the getActiveProjectsStatusByDimension() function returns. So you are trying to map over an undefined object. To solve this, simply put your initAxis() function inside the subscribe block.

ngOnInit() {
this.DashboardService.getActiveProjectsStatusByDimension(
this.statusIndex,
this.dimension
).subscribe(res => {
this.res = res;
this.projectSelectedDimension = JSON.parse(JSON.stringify(res));

this.totalStores = Array();

var storeCountIndex = 2;

for (let k = 0; k < this.projectSelectedDimension.data.length; k++) {
let obj = this.projectSelectedDimension.data[k];
let xAxis = Object.keys(obj)[0];
let yAxis = obj[Object.keys(obj)[0]][storeCountIndex];
// console.log("x:", xAxis);
// console.log("y:", yAxis);
let objBarChart = { store: xAxis, storeCount: yAxis };
this.totalStores.push(objBarChart);
}
this.initAxis() //put it here
});

// this.initAxis();
}


Related Topics



Leave a reply



Submit