0

I'm trying to load images with javascript, first I get wide size image url and when user open the moda then I'm gonna load wide size images.

I'm try to do it with below way

try {
    images
}
catch(err) {
    if (err.name == "ReferenceError"){
        let images = [];
        let nodes = tab.childNodes[1].children;
        for (let i = 0; i < nodes.length; i++) {
            if (nodes[i].firstElementChild.className === "slider") {
                images.push(nodes[i].firstElementChild.src)
            }
        }
        Images:load(images)
    }
}

But it doesn't work, loads images every time.

I try put these codes inside of these if statement but none of them didn't work too, they gave Uncaught ReferenceError: images is not defined at HTMLElement.<anonymous> error

if (typeof images == 'undefined')

if (typeof images === undefined)

if (typeof images == 'undefined' || images.lenth === 0 )

is there any way to check images variable not declared before ?

Teoman Tıngır
  • 2,766
  • 2
  • 21
  • 41

2 Answers2

-1

Use the following code:

if (typeof variable !== 'undefined') {
    // variable is defined
}
GreatDharmatma
  • 627
  • 5
  • 12
-1

GreatDharmatma is correct. Checking if the variable's type is strictly equal to 'undefined' would help solving your problem.

if (typeof something !== 'undefined') {
    // do stuff when variable was declared
} else {
    // do stuff when variables was not declared
}

I would also suggest you take a look at this question: How to check a not-defined variable in JavaScript

It has a lot of explanations about undefined, not declared and null variables in javascript.