Skip to content

JavaScript : Variables, Types and Values

Every programming language is designed to manipulate values, these values are referred to as Types and the most fundamental characteristics of a programming language is the set of types it supports.  

When a programmer needs to store a value to use for manipulation they will assign it to a variable.

A variable is nothing more than a symbolic name for a value and allows the value to referred to by name.

JavaScript makes use of Variables, Types & Values extensively.

In this post I will attempt to provide enough information on how JavaScript Variables, Types and Values however I do recommend reading [amazon text=JavaScript : The Defenitive Guide&asin=0596805527],   [amazon text=JavaScript: The Good Parts &asin= 0596517742] and  [amazon text=JavaScript Patterns&asin= 0596806752] , these books provide a lot more in depth information than I will ever hope to cover in my tutorials. They are still my number one go to reference guides for JavaScript.

JavaScript: The Good Parts

Douglas Crockford identifies the abundance of good ideas that make JavaScript an outstanding object-oriented programming language

[qodef_button size="medium" type="solid" text="Buy" custom_class="" icon_pack="font_awesome" fa_icon="fa-amazon" link="http://amzn.to/2qZ6ipx" target="_self" color="" hover_color="" background_color="" hover_background_color="" border_color="" hover_border_color="" font_size="" font_weight="" margin=""]

Object to Primitives

In JavaScript, Types can be divided into 2 categories : Primitive and Object types.

JavaScript's primitive types include numbers, strings and booleans.  JavaScript also has special values of null and undefined but they are not numbers, strings or boolean.  

Any value that is not a number, string, boolean, null or undefined is considered an object.

An object is an un-ordered collection of properties where each property has a name and value.  

The JavaScript language also defines a special kind of object known as an array, that represents an ordered collection of numbered values.  

Arrays have some special behaviour that distinguish them from ordinary objects.

Another special kind of object in JavaScript is known as a function .

A function is an object that has executable code associated with it. Functions can be invoked to run executable code and return a computed value. 

Functions behave differently from other kinds of objects and JavaScript defines a special language syntax for working with them. 

The most important thing to remember about functions in JavaScript is that they are true values and that JavaScript programs can treat them like regular objects.

Variables

Before you can use a variable in JavaScript you should declare it.

You declare a variable using the var keyword. You should always use the var keyword to declare your variables in JavaScript because there are some really nasty side effects that can happen if you don't!

JavaScript does not explicitly require you to use the var keyword to declare your variables, but if you don't you'll create what is called an implied global variable.

Variable Scope

A common cause of bugs in a JavaScript Application has to do with Variable Scoping, and peculiarities with how JavaScript deals with variables.

The scope of a variable is a region of  code in which it is defined.  However, variables declared within a function are defined only within the body of the function.

 /*
       In this example we have declared 2 variables  both have the same name
       but one has been declared globally and one has been declared within
       the body of a function one variable will have global scope whilst the 
       other one will have local scope
  */
var myName = "Gary Woodfine - Global Freelance Software Developer"; // global scope
function nameChange() {
   var myName = "John Smith - Local beer brewer";  // local scope
    alert(myName); // THe alert will display "John Smith"
}
nameChange();
alert(myName); //will display "Gary Woodfine - Global Freelance Software Developer"




Creating and assigning a value to a variable without using the var keyword in a function will create an implied global variable and can be used outside the functions scope

/*
   In this example we'll declare a variable within a function without the var keyword,
   and you'll notice that it now has global scope
 */
    function nameChange() {
        myName = "Gary Woodfine - Global Freelance Software Developer";  // this has global  scope

    }
    nameChange();
    alert(myName); //Alert will display "Gary Woodfine - Global Freelance Software Developer"

Function Scope and Hoisting

[qodef_blockquote text="JavaScript does not have block scope always declare your variables at the top of the function rather than declaring closer to the point at which they are used." title_tag="h5" width="80"]

 

Contrary to some other C-based programming languages, JavaScript does not have block scope , JavaScript implements function scope which means variables are visible within the functions in which they are defined and within any functions that nested within that function.

 /*
       In this example we'll create function scoped variable that will be accessible to all nested functions

     */
    function whoseAvailable(type) {
        var availableResource = "";       //function scoped variable
        if (type === "brewer") {
            anyBrewersAvailable();
        }
        else if (type == "developer") {
            anyDevelopersAvailable()
        }else{
            availableResource = "No One is available";
        }
        function anyBrewersAvailable() {                 // A nested function
            availableResource = "John Smith - local beer brewer"      // We can assign the value to variable
        }

        function anyDevelopersAvailable() {             // another nested function
            availableResource = 'Gary Woodfine - freelance software developer';
        }
        return availableResource;
    }

    alert(whoseAvailable("brewer"));
    alert (whoseAvailable("developer"));
    alert(whoseAvailable(""));




function scope means that all variables declared within a function are visible throughout the body of the function. This actually means that variables are even visible before they are declared!  This feature of JavaScript is informally known as hoisting , which means that all variables declarations in a function are hoisted to the top of a function.

/*
   An example to illustrate hoisting in action
   even though the variable has been declared at a global
   level within the function 
 */


var scope = "global";
function hoist(){
    console.log(scope);     // Returns undefined
    var scope = "local";
    console.log(scope);     // Returns local
}

hoist();




Latest posts by Gary Woodfine (see all)