Useful Javascript libraries
- Underscore.js contains a number of useful functions
Language basics
- Javascript is a dynamically typed language * // and /**/ are used to comment out code
Javascript variable types
- Number floating point numbers var num = 6;
- String sequence of charcters var str = "This is a string";
- Boolean true or false var what = true;
- Undefined variable doesn't have a value currently
- Null - non-existent
Log information to the debug console
var name = "string";
console.log(name);
Operators (MDN Operator Reference)
+ concatenation
- subtraction
* multiplication
/ division
== equals with type coercion
=== equals without type coercion
Boolean operators
- AND && OR || NOT !
Functions
- Functions are lexically scoped Each new function creates a scope Functions can access variables in the current execution context and all previous execution contexts (including the global execution context) Function scoping dictates what a function can see though Method borrowing allows an object to use a method from another object * A function inside an object is called a method
Function example:
function myFunc(param1, param2) {
console.log(param1);
return 2 + 2;
}
Control statements
- Case statements are used to control program flow * if () {} ... else if () {} ... else {} are also used to control program flow
Case statement:
job = "cabbie";
switch (job) {
case 'cabbie':
....
break;
case default:
....
}
If statement:
if (expression) {
....
else {
....
}
Use the ternary operator to shorten the if else
this.textContent === "Gorp" ? foo = 3: foo = 1;
Loop statements
The break and continue keywords can be used to skip a loop and to break out of a loop
For loops:
for (var i = 0; i < 10; i++ {
....
}
ForEach loops:
var nums = [12, 24, 36, 48];
nums.forEach(function(num) {
console.log(num);
});
function printNum(number) {
console.log(number);
}
var nums = [12, 24, 36, 48];
nums.forEach(printNum);
While loops:
var myArray = ["a", "b", "c"];
while (myArray.length > 0) {
console.log(myArray.pop());
}
Arrays (zero based)
var names = ['Bill', 'Louie', 'Mark'];
var names = new Array(Bill, Louie, Mark);
console.log(names[0]);
Mutate a value in an array:
names[0] = 'Sherry';
Add an entry to the end of the array:
names.push('Oppie');
Add an entry to the beginning of an array:
names.unshift('Sue');
Grab the last entry from an array and remove it:
names.pop();
Grab the first entry from an array and remote it:
names.shift();
Get the position of an array element:
-1 entry doesn't exist return code contains index of entry we are looking for
names.indexOf('Oppie');
Check if an entry exists in an array:
if (names.indexOf('Oppie') === -1 ) {
// Oppie doesn't exist
}
Create a subset of an array (a slice)
var num = [ 12, 24, 36, 48, 60];
var foo = num.slice(2,3);
Methods to display data and get feedback while debugging
Clear the screen:
clear()
Pop up an alert:
alert("I am annoying you!");
Prompt the user for input:
prompt("Please type something in:");
Objects (unordered)
- Items in an object are referred to as properties The this variable refers to the current object Objects have no order
Create an object:
var travel = {
destination: 'Florida',
luggage: true,
travelData: 10-10-2018,
clothes: ['shirts', 'pants', 'socks']
packed: false;
// Function expression
packed: function() {
return this.packed;
}
}
Grab an entry out of an object:
travel.destination;
travel['destination'];
travel[myVariable];
Create a new base object:
var foo = new Object()l
foo.destination = 'Canada';
Execution contexts
- This points to the global object in a regular function call This points to the object that is calling the method in a method call The this keywork is not assigned a value until a function where it is defined is actually called * When a function call occurs this points to the Window object
DOM manipulation and events
- DOM -> Document Object Model The DOM is a structured represnetation on an HTML docment DOM models are modeled in Javascript The DOM is used to connect web pages to javascript For each HTML section there is a DOM object created that we can use in our scripts Events are notifications sent to notify us that something (mouse click, window resize, etc.) happened Event listener waits for an event to happen and performs an action Message queue is where events are placed when they happen Event listeners are functions that are called when an event occurs
DOM manipulation methods
- Document selector methods (these return a node list):
- document.getElementById()
- document.getElementsByClassName()
- document.getElementsByTagName()
- document.querySelector()
- document.querySelectorAll()
myVar = 23;
document.querySelector('#selector').textContent = myVar;
myVar = 23;
document.querySelector('#selector').innerHTML = '`strong`STRONG TEXT</strong>';
var val1 = document.querySelector('#selector').textContent;
console.log(val1)
Set CSS attribute for a class:
document.querySelector('.myClass').style.display = 'none';
document.querySelector('.myClass').style.display = 'block';
Add an event listener for click. onClick is the callback function.
function onClick() {
...
}
document.querySelector('.myClass').addEventListener('click', onClick);
Select all a tags with theclass gorp inside li:
document.querySelector("li a.gorp");
Use an anonymous function
document.querySelector('.myClass').addEventListener('click', function() {
...
}
Change an image
var myVar = document.querySelector('.myElement');
myVar.style.display = 'clock';
myVar.src = 'image-2.png';
Get an element by id
document.getElementById('#myElement').textContent = 0;
Useful javascript methods
Run code at an interval
setInterval(funcToCall(), interval_in_ms)
Get the type of a variable:
var foo = 23;
typeof foo;
DOM manipulation
Print the DOM from a page to the Javascript console
console.dir(document)
CSS class adds / removes
document.querySelector("a").classList.add("newCSSClass"); // Add a class to an a element document.querySelector("a").classList.remove("newCSSClass"); // Remove a class from a element document.querySelector("a").classList.toggle("newCSSClass"); // Toggle the class on and off for the a element
Get and set element attributes
var aTag = document.querySelector("a");
aTag.getAttribute("href");
aTag.setAttribute("href","prefetch.net");