Javascript Basics
Javascript Basics
io
JavaScript Basics
Nov. 3, 2014 15 min read original
Overview
JavaScript is a rich and expressive language in its own right. This section
covers the basic concepts of JavaScript, as well as some frequent pitfalls for
people who have not used JavaScript before. While it will be of particular
value to people with no programming experience, even people who have used
other programming languages may benefit from learning about some of the
peculiarities of JavaScript.
If youre interested in learning more about the JavaScript language, I highly
recommend JavaScript: The Good Parts by Douglas Crockford.
Syntax Basics
Understanding statements, variable naming, whitespace, and other basic
JavaScript syntax.
A simple variable declaration
var foo = 'hello world';
'hello world';
Operators
Basic Operators
Basic operators allow you to manipulate values.
Concatenation
var foo = 'hello';
var j = ++i;
// pre-increment:
j equals 2; i equals 2
var k = i++;
console.log(foo + bar);
// 12. uh oh
The Number constructor, when called as a function (like above) will have the
effect of casting its argument into a number. You could also use the unary plus
operator, which does the same thing:
Logical Operators
Logical operators allow you to evaluate a series of operands using AND and OR
operations.
Logical AND and OR operators
var foo = 1;
var bar = 0;
var baz = 2;
foo || bar;
bar || foo;
Though it may not be clear from the example, the || operator returns the
value of the first truthy operand, or, in cases where neither operand is truthy,
itll return the last of both operands. The && operator returns the value of the
first false operand, or the value of the last operand if both operands are truthy.
Be sure to consult the section called Truthy and Falsy Things for more
details on which values evaluate to true and which evaluate to false .
Note
Youll sometimes see developers use these logical operators for flow control
instead of using if statements. For example:
// do something with foo if foo is truthy
foo && doSomething(foo);
This style is quite elegant and pleasantly terse; that said, it can be really hard
to read, especially for beginners. I bring it up here so youll recognize it in code
you read, but I dont recommend using it until youre extremely comfortable
with what it means and how you can expect it to behave.
Comparison Operators
Comparison operators allow you to test whether values are equivalent or
whether values are identical.
Comparison operators
var foo = 1;
var bar = 0;
var baz = '1';
var bim = 2;
foo == bar;
// returns false
foo != bar;
// returns true
foo == baz;
// returns false
// returns true
// returns true
// returns false
// returns true
// returns true
Conditional Code
Sometimes you only want to run a block of code under certain conditions.
Flow control via if and else blocks lets you run code only under
certain conditions.
Flow control
var foo = true;
var bar = false;
if (bar) {
// this code will never run
console.log('hello!');
}
if (bar) {
// this code won't run
} else {
if (foo) {
// this code will run
} else {
// this code would run if foo and bar were both false
}
}
Note
While curly braces arent strictly required around single-line if statements,
using them consistently, even when they arent strictly required, makes for
vastly more readable code.
Be mindful not to define functions with the same name multiple times within
separate if / else blocks, as doing so may not have the expected result.
// an empty array
{};
// an empty object
1;
// an empty string
While the ternary operator can be used without assigning the return value to a
variable, this is generally discouraged.
Switch Statements
Rather than using a series of if/else if/else blocks, sometimes it can be useful
to use a switch statement instead. [Definition: Switch statements look at the
value of a variable or expression, and run different blocks of code depending
on the value.]
A switch statement
switch (foo) {
case 'bar':
alert('the value was bar -- yay!');
break;
case 'baz':
alert('boo baz :(');
break;
default:
alert('everything else is just ok');
break;
'baz' : function() {
alert('boo baz :(');
},
'default' : function() {
alert('everything else is just ok');
}
};
if (stuffToDo[foo]) {
stuffToDo[foo]();
} else {
stuffToDo['default']();
}
Loops
Loops let you run a block of code a certain number of times.
Loops
// logs 'try 0', 'try 1', ..., 'try 4'
for (var i=0; i<5; i++) {
console.log('try ' + i);
}
Note that in Loops even though we use the keyword var before the variable
name i , this does not scope the variable i to the loop block. Well discuss
scope in depth later in this chapter.
The initialisation statement is executed only once, before the loop starts. It
gives you an opportunity to prepare or declare any variables.
The conditional statement is executed before each iteration, and its return
value decides whether or not the loop is to continue. If the conditional
statement evaluates to a falsey value then the loop stops.
The iteration statement is executed at the end of each iteration and gives you
an opportunity to change the state of important variables. Typically, this will
involve incrementing or decrementing a counter and thus bringing the loop
ever closer to its end.
The loopBody statement is what runs on every iteration. It can contain
anything you want. Youll typically have multiple statements that need to be
executed and so will wrap them in a block ( {...} ).
Heres a typical for loop:
A typical for loop
for (var i = 0, limit = 100; i < limit; i++) {
// This block will be executed 100 times
console.log('Currently at ' + i);
// Note: the last log will be "Currently at 99"
}
Youll notice that were having to increment the counter within the loops
body. It is possible to combine the conditional and incrementer, like so:
Notice that were starting at -1 and using the prefix incrementer ( ++i ).
do {
These types of loops are quite rare since only few situations require a loop that
blindly executes at least once. Regardless, its good to be aware of it.
You may also want to continue the loop without executing more of the loops
body. This is done using the continue statement.
Skipping to the next iteration of a loop
for (var i = 0; i < 10; i++) {
if (something) {
continue;
}
// The following statement will only be executed
// if the conditional 'something' has not been met
console.log('I have been reached');
Reserved Words
JavaScript has a number of reserved words, or words that have special
meaning in the language. You should avoid using these words in your code
except when using them with their intended meaning.
abstract
boolean
break
byte
case
catch
char
class
const
continue
debugger
default
delete
do
double
else
enum
export
extends
final
finally
float
for
function
goto
if
implements
import
in
instanceof
int
interface
long
native
new
package
private
protected
public
return
short
static
super
switch
synchronized
this
throw
throws
transient
try
typeof
var
void
volatile
while
with
Arrays
Arrays are zero-indexed lists of values. They are a handy way to store a set of
related items of the same type (such as strings), though in reality, an array can
include multiple types of items, including other arrays.
A simple array
var myArray = [ 'hello', 'world' ];
// logs 'bar'
// logs 2
While its possible to change the value of an array item as shown in Changing
the value of an array item, its generally not advised.
Adding elements to an array
var myArray = [ 'hello', 'world' ];
myArray.push('new');
// 'hello'
Objects
Objects contain one or more key-value pairs. The key portion can be any
string. The value portion can be any type of value: a number, a string, an array,
a function, or even another object.
[Definition: When one of these values is a function, its called a method of the
object.] Otherwise, they are called properties.
As it turns out, nearly everything in JavaScript is an object arrays,
functions, numbers, even strings and they all have properties and methods.
Creating an object literal
var myObject = {
sayHello : function() {
console.log('hello');
},
myName : 'Rebecca'
};
myObject.sayHello();
// logs 'hello'
console.log(myObject.myName);
// logs 'Rebecca'
Note
When creating object literals, you should note that the key portion of each
key-value pair can be written as any valid JavaScript identifier, a string
(wrapped in quotes) or a number:
var myObject = {
validIdentifier: 123,
'some string': 456,
99999: 789
};
Object literals can be extremely useful for code organization; for more
information, read Using Objects to Organize Your Code by Rebecca Murphey.
Functions
Functions contain blocks of code that need to be executed repeatedly.
Functions can take zero or more arguments, and can optionally return a value.
Functions can be created in a variety of ways:
Function Declaration
function foo() { /* do something */ }
I prefer the named function expression method of setting a functions name, for
some rather in-depth and technical reasons. You are likely to see both methods
used in others JavaScript code.
Using Functions
A simple function
var greet = function(person, greeting) {
var text = greeting + ', ' + person;
console.log(text);
};
greet('Rebecca', 'Hello');
console.log(greet('Rebecca','hello'));
console.log(foo);
// undefined!
Functions as Arguments
In JavaScript, functions are first-class citizens they can be assigned to
variables or passed to other functions as arguments. Passing functions as
arguments is an extremely common idiom in jQuery.
Testing Type
JavaScript offers a way to test the type of a variable. However, the result can
be confusing for example, the type of an Array is object.
Its common practice to use the typeof operator when trying to determining
the type of a specific value.
Testing the type of various variables
var myFunction = function() {
console.log('hello');
};
var myObject = {
foo : 'bar'
};
var myArray = [ 'a', 'b', 'c' ];
var myString = 'hello';
var myNumber = 3;
typeof myFunction;
// returns 'function'
typeof myObject;
// returns 'object'
typeof myArray;
typeof myString;
// returns 'string';
typeof myNumber;
// returns 'number'
typeof null;
jQuery offers utility methods to help you determine the type of an arbitrary
value. These will be covered later.
myName : 'Rebecca'
};
var secondObject = {
myName : 'Colin'
};
myObject.sayHello();
sayHello = function () {
console.log('Hi! My name is ' + this.myName);
},
myObject = {
myName : 'Rebecca'
};
var myObjectHello = sayHello.bind(myObject);
sayHello();
myObjectHello();
sayHello = function() {
console.log('Hi! My name is ' + this.myName);
},
myObject = {
myName : 'Rebecca'
},
secondObject = {
myName : 'Colin'
};
myObject.sayHello = sayHello;
secondObject.sayHello = sayHello;
sayHello();
myObject.sayHello();
secondObject.sayHello();
Note
When invoking a function deep within a long namespace, it is often tempting
to reduce the amount of code you need to type by storing a reference to the
actual function as a single, shorter variable. It is important not to do this with
instance methods as this will cause the value of this within the function to
change, leading to incorrect code operation. For instance:
var myNamespace = {
myObject : {
sayHello : function() {
console.log('Hi! My name is ' + this.myName);
},
myName : 'Rebecca'
}
};
var hello = myNamespace.myObject.sayHello;
hello();
You can, however, safely reduce everything up to the object on which the
method is invoked:
var myNamespace = {
myObject : {
sayHello : function() {
console.log('Hi! My name is ' + this.myName);
},
myName : 'Rebecca'
}
};
var obj = myNamespace.myObject;
obj.sayHello();
Scope
Scope refers to the variables that are available to a piece of code at a given
time. A lack of understanding of scope can lead to frustrating debugging
experiences.
sayHello();
// logs 'hello'
console.log(foo);
Code outside the scope in which a variable was defined does not have
access to the variable
var sayHello = function() {
var foo = 'hello';
console.log(foo);
};
sayHello();
// logs 'hello'
console.log(foo);
Variables with the same name can exist in different scopes with different
values
var foo = 'world';
// logs 'hello'
console.log(foo);
// logs 'world'
return myFn;
};
var f = myFunction();
f();
// logs 'world' -- uh oh
Scope insanity
// a self-executing anonymous function
(function() {
var baz = 1;
var bim = function() { alert(baz); };
bar = function() { alert(baz); };
})();
console.log(baz);
bar();
Closures
Closures are an extension of the concept of scope functions have access to
variables that were available in the scope where the function was created. If
thats confusing, dont worry: closures are generally best understood by
example.
In Functions cansee" changes in variable values after the function is
defined, we saw how functions have access to changing variable values. The
same sort of behavior exists with functions defined within loops the
function sees the change in the variables value even after the function is
defined, resulting in all clicks alerting 5.
Closures can also be used to resolve issues with the this keyword, which is
unique to each scope:
Using a closure to access inner and outer object instances
simultaneously
var outerObj = {
myName : 'outer',
outerFunction : function () {
innerObj.innerFunction();
console.log(this.myName); // logs 'outer'
}
};
outerObj.outerFunction();
Original URL:
http://autotelicum.github.io/Smooth-CoffeeScript/literate/js-intro.html