Skip to content

Instantly share code, notes, and snippets.

@newhavengill
Last active January 12, 2018 17:12
Show Gist options
  • Save newhavengill/227cf8cc8842a47fbfa26f3addc97c0b to your computer and use it in GitHub Desktop.
Save newhavengill/227cf8cc8842a47fbfa26f3addc97c0b to your computer and use it in GitHub Desktop.

Javascript Basics

The state of the web has evolved to the point that javascript is an essential developer skill.

Javascript Code Constructs:

Javascript and Data:

Misc Javascript:

Javascript Tools:


###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

  • Functions are objects in javascript
  • Assignable
  • Passable

Namespaces

  • 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 || {};

Module Pattern

  • 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:

  1. Create namespace
  2. Define class inside namespace. Set private variables. Private variable are only available within the class. Not accessible outside the class.
  3. 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.
  4. Make items public by making the object literal that owns them the return value for the class function.
  5. An immediately invoked function expression is used to create class instance.
  6. 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.

Promises:

  • 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();
		}
	);
)

Object Literals

  • 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();

JSON

  • 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);

Variable Scoping

  • 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

Comparison

  • 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');
}

Use Strict

  • must declare variables var x = 'hello'; not x='hello'

  • eval() is restricted

  • with statement blocked

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment