Introduction to JavaScript with SharePoint 2013

Setting the stage with basics

by David Mann on 4/16/2014

Share this:

Article Details

Date Revised:

This brief overview will help you come up to speed with JavaScript, but it is nota detailed review of the language. It will help you shake out the cobwebs if you’re a little rusty with JavaScript and prepare you for the material in subsequent articles.


With the release of SharePoint 2013, Microsoft has promoted JavaScript to a first-class language that all SharePoint developers must be comfortable with.  Prior to 2013, many SharePoint developers were able to successfully bypass or avoid JavaScript development.  This is no longer the case. Not only has the app model changed the development landscape, but additional capabilities across the product make JavaScript an even more important skill for SharePoint developers to possess. Even if you’re not creating apps, user expectations and the state of the web have evolved to the point that JavaScript is an essential developer skill.

This is the first part in a series on developing SharePoint 2013 solutions with JavaScript. As you would expect, the series will cover a lot of JavaScript. However, it won't spend a lot of time on JavaScript basics. Plenty of tutorials are available on the web that cover basic JavaScript. If you need that introductory level information, take a look at the JavaScript Resources section of my blog. Note that the resources available there include more than just basic information; they also include many intermediate and advanced topics, as well. 

Except for a very brief overview, I assume that you either know some JavaScript already or can pick it up in context as it is used. As long as you’re marginally familiar with both SharePoint and JavaScript, you should be fine with this series.  If you need a little refresher in JavaScript, this first article will help – it covers a few aspects of JavaScript you should be familiar with, as they’ll be used throughout the series. Even if you’re comfortable with JavaScript, I recommend that you at least skim this first article as there are likely going to be a few things covered that you need to brush up on.

The other articles will move pretty quickly into different options for using JavaScript in your SharePoint development, covering things like out-of-the-box capabilities, REST, the JavaScript Object Model, using common third-party libraries, etc.

Series 2 picks up where this series ends and goes into more detail on some advanced topics such as authentication, cross-domain calls, working with the new Minimal Download Strategy (MDS), etc.  The third series finishes things off with very specific scenarios for SharePoint development opportunities – things like the new JSLink capabilities, working with the Ribbon, Apps, Social, Workflow and a lot more – all from a JavaScript perspective. 

JavaScript Basics

Now let's start the overview of basic JavaScript information with the most basic and progress into intermediate, almost-advanced, JavaScript details pretty quickly. The intention is to rapidly cover the basic information required to follow along with the material later in the series. If you aren’t sure of how or why something is working or why we use certain constructs in a later series, chances are it’s covered here.

JavaScript Variables

JavaScript variables are used to store a value, like any other variable you’ve ever used in any other programming language. Unfortunately, in many ways, that’s where the similarities between JavaScript variables and other variables end.

A JavaScript variable can hold only seven possible data types:

  • String
  • Number
  • Boolean
  • Object
  • Array
  • Null
  • Undefined

Most of these are probably pretty familiar if you’ve worked with any other programming language, but a strange one called undefined is at the end of the list. This one is used when you declare a variable but do not assign it an initial value, so the JavaScript engine doesn’t know its data type. Types are determined when you assign a value to a variable, but unlike in other programming languages, those types are not fixed when the variable is declared. You may have heard people complain that JavaScript is not type-safe, and this is what it means. A variable can change its type when it is assigned a value, so the code in Snippet 1 is perfectly legal.

// create a variable and assign it a string value.
var myVar = “a string”;
//The variable now has a data type of String.
// now reassign the variable, this time with a number
myVar = 123;
// now assign the variable the value returned from a function, which 
// here happens to be an object
myVar = getSomeObject();

Snippet 1: JavaScript is not type-safe. Reassigning variables to different data types is legal

If you’ve been around a while doing development, this is like the old Variant data type, otherwise known as the scourge of VB3. It is arguably one of the most dangerous aspects of JavaScript for many modern programmers, and it’s one of the drivers behind Microsoft’s recently announced language Typescript, which, among other things, aims to provide type safety to JavaScript. We’ll cover TypeScript in the third article in this series.


