typeof
operatorIf you want to check whether a variable has been initialized or defined (i.e. test whether a variable has been declared and assigned a value) you can use the typeof
operator.
The most important reason of using the typeof
operator is that it does not throw the ReferenceError if the variable has not been declared. Let's take a look at the following example:
<script>
var x;
var y = 10;
if(typeof x !== 'undefined'){
// this statement will not execute
alert("Variable x is defined.");
}
if(typeof y !== 'undefined'){
// this statement will execute
alert("Variable y is defined.");
}
// Attempt to access an undeclared z variable
if(typeof z !== 'undefined'){
// this statement will not execute
alert("Variable z is defined.");
}
/* Throws Uncaught ReferenceError: z is not defined,
and halt the execution of the script */
if(z !== 'undefined'){
// this statement will not execute
alert("Variable z is defined.");
}
/* If the following statement runs, it will also
throw the Uncaught ReferenceError: z is not defined */
if(z){
// this statement will not execute
alert("Variable z is defined.");
}
</script>
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
How to Create and Manage Cron Jobs on Linux
Cron job is time based job schedule whic...How to reverse the order of an array in PHP
Use the PHP array_reverse() fu...Laravel 8 Generate Fake Data Using Faker Example
Sometimes you are testing project in loc...10 basic commands that every regular Linux users need to know Part 2
In the previous article, we have di...Django - How to Create Custom Login Page
Within this article we will look at how...