Oc-windows.ru

IT Новости из мира ПК
3 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Javascript is defined

JavaScript check if variable exists (is defined/initialized)

Which method of checking if a variable has been initialized is better/correct? (Assuming the variable could hold anything (string, int, object, function, etc.))

24 Answers 24

The typeof operator will check if the variable is really undefined.

The typeof operator, unlike the other operators, doesn’t throw a ReferenceError exception when used with an undeclared variable.

However, do note that typeof null will return «object» . We have to be careful to avoid the mistake of initializing a variable to null . To be safe, this is what we could use instead:

For more info on using strict comparison === instead of simple equality == , see:
Which equals operator (== vs ===) should be used in JavaScript comparisons?

In many cases, using:

will do the job for you. this will check these below cases:

  1. undefined: if the value is not defined and it’s undefined
  2. null: if it’s null, for example, if a DOM element not exists.
  3. empty string: »
  4. : number zero
  5. NaN: not a number
  6. false

So it will cover off kind of all cases, but there are always weird cases which we’d like to cover as well, for example, a string with spaces, like this ‘ ‘ one, this will be defined in javascript as it has spaces inside string. for example in this case you add one more check using trim(), like:

Also, these checks are for values only, as objects and arrays work differently in Javascript, empty array [] and empty object <> are always true.

I create the image below to show a quick brief of the answer:

In JavaScript, a variable can be defined, but hold the value undefined , so the most common answer is not technically correct, and instead performs the following:

That may suffice for your purposes. The following test has simpler semantics, which makes it easier to precisely describe your code’s behavior and understand it yourself (if you care about such things):

This, of course, assumes you are running in a browser (where window is a name for the global object). But if you’re mucking around with globals like this you’re probably in a browser. Subjectively, using ‘name’ in window is stylistically consistent with using window.name to refer to globals. Accessing globals as properties of window rather than as variables allows you to minimize the number of undeclared variables you reference in your code (for the benefit of linting), and avoids the possibility of your global being shadowed by a local variable. Also, if globals make your skin crawl you might feel more comfortable touching them only with this relatively long stick.

In the majority of cases you would use:

Unlike a simple if (elem) , it allows 0 , false , NaN and » , but rejects null or undefined , making it a good, general test for the presence of an argument, or property of an object.

The other checks are not incorrect either, they just have different uses:

if (elem) : can be used if elem is guaranteed to be an object, or if false , 0 , etc. are considered «default» values (hence equivalent to undefined or null ).

typeof elem == ‘undefined’ can be used in cases where a specified null has a distinct meaning to an uninitialised variable or property.

  • This is the only check that won’t throw an error if elem is not declared (i.e. no var statement, not a property of window , or not a function argument). This is, in my opinion, rather dangerous as it allows typos to slip by unnoticed. To avoid this, see the below method.

Also useful is a strict comparison against undefined :

However, because the global undefined can be overridden with another value, it is best to declare the variable undefined in the current scope before using it:

A secondary advantage of this method is that JS minifiers can reduce the undefined variable to a single character, saving you a few bytes every time.

Check if window . hasOwnProperty (» varname «)

An alternative to the plethora of typeof answers;

Global variables declared with a var varname = value; statement in the global scope

can be accessed as properties of the window object.

As such, the hasOwnProperty() method, which

returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it)

can be used to determine whether

a var of «varname» has been declared globally i.e. is a property of the window .

What’s great about hasOwnProperty() is that in calling it, we don’t use a variable that might as yet be undeclared — which of course is half the problem in the first place.

Although not always the perfect or ideal solution, in certain circumstances, it’s just the job!

Notes

The above is true when using var to define a variable, as opposed to let which:

declares a block scope local variable, optionally initializing it to a value.

is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.

Читать еще:  Java sql sqlexception invalid column index

At the top level of programs and functions, let , unlike var , does not create a property on the global object.

For completeness: const constants are, by definition, not actually variable (although their content can be); more relevantly:

Global constants do not become properties of the window object, unlike var variables. An initializer for a constant is required; that is, you must specify its value in the same statement in which it’s declared.

The value of a constant cannot change through reassignment, and it can’t be redeclared.

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned.

Since let variables or const constants are never properties of any object which has inherited the hasOwnProperty() method, it cannot be used to check for their existence.

Regarding the availability and use of hasOwnProperty() :

Every object descended from Object inherits the hasOwnProperty() method. [. ] unlike the in operator, this method does not check down the object’s prototype chain.

how to check if a javascript variable is defined?

Add New Comment

Do you have the same question? Follow this Question

9 answers

Answers

Jan 09, 2007 — 11:28 AM

Here are some reliable testing scenarios for a javascript variable:

if (x == null)alert(«x is undefined»);
else if (x === false)alert(«x is false»);
else if (x === true)alert(«x is true»);
elsealert(«x is » + x);

Remarks:
Declare your variable in the beginning of your script if you know you’re gonna test it later. Don’t give it a value at this point.
A declared variable that has not been assigned a value will have the value ‘null’

