-2

I using a json array in my external js file. This array is declared by some required pages and not using of my all pages. My problem is there is "variable not defined error message" showing when using the pages which is not required this array.

In my case I cannot declare this array to access in all the pages. So may I know is there any possible way to check array is defined or not even its not declared in jQuery.

I had some experiment with the given answers of this question. But I couldn't figure this out.

This is my code from JS file:

// var myArray={}
// if(myArray){
// if( typeof myArray !== 'undefined' || myArray !== null ){
if( myArray !== 'undefined' || myArray !== null ){
  var obj = JSON.parse(JSON.stringify(myArray));
  var initialPreview; 
  if(obj.initialPreview) {
    var initialPreview = obj.initialPreview; 
  } 
}

Console Error is ncaught ReferenceError: myArray is not defined

user3733831
  • 2,886
  • 9
  • 36
  • 68
  • `if (typeof variable !== 'undefined') { // the variable is defined }` https://stackoverflow.com/questions/5113374/javascript-check-if-variable-exists-is-defined-initialized – Kinglish Jun 03 '21 at 06:09
  • All you need is `if( typeof myArray !== 'undefined'`. If you do `if(myArray){`, ReferenceError. If you do `typeof myArray !== 'undefined' || myArray !== null`, ReferenceError once it tries testing the other side of the `||`. – CertainPerformance Jun 03 '21 at 06:09

1 Answers1

-2

you can try this code below. It will return true or false

Array.isArray(myArray)
Hoang Le
  • 78
  • 3