JavaScript functions form the core of the language. They are similar to functions or methods in other programming languages. Most of what you do in JavaScript is write functions, so if you’re not already familiar with them, you will be very soon.  In a nutshell, functions are named blocks of code that provide a unit of your required functionality. While it is technically possible to write JavaScript and not write functions, doing so is almost always a bad idea – and by almost always I mean that there are so few situations in which you don’t write functions that it is almost negligible. Functions are just what we do in our JavaScript. Snippet 2 shows a very basic sample function – our requisite Hello World example.

    function sampleFunction(){
	var myVar = “Hello World!”;

Snippet 2: Functions are a basic unit of functionality in JavaScript

This series will obviously cover many, many functions. There is rarely a reason to have your JavaScript code outside of a function.

Global Namespace

If you read about JavaScript, you’ll see a lot of discussions on not polluting the Global Namespace. In JavaScript, by default, all of the code loaded into memory is tossed into a single big bucket called the global namespace. Every variable, every function loaded from any library referenced by the page or any code added directly to the page, defaults to going into the global namespace. If you load a lot of JavaScript code, you run the risk of having conflicts between all of these names. So, imagine that the box in Figure 1 is our Global namespace.


Figure 1: A representation of the Global Namespace

As we go about adding variables and functions it begins filling up. Before long, it’s pretty full, as you can see Figure 1. Now we start having a hard time keeping track of everything, so we run the risk of naming conflicts – two objects in the global namespace with the same name.   

If you think this is unlikely, I can give you a really easy example of it happening right inside our little SharePoint world. SharePoint 2010 saw the explosion of the use of JavaScript, specifically JQuery. The JQuery object is often represented by the “$” variable. Unfortunately, certain JavaScript libraries in SharePoint also made use of the $ variable name, which would then conflict with JQuery. This led to the recommendation to point JQuery at another alias by using JQuery’s “noConflict” mode. Just the simple fact that JQuery has a “no conflict” mode points to the problem of naming conflicts.

One more example to help stress the importance of this. A default SharePoint 2013 Team Site homepage, with no customizations whatsoever has around 3000 items in the global namespace. Some of them have obscure or specific names so a conflict is unlikely. But some of them have names like RefreshPage, ToggleAllItems, and CancelEvent which are much more likely to cause conflicts. (And, by the way, if you look closely at Figure 1, you’ll notice that there are three instances of a variable named CompanyName so they would conflict with each other. See how easy it is to miss this problem? Debugging this could be exceedingly difficult.)

When a conflict occurs, JavaScript handles it in a very specific, very predictable, but perhaps unfortunate manner – the last item defined with a certain name wins. It overwrites or replaces the previous item with the same name which is going to often cause intermittent and unpredictable errors that can be very difficult to track down.

The solution to this problem is to create custom namespaces that are uniquely named. These namespaces then act as contains for your other names.  he only “names” now in the global namespace are your custom namespace containers. Technically, if you’re really taking namespacing to heart, you should create only one top-level namespace and then a series of sub-namespaces below that. That way you’ve only added one thing to the global namespace. You’ve just significantly reduced the likelihood of naming collisions; not entirely eliminated them, but if you choose your top-level namespace name carefully, certainly reduced as much as possible, and likely this will be enough.

JavaScript doesn’t intrinsically have the concept of namespaces, but we can simulate them with objects, so that’s what we do. In Snippet 3, we see three namespaces, all beginning with the name of our client – the mysterious ClientX. We have the top-level namespace, ClientX as the only new name we’ve added to the global namespace. This should eliminate collisions with third party libraries or any other JavaScript added to our site, including out-of-the-box JavaScript included with SharePoint. All we have to worry about now is collisions within our custom code – hence the second level namespaces ShoppingCart and Users.

Both ClientX.ShoppingCart and ClientX.Users have a variable named CompanyName but there is no conflict because they are in different namespaces – they have different fully qualified names.

//Declare our namespaces:
var ClientX = ClientX || {};
ClientX.ShoppingCart = ClientX.Shoppingcart || {};
ClientX.Users = ClientX.Users || {};
//Now use them:
ClientX.ShoppingCart.CompanyName = “Contoso”;
ClientX.Users.CompanyName = “Aptillon”;

Snippet 3: Declaring and using namespaces to avoid naming conflicts

Fortunately, setting up namespaces is easy. Snippet 3 shows an example of setting up a simple namespace hierarchy. We declare our top-level namespace variable called ClientX: var ClientX = ClientX || {}. The code here assigns to the variable ClientX the value of an existing variable named ClientX if it exists, or else creates a new empty object (using the shorthand {} notation). Again, JavaScript doesn’t really have true namespaces, so we simulate them with objects and get the same effect. We declare sub-namespaces as objects on our parent namespace following the same reuse-or-create-new-object approach, as you can see in Snippet 3 for both the ShoppingCart and Users sub-namespaces.

We now have three separate naming containers with which to work. Variables or functions declared as properties inside any of these objects, as Snippet 3 does for CustomerName, will not conflict with each other.

We’ll see significant additional use of namespaces as we go through the rest of the chapters in this book and the rest of the books in the series as well. At this point, though, you should have a basic understanding of why we go through all the hassle of doing so and have at least seen an example of how it works.

Module Pattern

 JavaScript development has a number of common patterns. My favorite is definitely the Module pattern because it gives me the ability to simulate classes with both public and private members. The module pattern often makes use of two other constructs in JavaScript that you’ll need to have an understanding of: Closures and Immediately Invoked Function Expressions.


In a nutshell, closures are a wrapper around the execution context in which a function was created. This execution context includes all of the variables local to that function, as well as any other functions nested inside the initial function. For whatever amount of time any of the inner functions are in scope, the execution context is available, even if the outer function that spawned the execution context itself has passed out of scope. This means that any variables or functions declared inside the outer function are available. This can be fairly confusing until you see it in action a few times, so we’ll get to that in just a moment.

Immediately Invoked Function Expressions

An Immediately Invoked Function Expression (IIFE - pronounced iffy), or self-executing function, is a function that is declared and then immediately executed. They are a shorthand way of declaring and then executing a function that can help ensure that the two operations aren’t unintentionally divorced.

In Snippet 4, I start by setting up my ClientX namespace as we saw earlier. Then I set up my class definition inside that namespace. The class definition contains four variables that will remain private – they will not be directly accessible outside the class. Inside the class, they’re fully available – just like regular private variables in other languages. 

//set up the top-level namespace:
var ClientX = ClientX || {}; 
//define the class:
ClientX.MyClass = function (initValue) {     
  var var1 = initValue;     
  var var2 = "this is var 2";     
  var var3 = "this is var3";     
  var var4 = new Date();     
  var publicMembers = {         
    get_var1: function () { return var1; },         
    set_var1: function (value) { var1 = value; }     
  return publicMembers; 
//create an instance of the class:
(function instantiateInstance() {     
  ClientX.instance = new ClientX.MyClass("initial value"); 
//use the new class instance:

Snippet 4: Closures and IIFEs can help us to simulate classes in JavaScript

Next I set up an object literal (we’ll cover these in detail on the next section; for now just think of it as a description of an object.) This particular object literal contains the members of my class that are going to be public. For clarity, I often name the variable that owns the objects I’m exposing outside of my simulated class publicMembers, as shown here, or perhaps just publics. I find it helpful to have just that little bit of explicitness when I’m looking at my code later. In Snippet 4, I have two functions that allow me to read and write one of the private variables, essentially a property getter and setter. I am not limited to just functions that read and write other variables; I could also include other functions and other variables – anything I want to be available on instances of this class.

I make them public by making the object literal the return value from the function that defines my class. By returning functions that reference the private internal variables of my class (which is really just an outer function), I’ve created a closure. The inner private variables remain available as long as the instance of my class, and therefore its public members that close-over the inner variables, remains in scope.

Next I have my somewhat forced IIFE. I say forced because it isn’t really necessary in such a simplistic example. We’ll see more natural IIFEs in later articles. In this example, I’m simply using it create my class instance. To avoid cluttering up the global namespace, I include the variable that holds my class instance inside my top-level namespace. 

Actually creating the iffy is easy. First you need to wrap your function statement inside parentheses. You’ll notice in Snippet 4 the opening parenthesis before function. The closing parenthesis comes on the last line of the IIFE – right after the closing curly brace. This tells the JavaScript engine that this is an expression, not a statement. Typically anything beginning with the keyword function is a statement, so we want to force it to be treated as an expression so that it can be invoked. We then force that invocation immediately by adding the standard open/close parenthesis pair after the function expression. When the page or library that contains this code loads, we will now have an instance of our MyClass class held inside the ClientX.instance variable, and we can reference it directly in any way we need to, using the public members it makes available to us. If we needed to pass a value into our IIFE, we could do that as shown in Snippet 5.

(function instantiateInstance(initValue) {     
  ClientX.instance = new ClientX.MyClass(initValue); 
})(“value passed in to IIFE”);

Snippet 5: Passing a value into the IIFE

We’ll see pretty significant use of this pattern throughout this series. There will be a few other patterns used as well, but this one is extremely common.

JavaScript and Data

One of the biggest changes in modern JavaScript programming is that m JavaScript used to be a tool used primarily for making appealing user interfaces. Now it's a tool for interacting directly and significantly with data. In order to understand how JavaScript interacts with data, we need to discuss a couple of elements. We’ll start with JavaScript object literals, which we saw an example of in Snippet 4.

Object Literals

JavaScript object literals are simply a means of describing an object in a succinct manner. The object literal syntax is more concise than XML and is often used for passing data from one function in your application to another, or to some external service or entity.

var person = {                
    FName : "David",                
    LName : "Mann",                
    IsAuthor : true,                
    Address: {                    
        Street : "123 Main Street",                    
        City :   "Anytown",                    
        State :  "Pennsylvania",                    
        Zip :    "12345"                
    sayHello : function(){                    
        alert("Hello " + this.FName);                

Snippet 6: Object Literals describe an object or a piece of data

Object literals are simply name-value pairs describing an object. Within an object literal, the name value pairs are separated by commas, and the whole object literal is wrapped in curly braces, as shown in Snippet 6. The code shown in this snippet creates an object using the object literal syntax. It describes a person object with five properties. First, three simple properties store the person’s first name, last name, and whether they are an author. Then a property stores the person’s address – Street, City, State, ZIP, with the key portion being the same as we saw for FName and LName, just a simple text label. The value portion of the Address property, however, is a nested object literal; it is another set of key-value pairs wrapped in curly braces.

This object literal shown in Snippet 6 also includes a method, sayHello, which is really just another property that has a function as its value. This is an important aspect of JavaScript object literals - object literals can describe more than just properties; they can also describe methods available on the object as JavaScript functions.


Another important element to understand is JSON or JavaScript Object Notation. It is a subset of the whole JavaScript object literal syntax we just looked at. It is more restrictive than the full object literal and is also, in practice, used differently. The primary additional restriction of JSON that you need to be aware of is the way that property keys are designated. In object literals, property names do not have to be delimited, and do not actually even need to be strings. The numeral 5 would be a perfectly valid property identifier in the object literal syntax. JSON doesn’t allow this. In JSON, property identifiers must be valid strings, and must be wrapped in single or double quotes, as shown in Snippet 7.

var jsonPerson = {                
    "FName" : "David",                
    "LName" : "Mann",                
    "IsAuthor" : true,                
    "Address": {                    
        "Street" : "123 Main Street",                    
        "City" : "Anytown",                    
        "State" : "Pennsylvania",                    
        "Zip" : "12345"                

Snippet 7: JSON is a more restrictive subset of the object literal syntax

Compare Snippet 7 to Snippet 6 to see this difference between them.

Another key difference to be aware of is that, in practice, JSON is typically used to pass data around, and therefore it is less common to see JSON objects containing methods. Having methods is not disallowed by the JSON spec; it is just not how JSON is most often used. JSON objects are typically just used to describe the properties of an object, not its functionality. JSON objects are, in practice, a means of passing data around to different parts of your application.


Promises are a pretty advanced topic in JavaScript but aren’t really that difficult and are huge when you’re doing asynchronous programming--like almost everything we do in SharePoint JavaScript. They allow for a much higher degree of control over asynchronous calls and related interactions. In the snippets here and in the sample code, I leverage the JQuery Deferred object to facilitate my promises. Other libraries have similar support for promises.

function doSomethingThatReturnsAPromise(input) {
    var dfd = $.Deferred();
    // do stuff then make an asynchronous call:
    return dfd.promise();

Snippet 8: A simple shell of a function that works with promises

Snippet 8 shows our first look at a Promise, which we can use to get a better understanding of what they’re all about. Line 2 sets the variable dfd to a JQuery Deferred object. On line 3 we would run some code to prepare for the asynchronous call we make on line 4. The asynchronous call in line 4, in this case using the SharePoint Client-Side Object Model (CSOM), is not a blocking operation – it makes a call up to the SharePoint server but it does not wait for the server to respond, as you would expect for an asynchronous call. Instead, it registers two callbacks – one if the call to the server succeeds (the anonymous function beginning on line 6), and one if it fails (the anonymous function beginning on line 10). The main function continues immediately after the asynchronous call with the code on line 14, which simply returns the promise to its caller.

The asynchronous call made to the server on line 4 will eventually return and go into either the success callback or the failure callback. In the former case, the code on line 7 will resolve our promise – essentially signaling to the caller that the call completed successfully. In the latter case (failure), the code on line 11 will signal to the caller that the asynchronous call completed, but an error has occurred. It is up to the caller to respond to either the resolving or rejection of the Promise however it sees fit.

    //Success callback
    function () {     
    //Failure callback
    function() {
    function() {

Snippet 9: Acting on our returned Promise

Snippet 9 shows one possible caller of our promise. You’ll notice that line 1 makes a call to our doSomethingThatReturnsAPromise function from Snippet 8 and passes in a value of “a” for the input parameter. Line 2 simply indicates what we want to have happen when the returned Promise is finished – either successfully or with an error via the then method of the Promise object. You’ll notice that this function also includes both a success and a failure callback. If the Promise is resolved when the asynchronous call returns (as it is on line 7 of Snippet 8), the success callback will be triggered; and the failure callback if the Promise is rejected (line 11 of Snippet 8). This allows the caller to respond to whatever outcome occurs from the asynchronous call. 

Regardless of whether the Promise is resolved or rejected, the code in the always method on line 11 of Snippet 9 will, as you would expect from the name, always be called.

The next example, shown in Snippet 10, is similar except that it takes a collection of functions that each return a Promise and wraps them in a single Promise that gets triggered only after ALL of the individual Promises are triggered. This sounds more complicated than it really is, so don’t worry if your head just started hurting. 

In this example, we make three separate calls into the doSomethingThatReturnsAPromise function from Snippet 9, each passing in a different parameter. Only when all three calls have had their promises triggered will the when function complete and execution continue with the then and always. Again, this is non-blocking and supports both success and fail triggering. The nature of asynchronous calls is such that even though these calls are made in a defined order, there is no guarantee that they will complete and return in any given order. Using the Promise helps to ensure that we only continue when all calls are finished, regardless of the order in which they finish.

   //each must return a Promise 
   doSomethingThatReturnsAPromise (“a”),
   doSomethingThatReturnsAPromise (“b”),
   //same as Snippet 9
   //same as Snippet 9

Snippet 10: Queuing up individual calls and only continuing when ALL are complete

These are just two examples of Promises. Promises also support additional capabilities such as progress, done and fail. We’ll see additional examples of Promises throughout the series, including significant use in some elements of the REST and JavaScript Object Model articles. For now, I just wanted to introduce them and lay a foundation upon which to build. There is a LOT more to Promises. If you want to learn more about Promises you can start with the resources on the JavaScript Resources page.

JavaScript Odds and Ends

There are just three more code things to cover before we move on to a quick discussion of important JavaScript tools. These are really just concepts that are important to know that don’t really fit in anywhere else.


The first is the concept of hoisting.  his is an important concept because it can often lead to unpredictable and unexpected results. JavaScript is an interpreted language, not a compiled one. The code is read and executed when needed. This doesn’t mean, however, that the JavaScript code you write is processed exactly as you type it in. It is actually parsed and interpreted before being executed, and this changes things. Hoisting is the common term applied to one side effect of the way JavaScript is parsed. In a nutshell, it means that JavaScript variable declarations and value assignments can be split and moved around inside of your function.

var myVar = "this is a global variable"; 
function hoistingSample() {             
    var myVar = "this is a local variable";             

Snippet 11: How you type your code isn't always how it is executed

For example, you might type a function that looks something like Snippet 11. It would be reasonable to expect this code to pop up two message boxes – the first saying this is a global variable and the second saying this is a local variable.” As the code is typed, it looks like the second declaration of myVar, the local declaration inside the function on line 5, happens after the first use in the alert on line 4. So thinking that myVar carries its global value from line 1 until it is redeclared on line 5 makes a certain amount of sense. But that is not what happens.  Instead, what happens is that the first pop up says undefined and the second says this is a local variable.

var myVar = "this is a global variable";
function hoistingSampleAsInterpreted() {             
    var myVar;          //myVar declaration is moved to top.  
    alert(myVar);       //value is undefined             
    myVar = "this is a local variable"; 
    //Local myVar now has a value  

Snippet 12: This is how Snippet 11 is actually interpreted by the browser

Snippet 12 shows how the code in Snippet 11 is actually interpreted and then executed by the browser. This actually demonstrates two important and related aspects of JavaScript. The first is variable scoping and the second is the hoisting mentioned above. JavaScript is a function-scoped language, meaning that, in Snippet 11, the variable myVar defined inside the function (line 5) supersedes the global variable with the same name – it essentially replaces it while the function is in scope (once scope leaves the function, the outer variable maintains its original value.) You would think, though, that the replacement wouldn’t actually happen until the function-scoped variable is declared on line 5. This is not the case, and that is where hoisting comes into play.

Variable hoisting happens inside the JavaScript parsing engines as it interprets the code before it is executed. It separates the variable declaration from the variable assignment. All variable declarations anywhere in the function are lifted, or hoisted, to the top of the function block, and the variable assignments are left wherever they appear in the typed code. That’s why Snippet 12 looks different from Snippet 11 and why we don’t get the results we expect. The declaration of the variable myVar is moved to the top of the function and the assignment of the value is left in place. When you look at the representation of the code in Snippet 12, the result we actually get makes more sense. The first alert box pops up a message that says “undefined” because the variable has been declared but not given a value – it truly is undefined, thanks to variable hoisting.

Because of variable hoisting, it is generally recommended that you declare and assign your variables at the top of your functions, before any other code whenever possible, as shown in Snippet 13.

var myVar = "this is a global variable";
function hoistingSampleAsInterpreted() {             
    var myVar = "this is a local variable";

Snippet 13: A better approach to declaring function variables

I understand that for any number of reasons this is not always possible, but it is something to strive for nonetheless. In the rewritten example in Snippet 13, my variable declaration and assignment are moved to the top of the function. The alert box will now show the correct initial value for the variable:


Figure 2: The expected initial alert box from our example


The last aspect of JavaScript code that you need to understand is simply the way JavaScript does comparisons. At the very beginning of this module, we talked about JavaScript not being a strongly typed language. This type-flexibility comes into play when doing simple equality comparisons. 

var x = "1";                          
if (x == 1) {  
    //attempt to typecast succeeds, so equal                 
else {                 
    alert("not equal");             

Snippet 14: Type coercion in a "normal" comparison can yield unexpected results

Snippet 14 shows code that checks to see if our variable x is equal to the numeral 1. X has been assigned a value of the string representation of the number 1 so in looking at this code we would expect this comparison to return false and so show us the “not equal” message because a string is not equal to a number. This is not the case. In this example, doing a comparison with the double equal sign on line 2 attempts to convert the two values being compared to the same type. If it succeeds, it then does a comparison. In our example, the numeral representation of the number 1 can be converted into the string 1, and so the comparison is actually between two instances of the string 1, which are of course equal and so the end result is the pop up “equal”. This is probably not what we wanted.

var x = "1";                          
if (x === 1) {  
    //no type coercion, so not equal                 
else {                 
    alert("not equal");             

Snippet 15: The proper way to do equality comparisons, without type coercion

Instead, what the developer most likely intended was a comparison of the two values without any type coercion occurring. To achieve this in JavaScript, you need to use the triple equal sign, as shown on line 2 of Snippet 15. This says don’t try to convert types, just compare them as-is. If they’re not the same type, they are by definition, not equal. The string 1 is not equal to the number 1, so we get the expected “not equal” pop-up. 

A side effect of doing a non-coercive comparison with the triple equal sign is that your code will actually run marginally faster as there is no type conversion occurring, though you won’t notice anything unless you are doing a lot of comparisons.

Both comparison operators have a negative equivalent: exclamation-equals and exclamation-double equals which perform as simply the opposite of their equivalent comparison operator – a not-equals comparison, again either with (!=) or without (!==)  type coercion.

Strict Mode

As I’ve mentioned and you’ve seen in this module, JavaScript is very forgiving. You would think that’s a good thing but it’s really not. If you’re writing code, even JavaScript code, it means that you have a very specific set of steps that you want the user or process to go through to achieve whatever end you had in mind. If you’re doing JavaScript and NOT using strict mode, it’s harder to guarantee that things will end up where you want them to end up.  Strict mode enforces a better flavor of JavaScript. If you’ve been around awhile, this is the “Option Explicit” mode from classic VB.

"use strict";
function myFunction(){
  // strict mode enforced in here!

Snippet 16: Declaring strict mode for a whole library

Setting up strict mode is easy – just add the literal string “use strict” to your code. That’s all it takes. The string will be simply ignored by browsers that may not support strict mode so there is zero downside. It can be added at either the Library level, as shown in Snippet 16 or at the level of an individual function, as shown in Snippet 17.

function myStrictFunction(){
  "use strict";
  // strict mode enforced inside the function
// strict mode NOT enforced outside the function

Snippet 17: When declared inside a function, strict mode applies only to the code in the function

Things restricted by strict mode include the following:

  • You must declare variables by specifying the var keyword. This in itself is reason enough to use strict mode – it prevents a lot of dumb mistakes. See Snippet 18.
    var x = "1";     //strict mode
    y = "2";         // not strict mode – var is missing

    Snippet 18: Variable declarations with and without Strict mode

  • The use of the eval function is severely restricted. Many JavaScript developers view eval as pure evil anyway so this is a welcome change. My opinion is that used appropriately, and in moderation, eval is not a problem. Strict mode doesn’t prevent the use of eval, it just limits the situations in which it can be applied. If you’re not familiar with eval, it allows you to pass in a string of text and have it parsed and executed as JavaScript. It’s handy when you need to dynamically put together your JavaScript code, but like I said – in moderation, please.
  • The use of the with statement or with block is disallowed, as shown in Snippet 19
    with (myObject) { 
    //the above not allowed in strict mode

    Snippet 19: Strict mode prevents code like this from being used

There are a few other things restricted by strict mode as well, but those are the biggies.

I strongly recommend that you use strict mode in all of your JavaScript development. You’ll see that I do inside the full code samples that accompany this book.


That gets us through the main ideas that you need to know about the JavaScript language in order to be able to follow along with the examples later in the series. Becoming a JavaScript expert is obviously going to take you more than just this brief overview, but you should now be able to understand the later material and so get started doing SharePoint JavaScript development. 


The last piece of introductory material to cover is a simple review of the tools you’re going to want to be familiar with if you expect to be a productive JavaScript developer. These are all tools you WILL make use of as you write more and more JavaScript. 

Links to all of the tools mentioned here as well as others are available on JavaScript Resources page for the book (

We’ll start with a few simple Visual Studio plugins. These are all available through the extension manager inside Visual Studio. Note that I’ll be using Visual Studio 2012 throughout this series though all of them are available for Visual Studio 2013 and some are even updated.

Web Essentials

First up is the granddaddy of plug-ins for web developers – Web Essentials 2012. This one is a no-brainer. Just install it. Don’t wait. If you have your development box readily available, stop reading here and go install this one. Seriously.  If you’re not using it, you’re just making your life harder. It adds all kinds of useful tidbits. There is an updated version for VS 2013.

JavaScript Parser

Next in my list is a simple little plug-in that just makes it easier to find your way around large JavaScript files. It’s called simply JavaScript Parser and it presents as a dockable window that shows you a tree-view of the objects, variables and functions inside the active JavaScript file.


The last plugin in my list is a JSLint plugin – JSLint for Visual Studio. If you’re not familiar with JSLint, it is essentially Code Analysis for JavaScript. It was developed by Douglas Crockford and honestly is a little controversial – some people feel it is a little too strict, that the rules it enforces are not realistic for actual production projects. Other people don’t feel that way. I tend to fall more into the former camp – JSLint is a little too stringent for me, so I’m more of a fan of a fork of the JSLint project called, cleverly enough, JSHint. I find this version to be more in line with my coding style and habits. Fortunately, this plugin supports either. I switch it to use the JSHint engine and configure a few options to my liking. One more thing about this plug-in: Web Essentials also supports JSHint but this plug-in does one thing Web Essentials doesn’t that I find very useful – it allows you to ignore JavaScript libraries included in your project from evaluation. This is important because, for example, JQuery fails both JSHint and JSLint analysis miserably.

JSON Viewer

The next tool is one that lets you examine your JSON data. When working with JSON data, it is often helpful to be able to walk through the JSON data. While there are dozens of them out there, the one available from is about the best I’ve come across.  It’s easy and fast and open source so if you want to extend it, you can. 


Fiddler is a web-debugging proxy. It allows you to intercept and analyze web traffic. It also has a nifty composer capability which allows you to craft up your own web request and submit it. Fiddler comes in especially handy when you’re doing REST, so we’ll explore it in detail in that article.

Browser Tools

And of course, you can’t do web development without the developer tools in the various browsers. All zealotry aside, it doesn’t really matter which you use as your main browser; the tools in all of them are good. Some people swear by one, others by another, but when push comes to shove, it is really largely a religious battle so pick whichever one you feel most comfortable with. 

There are, of course, many, many other tools out there and it is an absolute certainty that I’ve missed some here. That’s OK. The tool landscape evolves almost as quickly as the development landscape does and what is today a pretty good list of important tools is tomorrow woefully inadequate. I’ll keep the list of resources up to date as new tools emerge or I stumble across them. If you have a favorite tool or two, I’d love to hear about it.


I've briefly covered just the core elements of JavaScript that you’ll need to be familiar with in order to be able to follow along with the material in later articles. Again, if JavaScript is entirely new to you or this overview raised more questions than it answered, I highly recommend spending some time with the resources before continuing on.

This concludes our quick overview of some of the important elements of JavaScript you must be familiar with as we move into developing for SharePoint 2013 with JavaScript. In the rest of this series, we’ll put this newfound knowledge to work building SharePoint 2013 solutions with JavaScript.


Topic: Article

Sign in with

Or register