Use the === compare operator to check whether the variable is really boolean false.
The == operator is not reliable as a value of 0 will also evaluate to false.
(Basically, the === asks whether variable are of same value AND datatype!)

Hope this helps!
Cheers, Jakob

Add New Comment

Jan 09, 2007 — 11:36 AM

Add New Comment

Jan 09, 2007 — 11:48 AM

Add New Comment

Jan 09, 2007 — 12:28 PM

Yeah, I wasn’t able to find a solution so far for the case that it is not even declared — any testing on a non-declared variable gives a javascript error «x is not defined».

Instead of an individual variable you could also try working with a property of a declared object. That way you don’t have to declare the specific property first. You do have to declare the object though, but that could be used for multiple purposes.

Keep me posted if you come across a way of checking wether a variable has been declared.

Add New Comment

Jan 09, 2007 — 12:39 PM

I just checked the link you posted and found this easy solution:

if (window.x === undefined) alert(«x is undefined»);

Just add the «window.» in front of the variable name, then you won’t get the error message and the expression will evaluate to true in both cases;
— if the variable has been declared but not assigned
— if the variable has simply not been declared.

Actually it’s related to what I suggested about using a property instead of a variable. Since all variables are also properties of the window object!

Add New Comment

Feb 10, 2007 — 03:01 AM

Add New Comment

Feb 11, 2007 — 09:38 AM

Here is an example (testing the variable «x»):

if (window.x === undefined) alert(«x is undefined/undeclared»);
else if (x === false) alert(«x is false»);
else if (x === true) alert(«x is true»);
else alert(«x is » + x);

In the first line I am using «window.x» instead of just «x». This works because all variables are also defines as properties of the window object.
«x === undefined» will only work if the variable has actually been declared with «var x» (but not assigned a value). Therefore it is safer to use «window.x» which will not result in an error if the variable hasn’t been declared.

Use the === compare operator to check whether the variable is really boolean false.
The == operator is not reliable as a value of 0 will also evaluate to false.
(Basically, the === asks whether variable are of same value AND datatype!)

JavaScript check if variable exists (is defined/initialized)

Which method of checking if a variable has been initialized is better/correct? (Assuming the variable could hold anything (string, int, object, function, etc.))

24 Answers 24

The typeof operator will check if the variable is really undefined.

The typeof operator, unlike the other operators, doesn’t throw a ReferenceError exception when used with an undeclared variable.

Читать еще:  Reverse arraylist java

However, do note that typeof null will return «object» . We have to be careful to avoid the mistake of initializing a variable to null . To be safe, this is what we could use instead:

For more info on using strict comparison === instead of simple equality == , see:
Which equals operator (== vs ===) should be used in JavaScript comparisons?

In many cases, using:

will do the job for you. this will check these below cases:

  1. undefined: if the value is not defined and it’s undefined
  2. null: if it’s null, for example, if a DOM element not exists.
  3. empty string: »
  4. : number zero
  5. NaN: not a number
  6. false

So it will cover off kind of all cases, but there are always weird cases which we’d like to cover as well, for example, a string with spaces, like this ‘ ‘ one, this will be defined in javascript as it has spaces inside string. for example in this case you add one more check using trim(), like:

Also, these checks are for values only, as objects and arrays work differently in Javascript, empty array [] and empty object <> are always true.

I create the image below to show a quick brief of the answer:

In JavaScript, a variable can be defined, but hold the value undefined , so the most common answer is not technically correct, and instead performs the following:

That may suffice for your purposes. The following test has simpler semantics, which makes it easier to precisely describe your code’s behavior and understand it yourself (if you care about such things):

This, of course, assumes you are running in a browser (where window is a name for the global object). But if you’re mucking around with globals like this you’re probably in a browser. Subjectively, using ‘name’ in window is stylistically consistent with using window.name to refer to globals. Accessing globals as properties of window rather than as variables allows you to minimize the number of undeclared variables you reference in your code (for the benefit of linting), and avoids the possibility of your global being shadowed by a local variable. Also, if globals make your skin crawl you might feel more comfortable touching them only with this relatively long stick.

In the majority of cases you would use:

Unlike a simple if (elem) , it allows 0 , false , NaN and » , but rejects null or undefined , making it a good, general test for the presence of an argument, or property of an object.

The other checks are not incorrect either, they just have different uses:

if (elem) : can be used if elem is guaranteed to be an object, or if false , 0 , etc. are considered «default» values (hence equivalent to undefined or null ).

typeof elem == ‘undefined’ can be used in cases where a specified null has a distinct meaning to an uninitialised variable or property.

  • This is the only check that won’t throw an error if elem is not declared (i.e. no var statement, not a property of window , or not a function argument). This is, in my opinion, rather dangerous as it allows typos to slip by unnoticed. To avoid this, see the below method.

Also useful is a strict comparison against undefined :

However, because the global undefined can be overridden with another value, it is best to declare the variable undefined in the current scope before using it:

