Bitesize Bugs

Accidental Global Variables in JavaScript

Omitting the “var” keyword when declaring a variable in JavaScript will scope it to the global namespace.

Thus, the variable is no longer bound to the scope of the parent function or object instance, but accessibile to every other script through the global “window” object.

Example

SeeĀ https://gist.github.com/1092039

Avoid accidentally creating global variables by always declaring them with ‘var’.

This problem gets especially frustrating when expecting variables to be private, bound to instances of an object. You soon realize that your instances’ internal states change unexpectedly.


 

 

 

 

 

Advertisements

Filed under: JavaScript, , , , , , , ,

Zero is ‘falsy’ in JavaScript

Numeric zero in JavaScript is a ‘falsy’ value.
If it is used in a conditional operator it will act as false.

Example:

var checkValue = function(value){
    var check = "";

    if(value){
       check = "it was "+value;
    }
    else{
       check = "no value";
    }

    return check;
}

// number; returns "no value"
console.log(checkValue(0)); 

// string; returns "it was 0"
console.log(checkValue("0"));

Related reading:

Falsy values – extract from “JavaScript: The Good Parts”
Truthy and falsy in JavaScript

Filed under: Front-end, JavaScript, , , , , ,

typeof NaN in JavaScript

The typeof NaN in JavaScript is number.
This is because NaN is a property of the Number object.

Example:

var num = Number("string value");
console.log(num); // returns NaN
console.log(typeof num); //returns 'number'

Background:

NaN stands for Not-a-number.
It is used to indicate that a value is not numeric.

Filed under: Front-end, JavaScript, , , , ,

So what’s it about?

Bitesize Bugs is a collection of short articles that expose pesky bugs in front-end web technologies like JavaScript, CSS, HTML and browser behaviors gone bad.