The state of the web has evolved to the point that javascript is an essential developer skill.
- Browser Console
- JSONLint
###Variables
- Store a value
- Datatypes -
- String
- Number
- Boolean
- Object
- Array
- Null
- Undefined
- Undefined is when a variable is declared but isn't assigned an initial value. Therefore the javascript engine does not know it's datatype.
- Objects passed by reference, primitive types passed by value
- Not type safe
example:
function changeVariableTypeExample() {
var myVar = 'test value';
alert(myVar);
myVar = 5;
alert(myVar);
}
- Functions are objects in javascript
- Assignable
- Passable
- Naming collisions. All javascript code loaded into memory is put into the Global Namespace. All the variables, functions, etc in all libraries.
- Last item defined with a certain name, wins. Overwrites or replaces the previous item with the same name.
PROTIP: Use custom namespace containers.
- Create 1 top level namespace than a series of sub namespaces below that. This way you've only added one thing to the global namespace. Significantly reducing likelihood of naming collisions.
example:
/* if namespace exists, reuse, else create a new */
var ViewBlogAPI = window.ViewBlogAPI || {};
- Used to simulate classes
- Public and private variables
- Closures
- Immediately invoked function expressions
example:
var ViewBlogAPI = ViewBlogAPI || {};
ViewBlogAPI.MyClass = function (initValue) {
var var1 = initValue,
var2 = 'this is var 2',
var3 = 'this is var 3',
var4 = new Date();
var publicMembers = {
get_var1: function () { return var1; },
set_var1: function (value) { var1 = value; }
};
return publicMembers;
};
(function instantiateInstance() {
ViewBlogAPI.instance = new ViewBlogAPI.MyClass('initial value');
})();
alert(ViewBlogAPI.instance.get_var1());
Steps:
- Create namespace
- Define class inside namespace. Set private variables. Private variable are only available within the class. Not accessible outside the class.
- Create an object literal. This will contain members of the class that will be made public. Anything you want made available on public instances of this class goes in the object literal.
- Make items public by making the object literal that owns them the return value for the class function.
- An immediately invoked function expression is used to create class instance.
- Reference it directly however you need to by using the public members it makes available to you.
Closure: By returning functions that reference the private internal variables of the class (which is really just an outer function) we've created a closure. The variables of the outer function (var1,2,3,4) remain available as long as the instance of the class and therefore its public members which closed over those inner variables remain in scope. See Step 4.
Immediately invoked function expression: Wrap in parens. This tells the javascript engine it's an expression not a statement. Typically anything beginning with keyword function is a statement. The parens force it to be treated as an expression so that it can be invoked. The to force invocation, add standard open/clases parens (); after the function expression. When the page (or library) that contains this code loads, we'll now have an instance of our class in the ClientX.instance variable. See Step 5.
PROTIP: To avoid cluttering up global namespace, the expression is included inside top level namespace.
- Facilitate clean code when doing async programming.
- Allows for control over callbacks (e.g. sequencing/grouping of calls).
- Introducing jQuery Deferred
- Then and When examples. 2 simple examples Ability to make async call and make 1 of 2 passes (success or failure) and the another call regardless of pass or fail.
example jQueryDeferred():
function doFoo(bar) {
var dfd = $.Deferred();
context.executeQueryAsync(
//success
function() {
dfd.resolve();
},
//failure
function(){
dfd.reject();
}
);
return dfd.promise();
}
example Then():
doFoo('a')
// must return a promise. not a blocking operation.
.then(
//success
function () {
doFooElse();
},
//error
function() {
logError();
})
.always(
function() {
thisAlwaysGetsCalled();
}
);
)
example When():
$.when()
doFoo('a'),
doFoo('b'),
doFoo('c')
// must return a promise not a blocking operation.
).then(
//success
function () {
doFooElse();
},
//error
function() {
logError();
})
.always(
function() {
thisAlwaysGetsCalled();
}
);
)
- Wrap data for transport.
- nName-value pairs, separated by commas, wrapped in curly braces.
- Describe properties.
- Methods can be made available on the object.
example:
var person = {
FirstName: 'Justin',
LastName: 'Gill',
Address: {
Street: '134 West Elm St',
City: 'New Haven',
State: 'CT',
ZIP: '06515'
},
sayHello: function() {
alert('Hello ' + this.FirstName);
}
};
person.sayHello();
- Subset of object literal.
- More restrictive.
- Property keys are designed.
- Keys must be strings.
- Not common for json to contain methods
example:
var jsonPerson = {
'FirstName': 'Justin',
'LastName': 'Gill',
'Address': {
'Street': '134 West Elm St',
'City': 'New Haven',
'State': 'CT',
'ZIP': '06515'
}
};
alert('Hello ' + jsonPerson.FirstName);
- Function scoped language - variables defined in function supercedes globally defined variables.
- Variable declarations are moved to top of functio by javascript engines.
- Interpreted language. Not compiled. Code is read and executed when it's needed.
PROTIP: declare and assign variables at top of functions
- Equality/Inequality WITH type coercion: ==/!=
- Equality/Inequality WITHOUT type coercion: ===/!==
example 1: Variable x is defined as a string 1. A double equal will attempt to convert the two values being compared to the same type.
var x = '1';
if (x ==1 ){ // typecast attempted
alert('equal');
}
else {
alert('not equal');
}
example 2: Variable x is defined as a string 1. A triple equal does not attempt type conversion. Just compares.
var x = '1';
if (x ===1 ){ // typecast not attempted
alert('equal');
}
else {
alert('not equal');
}
-
must declare variables
var x = 'hello';
not x='hello'
-
eval() is restricted
-
with statement blocked