The difference between undefined and null in JavaScript

Source: Internet
Author: User

Typically, when we try to access something that doesn't exist.Or variable with no value assigned, you will get a undefinedValue. JavaScript automatically sets the variable that is declared to be not initialized to undifined.

What happens if a variable doesn't exist at all:

>>> Fooreferenceerror: foo is not defined

We got an error message. We use the typeof operator on this variable to see what type it is:

>>> typeof Foo "undefined"

The result we get is the string "undefined".

If we do not assign a variable when we declare it, the variable is called without error, but the typeof operator still returns the string "undefined".

>>> var somevar;>>> somevar;undefined>>> typeof Somevar; " undefined"

And the null value is completely different. He cannot come from a dynamic assignment through JavaScript, which means that we have to manually assign a value to NULL for a variable:

>>> var somevar = null;>>> Somevar; NULL

Moreover, the TypeOf operator returns an Object!

>>> typeof Somevar; " Object"

Although the difference between undefine and Null is not very large, they behave very differently in some arithmetic operations:

>>> var i = 1 + undefined; I NaN>>> var i = 1 + null; I 1

This is because the method has some difference when undefined and null are converted to other basic types, and we give some possible types of conversions below.

Convert to a number (treat undefined as a string, null as 0):

>>> 1 * undefined; Nan>>> 1 * null;0

Convert to a Boolean value:

>>>!! Undefined;false>>>!! Null;false converted to a string (all corresponding to a string):>>> "+undefined;" Undefined ">>>" +null; Null

The above is the difference between undefined and null, and where operations are to be noted.

The difference between undefined and null in JavaScript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.