HTML and CSS Reference
In-Depth Information
Suddenly, that undefined output makes sense. Be careful! Declare all your variables up front so that this scenario
doesn't catch you unawares, and make sure they have sane default values.
As a further illustration, let's take a look at the following example:
var myHealth = 100;
var decrementHealth = function(health) {
var myHealth = health;
myHealth--;
console.log(myHealth);
};
decrementHealth(myHealth);
console.log(myHealth);
This will output 99 first, then 100 , because you're setting myHealth to the value of health inside the function
rather than setting by reference.
JavaScript Typing and Equality
Now that you understand the basics of variables, let's talk about what types of values those variables can take.
JavaScript is a loosely typed language, with a few base types and automatic coercion between types (for more
information, see the section “Type Coercion”).
Base Types
JavaScript only has a few basic types for you to keep in mind:
1.
Numbers
2.
Strings
3.
Booleans
4.
Objects
5.
Arrays
6. null
7. undefined
Numbers
Numbers are fairly self-explanatory. They can be any number, with or without a decimal point or described using
scientific notation, such as 12e-4 .
Most languages treat at least integers and floating-point numbers differently. JavaScript, however, treats all
numbers as floating point.
It would take too long to go into the potential problems with floating-point numbers here. Suffice it to say that
if you're not careful, you can easily run into floating-point errors. If you want to learn more about the pitfalls of
floating-point arithmetic, I'd recommend checking out the Institute of Electrical and Electronics Engineers (IEEE)
spec IEEE 754: Standard for Binary Floating-Point Arithmetic .
 
Search WWH ::




Custom Search