JS 101
Getting JS on the page
<script src="main.js"></script>
</body>
JavaScript Syntax
document.getElementById('header');
document
: object.
: property accessorgetElementById
: property (in this case, a function)()
: function call'header'
: argument (in this case, a String);
: end of the statement
Comments
A comment is ignored by the JS engine.
//
starts a single line comment./*
starts a multiple line comment,*/
ends the comment:
// This is a single line comment.
console.log("Cool"); // It can be at the end too
/* This is a multiple line comment.
Cool right? */
Statements
A JavaScript program is one or more JS statements. Like a sentence, a statement is one coherent "thought" or instruction.
- It should appear on its own line.
- It should end with a semicolon (a semicolon means "this instruction is over, move to the next one.")
Values (nouns)
Numbers
1;
3.14;
-20;
4.5e7;
String
'Cool';
"Cool";
"That was 'cool'";
"That was \"cool\"";
Booleans
A boolean represents something that is true or false.
true;
false;
10 > 5;
- Object
- Array
- Function
Special values
undefined // represents a value that is not defined
null // represents an object that is not defined
NaN // represents a Number that doesn't make sense, e.g. 0 / 0
Variable
Label for a value.
Declare a variable
var age;
Assign a value to a variable
age = 47;
A single equal sign is the "assignment operator".
Shorthand
Declare and assign:
var age = 47;
Declare multiple variables:
var age, favoriteColor, name;
Declare and assign multiple:
var age = 37, favoriteColor = "green", name = "Jake";
Naming
- First character a-z, A-Z, $,
_
- Variables starting with $ are often used for DOM objects
- Variables starting with
_
are often used for things that are not meant to be used by the developer - The other characters can be letters, $,
_
, numbers - They are case sensitive.
- The convention, but not rule, is to capitalize each word after the first:
var someCoolVariable;
Expressions
An expression is code that evaluates to a value.
// a value is an expression
'cool' // => 'cool'
// a variable is an expression
a // => 'cool'
// a variable declaration is also an expression
var c = 'another thing'; // => undefined
// a variable assignment is an expression
c = 'a third thing'; // => the rhs of the assignment, i.e. 'a third thing'
Mostly everything in JS is an expression / has a value
Operators (verbs)
Operators act on values to produce new values. The value and side effects differ for each operator.
[Arithmetic
Operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators)
4 + 3 // => 7
4 - 3 // => 1
4 * 3 // => 12
12 / 5 // => 2.4
12 % 5 // => 2
[Comparison
Operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
Loose (they coerce the type)
"cool" == "cool" // => true
"cool" != "dumb" // => true
1 == "1" // => true (it coerces the number into a string)
0 != false // => false (it coerces the number into a boolean)
12 > 5 // => true
12 >= 12 // => true
12 < 36 // => true
12 <= 12 // => true
Strict (do not coerce the type)
"cool" === "cool" // => true
"1" === 1 // => false
0 !== false // => true
[Logical
Operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators)
!true // => false
!(10 > 5) // => false
true && true // => true
true && false // => false
(10 > 5) && (10 < 100) // => true
(10 > 5) && (10 < 10) // => false
true || true // => true
true || false // => true
false || false // => false
(10 > 5) || (10 < 100) // => true
(10 > 5) || (10 < 10) // => true
[Assignment
Operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators) There are many available, but a couple of examples:
var x;
x = 2;
x // => 2
x += 2;
x // => 4
Functions
A function is a group of statements that can be called multiple times, and can be stored in a variable or passed around.
To put it another way: A function is an object that contains JavaScript code that is run when I call the function.
Functions have:
- Zero or more arguments
- Zero or more explicit parameters
- Two implicit parameters (
this
,arguments
) - Zero or more side effects
- Exactly one return value,
undefined
by default
Function Declaration
A function declaration is a complete statement that can stand on its own. It creates a function with the name you specify.
A function declaration consists of:
function
keyword- function name
- parameter list
- function body
function functionName(firstParameter) {
// body
}
Function Expression
A function expression cannot stand on its own, but we can assign it to a variable or pass it to another function. It's not a statement, it's an expression, so it must be used as part of a statement.
var aFunction = function(thing) {
alert(thing);
}
document.getElementById(id).addEventListener('click', function(){
alert("Hay");
});
// Immediately Invoked Function Expression
(function(){
})();
Scope
- Lexical (top to bottom)
- Variable declarations are hoisted to the top of their function, assignments are not
- Function declarations are hoisted in their entirety
Arrays
A type that is an ordered list of values.
create
var anArray = [1, 2, 3];
var secondArray = new Array(1, 2, 3);
Array length
anArray.length // => 3
get a value
Arrays are zero indexed.
anArray[1] // => 2
set a value
anArray[1] = 5;
anArray[100] = 'cool';
Object literal
Objects are both values and containers of values. The contained values are called properties and can include functions, arrays, and other objects.
While everything in JavaScript is basically an object, you can create "vanilla" objects (a.k.a. Plain Old JavaScript Objects or POJOs) using the "object literal".
Literal syntax
var theObject = {
someProperty: "cool",
anotherProperty: ['things', 'another thing']
};
Properties
Properties are like variables on objects.
var theObject = {
someProperty: "cool",
someOtherProperty: ["hay", "guyz"]
}
// New properties are created automatically when you assign to them
theObject.thirdThing = 123;
// Access properties with the dot (.)
var num = theObject.thirdThing;
// Or with brackets and strings
var cool = thirdThing['cool']
// Functions on objects are called 'methods'
var dog = {
bark: function(){
console.log(this); // => the dog
}
}
Boolean Logic
Boolean logic is at the heart of programming.
true
is not the same as 'true'
NOT is !
AND is &&
OR is ||
If two things must be true to proceed, then condition1 AND condition2
is the
logical statement you need.
If only one of two things must be true to proceed, then condition1 OR
condition2
is the logical statement you use.
In JavaScript, all values are either 'truthy' or 'falsy', meaning they can be (and are) coerced into booleans by operators and control flow.
Falsy values
""
0
false
undefined
null
NaN
Truthy values
Everything else
var name = "";
if(name){
// this will not happen
alert(name);
}
if...else
An if...else statement is one of the primary ways that you can control the flow of a JavaScript program (the other primary way is using functions).
if(/* something truthy */){
// do something
} else {
//something else
}
switch
switch
can be used to handle multiple scenarios for a single variable.
var name = "Jake";
switch(name) {
case "Jake":
console.log("Hi Jake");
break;
case "Finn":
console.log("Are you a human or a dog?");
break;
default:
console.log("I don't know you.");
}
for loops
In class, we will almost exclusively use iteration functions, but it's important to know what a for loop is:
for(var i = 0; i < 5; i++){
console.log(i);
}
// => 1
// => 2
// => 3
// => 4
// => 5
See MDN for documentation on for loops, and other loops:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/do...while
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in