if (myVar === undefined) { doSomething(); }
var myVar1; // myVar1 is declared, and has a value of undefined myVar2 + 3; // myVar2 isn't even declared; this will throw an error
$myString = "Hello {$name}, you have an {$animal}." // PHP string sub, not valid in JS
var myVar = 9; myVar = 'someString'; myVar = new Object();
{}
block like Java. JS has no block scope.var
. (Technically, you can assign a variable a value and it will be implictly declared, but these are always declared as globals, so a better idea is just to always declare them yourself with var
). '3' !== 3
.instanceof
and typeof
are also operators in JavaScript. They do similar things:instanceof
is used to figure out whether a given object is a certain type of object, e.g. a instanceof Array
would return true if a is an array. It requires both left and right-side operands.typeof
takes only a single (right-side) operand (e.g. typeof a
), and returns a string with the type of object. Unfortunately, it only returns base types… 'number', 'string', 'boolean', 'object', 'function' or 'undefined'. NOTE: functions are objects in JS, so I'm unclear on why it wants to return a special value for function, but it does.?:
, e.g. (x > 0) ? document.write('x is positive') : document.write('x is negative');
new
and delete
are for creating new objects and deleting them. Since JavaScript doesn't really have classes, you can't create and delete classes, but objects are kinda like classes.if/else
, while
and do…while
, for
loops, etc. It also has a few funny ones:for…in
can be used to iterate over the properties of an object. It is used like this:var myObj = new Object(); myObj.prop1 = 3; myObj.prop2 = 4; for (var index in myObj) { document.write(index+','); }
That will produce the output prop1,prop2,
. Note that it is actually iterating over the property names themselves… if you want to get the value of the property, you need to look it up using the array notation: document.write(myObj[index])
.
throw
and try/catch/finally
. These are the same as in other languages, but it's definitely nice that it has finally
, which is guaranteed to execute after the other statements.myObj.prop1
) or via array notation (myObj[“prop1”]
). for…in
loops, and if you have to access a property with a name that contains otherwise invalid identifier characters. See Using PHP Input Arrays with Javascript for an example. var foo = {};
) or the new
syntax (var foo = new Object();
)String.prototype.trim=function(){ return this.replace(/^\s*|\s*$/g,''); };
myArray.length
gives you the length of your array. Something that's rather cool: you can set the length property if you want, and it will create an array of that size. So if you say myArray.length = 10000;
, you'll have an array of 10,000 elements.join()
, reverse()
, sort()
and several other functions are available as well.length
property) won't work. See Associative Arrays in JavaScriptfunction hypotenuse(a,b) { function square (x) { return x*x} return Math.sqrt(square(a), square(b)) } // square() can't be accessed here, because it was defined in the hypotenuse() // function and thus isn't global in scope
var addNumbers = new Function('x', 'y', 'return x+y'); document.write(addNumbers(4,5)); // returns 9
This is mainly useful in dynamically creating functions (during code execution); otherwise you may as well just use the function
statement.
var addNumbers = function (a, b) { return a + b; } // define a function and assign it to a variable function doMath(mathFunc, a, b) { // create a function that accepts an argument return mathFunc(a,b); } doMath(addNumbers,2,3); // call the function with the argument
document.write ('foobar');
then an anonymous variable is created for the string 'foobar'. You can do the same with functions:
// this defines an anonymous function with a and b as the arguments, and then // executes that function with 3 and 4 as the values document.write(function(a, b) { return a+b; }(3,4));
methods
. Methods have one important core difference that makes them more than just 'functions attached to objects'. You can access the parent object with the this
keyword inside the method that it is called from. For example:var myObject = {}; myObject.a = 5; myObject.b = 7; myObject.goo = function () {return this.a + this.b}; document.write(myObject.goo())
function Circle(r) { this.radius = r; }
By convention, class names always start with a Capital Letter. That's how you tell them apart from normal functions. this refers to the object you're creating, so setting this.radius
means you create and set a public member radius
. It's an instance member (or 'instance property', in JS terms), which means it will be different for every instance of the class that you instantiate.
var Rectangle = {}
then you CAN'T instantiate it. Thus the literal notation is generally more useful for namespacing than classes.prototype
object, or you can put the methods inside the constructor:// Option #1: This is the better way to do it, because it stores one copy of the method, // rather than a copy for each object that is instantiated. function Circle(r) { this.radius = r; } Circle.prototype.diameter = function () { return 2 * this.radius * 3.14; } // Option #2: here, we get identical copies of the function every time we // create a new Circle object. That uses a lot of memory. function Circle(r) { this.radius = r; this.diameter = function () { return 2 * this.radius * 3.14; } }
this
keyword in these.function Circle(r) { this.radius = r; } // class property. ALL CAPS is a convention, much like defining constants in PHP, Java, etc. Circle.MAX_RADUIS = 2; // class method. Circle.isTooBig = function(radius) { // return true if the radius given is bigger than the max radius return (radius > Circle.MAX_RADIUS) ? true : false; } Circle.isTooBig(3); // returns true
var re1 = RegExp("^foobar$", "i"); // matches the entire string foobar, ignoring case (that's the 'i') var re2 = /^foobar$/i; // same thing; different way of defining it
var re1 = RegExp("^foobar$", "i"); var myString = "FooBar"; var myString2 = "FooBarBaz"; myString.match(re1); // this will match myString2.match(re1); // this won't (and will return null), since the RegExp specified said we must begin and end with the string 'foobar'
See the JavaScript Notes & Best Practices document.