JavaScript Variables: Initialization, Booleans, and Numbers

code-820275_640Uninitialized variables show as a type of undefined. So do variables that haven’t been declared at all.

We should always initialize variables so that we know that undefined means we haven’t declared the variable.

null is an empty object pointer. We should initialize objects to null so that the typeof will return the correct data type.

null and undefined are equal (null == undefined) //true.

true is not equal to 1 and false is not equal to 0.

true and false are Boolean literals. They are different from True and False which are identifiers, not Boolean values.

You can use Boolean(message) to type cast a variable to a Boolean value. Non-empty strings, nonzero numbers and objects will convert to true and empty strings, 0, NaN, null and undefined will convert to false The if statement (and other flow control statements) automatically perform the Boolean conversion.

Decimal integers without a leading zero initialize Number type variables. Numbers with a leading zero indicate an octal number UNLESS a digit is greater than 7, then it’s treated as a decimal number. If the number starts with 0x it will be treated as a hexadecimal number.

var o = 040; //octal
var h = 0xA; //hex (case doesn't matter 0xa = 0xA)
var d = 77;  //decimal
var x = 077; //octal
var y = 078; //decimal

Decimal, octal and hexadecimal numbers are all treated as decimal in arithmetic operations.

In JavaScript, you can have a negative zero (-0) or positive zero (+0). They are equivilent (-0=+0).

Floating-point numbers must have a decimal point and a number following the decimal point (i.e. .1). It is recommended to have a number before the decimal point.

If a floating-point number can be converted to an integer, it will to save space (i.e. 7.0 or 10..

E-notation is valid for large numbers (i.e. x = 4.235e7) or very small numbers (i.e. x = 3e-17.

Floating-point values are often inaccurate in arithmetic because of small rounding errors, so you should never test for specific floating-point values. (This is not a JavaScript problem but a side effect of arithmetic wiht IEEE-754-based numbers.)

There are minimum and maximum values for numbers called negative infinity and positive infinity. We can test for a number between these two values with isFinite().

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top