The new keyword

So far, we've been building objects from scratch using the "object literal" (shortcut) syntax.

Javascript provides another way of building objects using the new keyword. It looks something like this:

var brandon = new Object();

// The new object works just as if we had
// defined it using "var brandon = {};"

brandon.firstName = 'Brandon';
brandon.lastName = 'Carpenter';

log(brandon.firstName + ' ' + brandon.lastName);

Built-in Object Types

This may not seem very handy at first, but Javascript also provides us with a way of creating "pre-built" objects using the new keyword. Here are the basic ones:

  • Object - new Object() is just like {}.
  • Array - new Array() is just like [].
  • String - Stores a string value and provides some methods for working with it.
  • Number - Stores a number value and provides some methods for working with it.
  • Boolean - Stores a boolean value and doesn't really do much else.
  • Function - Surprise! In Javascript functions are actually objects as well.

There's also some useful built-in object types that we haven't seen yet:

  • Date - Stores a date/time value and provides some methods for working with it.
  • RegExp - A regular expression. We probably won't get to these in this class, but they're used to find/replace text in strings.

Array

Exactly the same as creating an array using the "array literal" syntax.

var chores = new Array(
  'take out the trash.', 
  'wash the dishes'
);

/*
Equivalent to:
var chores = [
  'take out the trash.', 
  'wash the dishes'
];
*/

for (var i=0; i < chores.length; i++) {
  log('Brandon needs to ' + chores[i]);
}

Methods available to Array objects

String

String objects are not the same as string primitives!

The nice thing about string objects is that they have methods to interact with the string.

var myName = new String('Brandon');
log( myName.toUpperCase() );

Methods available to String objects

Number

Number objects are not the same as number primitives!

The same thing applies for numbers.

var cost = new Number(16.534439432);
log( cost.toFixed(2) );

Methods available to Number objects

Boolean

Boolean objects are not the same as boolean primitives!

The Boolean object is an object that contains a boolean value as one of it's properties.

It is important to note that (since objects are always truthy) any boolean object that you create will evaluate as true in an if statement.

var isThisTrue = new Boolean(false);

log( typeof isThisTrue );
if ( isThisTrue ) {
  log('true');
} else {
  log('false');
}

log('------------');

// You can retrieve the value stored in the
// object by calling the `valueOf()` method
log( isThisTrue.valueOf() );

Boolean objects are pretty much useless.

More Shortcuts

JavaScript provides a shortcut for calling methods of these primitive container objects.

If you try to call a method on a primitive, it will automatically convert that primitive to an object behind the scenes so it can call that method.

var myName = new String('Brandon');
log( myName.toUpperCase() );
log( "Brandon".toUpperCase() );

.

var pi = 3.14159;
log( pi.toFixed(2) );

Function

Functions in Javascript are actually objects as well, so you can create one using the new keyword.

However, I don't want you to ever do this, so I'm not even going to show how here.

Date

Dates are super-useful object types in Javascript. You can construct a Date works in one of four ways.

Specifying numbers for year, month, and date (and optionally include hour, minute, and second as well).

var date1 = new Date( 2012, 05, 23, 15, 35, 29 ); 
log( "Date 1: " + date1 );

Specifying a date string

var date2 = new Date( "05/23/2012 15:35:29" ); 
log( "Date 2: " + date2 );

Date

Specifying the number of milliseconds since Jan 1, 1970

var date3 = new Date( 1337801729000 ); 
log( "Date 3: " + date3 );

The current date

// No arguments
var now = new Date();
log( "Now: " + now );

Date Methods

var now = new Date();

log( now.toDateString() );
log( now.toTimeString() )
log( now.toUTCString() );

log('---------------');

now.setYear( 2011 );
log( now.toDateString() );
log( now.getDate() );

Properties and methods available to Date objects

RegExp

Regular expressions are a way of matching patterns in strings. They're useful in combination with the replace() and search() methods of String objects.

var pattern = new RegExp('[Hh]ello');
var s = 'Hello, world!';
var edited = s.replace(pattern, 'Goodbye');

log(edited);

We don't have time to really go into this, but after you've been programming a while I highly recommend learning how to use them.

Regular Expression Reference

Scope

Scope is whether or not a particular line of code can access a particular variable.

Global Scope

  • When a variable is declared outside of a function in the top level (more on this later) it is said to be a global variable
  • Variables that are not declared before they are assigned a value are automatically global variables.

.

iAmGlobal = 5;

.

log(iAmGlobal);

Block Scope

  • Some programming languages also have "block scope", meaning that any time you have a "block" of code (surrounded by {}), the variables you declare inside of that block can only be accessed inside of that block.
  • Javascript doesn't have this.

File Scope

  • In addition, some programming languages have a scope of variables for each file (if your program is split among multiple files).
  • Javascript doesn't have this either.

Function scope

  • Javascript has this!
  • Variables declared inside of a function can only be accessed inside of that function.

For example:

var hello = function() {
    var greeting = "hello";
    log(greeting);
};

hello();
log(typeof greeting);

Variable Shadowing

When a variable is declared in a child scope that is already available in a parent scope it is said to "shadow" or "mask" the other variable.

var greeting = 'goodbye';

var hello = function() {
  var greeting = 'hello';
  log(greeting);
};

hello();
log(greeting);

Lexical Scoping

  • JavaScript's approach to variable scope is called lexical scoping
  • Essentially this means that variables defined in a parent scope are available in the child scope too
  • THIS IS WHY THE VAR KEYWORD IS IMPORTANT

.

var greeting = 'goodbye';

var hello = function() {
  greeting = 'hello';
  log(greeting);
};

hello();

// The above function call modified the 
// global greeting variable!
log(greeting);

Advanced Topics: Creating Scope

One trick that advanced Javascript programmers often use is to create a new variable scope using an anonymous function that is executed immediately.

(function() {

  // Protect "myvalue" so no one else can edit it!
  var myvalue = 100;
  log(myvalue);

}());

The above is equivalent to:

var newscope = function() {

  // Protect "myvalue" so no one else can edit it!
  var myvalue = 100;
  log(myvalue);

};

newscope();

Scope: More Resources

For more scope examples in Javascript check out: this post on Stack Overflow.