JavaScript Fundamentals

Naming

All JavaScript variables, keywords, functions, labels, and objects must be identified with unique names called identifiers. Identifiers can be short names (like x and y) or more descriptive (like age, average_height, total_volume).

The general rules for constructing unique identifiers are:

  • Identifiers can contain letters, digits, underscores, and dollar signs.
  • Identifiers must begin with a letter, $, or _. Numbers are not allowed as the first character.
  • Identifiers are case sensitive (y and Y are different names).
  • Reserved JavaScript keywords cannot be used as names. Current keywords include:
    break, case, catch, class, const, continue, debugger, default, delete, do, else, export, extends, finally, for, function, if, import, in, instanceof, new, return, super, switch, this, throw, try, typeof, var, void, while, with, yield
    See a complete list of current and future keywords at developer.mozilla.org.

It is best practice to name things with human-friendly, meaningful names. JavaScript does not specifically enforce any naming convention although traditionally Lower Camel Case seems to be popular. I prefer Snake Case myself.

You can use most of ISO 8859-1 or Unicode letters such as å and ü in identifiers (for more details see this blog post). You can also use the Unicode escape sequences as characters in identifiers.

Data Types

JavaScript uses seven data types, six primitives and the object type.

Type Name Info
Boolean Boolean represents a logical entity and can have two values: true, and false.
Null The Null type has exactly one value: null.
Undefined A variable that has not been assigned a value has the value undefined.
Number Numbers can be defined with or without decimals or as the symbolic values +Infinity, -Infinity, and NaN (not-a-number).
String Strings can be written with double or single quotes.
Symbol new in ECMAScript 6.
Object

Boolean

Null

Undefined

Number

The value of a number data type can be a double-precision 64-bit binary format IEEE 754 number or the symbolic values: +Infinity, -Infinity, and NaN (not-a-number). Integers can also be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8) and binary (base 2). A leading 0 (zero) on an integer literal, or a leading 0o (or 0O) indicates it is in octal. Octal integers can include only the digits 0-7.

0, 117 and -345 (decimal, base 10)
015, 0001 and -0o77 (octal, base 8)
0x1123, 0x00111 and -0xF1A7 (hexadecimal, "hex" or base 16)
0b11, 0b0011 and -0b11 (binary, base 2)

String

Symbol

Object

Variables

Variables are containers for storing data types.

Scope

In JavaScript variables are one of three types of declarations along with const and the recently added let.

Declaring

Creating a variable in JavaScript is called “declaring” a variable. There are three types of variable declarations In JavaScript. In addition to var there is const and the recently added let.

declare both local and global variables.

You declare a JavaScript variable with the var keyword. You can declare an undefined or empty variable, or you can populate the variable with data as it’s created.

The assignment operator = (the equal sign) is used to assign values to variables.

// Declare an `undefined` variable.
var person_name;

// Declare a `defined` variable.
var person_name = 'Daniel';

// Declare many variables with one `var` statement.
var
    person_name = 'Daniel',
    person_age = 30,
    person_eye_color = 'Blue'
;

It’s a good programming practice to declare all variables at the beginning of a script.

Objects

An object is a collection of one or more properties. Properties are key-value pairs grouped into an object. A property can reference another object, a primitive, or a method. The simplest object in JavaScript is a variable.

// Define a variable object.
var person = "John";

An empty object can be defined now and then properties can be added later. The following uses the object literal syntax, and is more convenient. This syntax is also the core of JSON format and should be preferred at all times.

An empty object can be defined simply with curly braces.

// Define an empty object.
var obj = {};

An object can be created and populated with properties at the same time.

// Define a `person` object with a number of properties.
var person = {
    'first_name': 'John',
    'last_name': 'Doe',
    'age': 50,
    'eye_color': 'blue'
};

An object can also be many dimensions deep.

// Define a `people` object with a number of `person` objects as properties.
var people = {
    '1': {'first_name': 'John', 'last_name': 'Doe', 'age': 50, 'eye_color': 'blue'},
    '2': {'first_name': 'Bob', 'last_name': 'Dobbs', 'age': 29, 'eye_color': 'brown'},
    '3': {'first_name': 'David', 'last_name': 'Dodo', 'age': 37, 'eye_color': 'blue'}
};

// Another example.
var user = {
    'user_name': 'Bob',
    'user_id': '24735',
    'likes': [{
        '0': 'Walking',
        '1': 'Trees'
    }],
    'total_purchases': '6',
    'dislikes': [{
        '0': 'biking'
     }]
};

Assign new properties to an existing object.

// Array notation.
jsonObj["myProperty"] = value;

// Dot notation.
jsonObj.myProperty = value;

Count Object Properties

// Count the number of properties in an object.
$var total_properties = Object.keys( my_obj ).length;

Check for a Property

It’s better to use the Object.hasOwnProperty method as opposed to the in method. in will also return true if the key gets found somewhere in the prototype chain, whereas Object.hasOwnProperty will only return true if key is available on that object directly (its “owns” the property).

if (jsonObj.hasOwnProperty('prop_name')) {
    console.log(prop_name + ' exists!');
}

Iterate Over Properties

// Iterate using jQuery.
$.each (obj, function(i, property) {

    // Log the whole property.
    console.log( property );

    // Log a sub-property of the property.
    console.log( property.sub_property );
});

// Iterate using native javascript.
for(i in jsonObj){
    var key = i;
    var val = jsonObj[i];
    for(j in val){
        var sub_key = j;
        var sub_val = val.j;
        console.log(sub_key);
    }
}

Wait for Object to Load

Check if an object has been defined and if not, check again in a quarter of a second.

function check_for_my_obj()
{
    if (typeof my_obj == 'undefined') {
        setTimeout(check_for_my_obj, 250);
    } else {
        // Do something...
    }
}