Javascript unassigned var?

What happens to a variable declared in Javascript if no initial value has been assigned to it?

Suppose I declare a variable below

var cancel;

Now, does this "cancel" variable have a value or is it null or what?

Thank.

-3
source share
3 answers

undefinedis a property of a global object, i.e. is a variable in a global area. The initial value undefinedis a primitive value undefined.

In modern browsers (JavaScript 1.8.5 / Firefox 4+) undefined, this is a non-configurable, writable property according to the ECMAScript 5 specification. Even if it is not, avoid overriding it.

, , undefined. undefined, , , . undefined, .

undefined , ( ) , .


var x;
if (x === undefined) {
    // these statements execute
}
else {
    // these statements do not execute
}



typeof

typeof:

var x;
if (typeof x === 'undefined') {
    // these statements execute
}

typeof , , .

// x has not been defined before
if (typeof x === 'undefined') { // evaluates to true without errors
    // these statements execute
}

if(x === undefined){ // throws a ReferenceError

}



void

void .

var x;
if (x === void 0) {
    // these statements execute
}

// y has not been defined before
if (y === void 0) {
    // throws a ReferenceError (in contrast to `typeof`)
}



: MDN - Mozilla

+2

'undefined'.

, (, PHP) 'undefined' - Javascript, , :

if(cancel == undefined) { alert('Cancel is undefined!'); };

Javascript, javascript

typeof

:

var cancel;
var typeOfCancel = typeof cancel; // In this case, undefined

var cancel = true;
var typeOfCancel = typeof cancel; // In this case, boolean

javascript, , โ€‹โ€‹, :

if(cancel == undefined || cancel == null || cancel == '') {
    // React to the empty value here
}

, : http://jsfiddle.net/7bu84/

+1

, undefined. Firebug Chrome.

var cancel;
alert(cancel)
-1
source

Source: https://habr.com/ru/post/1656384/


All Articles