A secondary advantage of this method is that JS minifiers can reduce the undefined variable to a single character, saving you a few bytes every time.

Check if window . hasOwnProperty (» varname «)

An alternative to the plethora of typeof answers;

Global variables declared with a var varname = value; statement in the global scope

can be accessed as properties of the window object.

As such, the hasOwnProperty() method, which

returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it)

can be used to determine whether

a var of «varname» has been declared globally i.e. is a property of the window .

What’s great about hasOwnProperty() is that in calling it, we don’t use a variable that might as yet be undeclared — which of course is half the problem in the first place.

Although not always the perfect or ideal solution, in certain circumstances, it’s just the job!

Notes

The above is true when using var to define a variable, as opposed to let which:

declares a block scope local variable, optionally initializing it to a value.

is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.

At the top level of programs and functions, let , unlike var , does not create a property on the global object.

Читать еще:  Java security cert certpathvalidatorexception trust

For completeness: const constants are, by definition, not actually variable (although their content can be); more relevantly:

Global constants do not become properties of the window object, unlike var variables. An initializer for a constant is required; that is, you must specify its value in the same statement in which it’s declared.

The value of a constant cannot change through reassignment, and it can’t be redeclared.

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned.

Since let variables or const constants are never properties of any object which has inherited the hasOwnProperty() method, it cannot be used to check for their existence.

Regarding the availability and use of hasOwnProperty() :

Every object descended from Object inherits the hasOwnProperty() method. [. ] unlike the in operator, this method does not check down the object’s prototype chain.

JavaScript Function Definitions

JavaScript functions are defined with the function keyword.

You can use a function declaration or a function expression.

Function Declarations

Earlier in this tutorial, you learned that functions are declared with the following syntax:

Declared functions are not executed immediately. They are «saved for later use», and will be executed later, when they are invoked (called upon).

Example

Semicolons are used to separate executable JavaScript statements.
Since a function declaration is not an executable statement, it is not common to end it with a semicolon.

Function Expressions

A JavaScript function can also be defined using an expression.

A function expression can be stored in a variable:

Example

After a function expression has been stored in a variable, the variable can be used as a function:

Example

The function above is actually an anonymous function (a function without a name).

Functions stored in variables do not need function names. They are always invoked (called) using the variable name.

The function above ends with a semicolon because it is a part of an executable statement.

The Function() Constructor

As you have seen in the previous examples, JavaScript functions are defined with the function keyword.

Functions can also be defined with a built-in JavaScript function constructor called Function() .

Example

var myFunction = new Function(«a», «b», «return a * b»);

var x = myFunction(4, 3);

You actually don’t have to use the function constructor. The example above is the same as writing:

Example

var myFunction = function (a, b) ;

var x = myFunction(4, 3);

Most of the time, you can avo >new keyword in JavaScript.

Function Hoisting

Earlier in this tutorial, you learned about «hoisting» (JavaScript Hoisting).

Hoisting is JavaScript’s default behavior of moving declarations to the top of the current scope.

Hoisting applies to variable declarations and to function declarations.

Because of this, JavaScript functions can be called before they are declared:

function myFunction(y) <
return y * y;
>

Functions defined using an expression are not hoisted.

Self-Invoking Functions

Function expressions can be made «self-invoking».

A self-invoking expression is invoked (started) automatically, without being called.

Function expressions will execute automatically if the expression is followed by ().

You cannot self-invoke a function declaration.

You have to add parentheses around the function to indicate that it is a function expression:

Example

The function above is actually an anonymous self-invoking function (function without name).

Functions Can Be Used as Values

JavaScript functions can be used as values:

Example

function myFunction(a, b) <
return a * b;
>

var x = myFunction(4, 3);

JavaScript functions can be used in expressions:

Example

function myFunction(a, b) <
return a * b;
>

var x = myFunction(4, 3) * 2;

Functions are Objects

The typeof operator in JavaScript returns «function» for functions.

But, JavaScript functions can best be described as objects.

JavaScript functions have both properties and methods.

The arguments.length property returns the number of arguments received when the function was invoked:

Example

The toString() method returns the function as a string:

Example

function myFunction(a, b) <
return a * b;
>

var txt = myFunction.toString();

A function defined as the property of an object, is called a method to the object.
A function designed to create new objects, is called an object constructor.

Arrow Functions

Arrow functions allows a short syntax for writing function expressions.

You don’t need the function keyword, the return keyword, and the curly brackets.

Example

// ES5
var x = function(x, y) <
return x * y;
>

// ES6
const x = (x, y) => x * y;

Arrow functions do not have their own this . They are not well suited for defining object methods.

Arrow functions are not hoisted. They must be defined before they are used.

Using const is safer than using var , because a function expression is always constant value.

You can only omit the return keyword and the curly brackets if the function is a single statement. Because of this, it might be a good habit to always keep them:

Example

Arrow functions are not supported in IE11 or earlier.

Ссылка на основную публикацию
Adblock
detector