Table of Contents

Javascript Basics

Background

  • Adds logic and interactivity to a webpage
  • The actions or "verbs" of a webpage

Primitives

5 Primitive Data Types

1) Numbers

2) Strings

Single or Double quotes OK

In [1]:
"hello world"
'hello world'
Out[1]:
'hello world'

Concatenation

In [3]:
"charlie" + "brown"
Out[3]:
'charliebrown'

Escape character starts with "\"

In [4]:
"This is a backslash:\\" // "This is a backslash:\\"
Out[4]:
'This is a backslash:\\'
In [6]:
"hello".length % "hi\\".length
Out[6]:
2

Strings have a length property counting from 1

In [7]:
"hello world".length
Out[7]:
11

Access individual character using [] and an index

In [14]:
"hello"[0]
Out[14]:
'h'
In [13]:
"hello"[4]
Out[13]:
'o'
In [10]:
("blah"+"blah")[6]
Out[10]:
'a'

3) Boolean

See "Boolean Logic" below

4) null

null is "explicitly nothing"

In [15]:
var currentPlayer = "charlie";
currentPlayer = null; // game over
Out[15]:
null

5) undefined

Variables that are declared but not initialized are undefined

The following variables are undefined:

In [19]:
var name;
var age;

Boolean Logic

Comparison Operators

Assume x = 5

Operator Name Example Result
> Greater than x > 10 false
<= Greater than or equal to x >= 5 true
< less than x < -50 false
<= less than or equal to x <= 100 true
!= Not equal to X != "b" true
=== Equal value and type x === "5" false
!== Not equal value and equal type x !== 5 true

Equality Operators

== vs. ===

"==" performs type coercion while "===" does not

In [20]:
var x = 99;
x == "99"
Out[20]:
true
In [21]:
x === "99"
Out[21]:
false
In [22]:
var y = null;
y == undefined;
Out[22]:
true
In [23]:
y === undefined;
Out[23]:
false

A Few Interesting Cases

In [24]:
true === "1"
Out[24]:
false
In [26]:
0 == false
Out[26]:
true
In [27]:
null == undefined
Out[27]:
true

Javascript cannot compare non-numbers

In [29]:
NaN == NaN
Out[29]:
false

Logical Operators

AND, OR and NOT

Assume x = 5 and y = 9

Operator Name Example Result
&& AND x < 10 && x !== 5 false
|| OR y < 9 $ $ x ==== 5 true
! NOT !(x === y) true

Truthy and Falsy Values

Values that aren't actually true or false are still inherently "truthy" or "falsey" when evaluated in a boolean context

In [31]:
!"Hello World"
Out[31]:
false
In [32]:
!""
Out[32]:
true
In [33]:
!null
Out[33]:
true
In [34]:
!0
Out[34]:
true
In [35]:
!-1
Out[35]:
false
In [36]:
!NaN
Out[36]:
true

Falsy Values

  • false
  • 0
  • ""
  • null
  • undefined
  • NaN

Everything else is Truthy

While Loop

Repeat code WHILE a condition is true

while (true){
  // run some code
}
In [2]:
var str = "hello";
var count = 0;

while (count < str.length){
  console.log(str[count]);
  count++;
}
h
e
l
l
o
Out[2]:
4

Infinite loops occur when the terminating condition in a loop never returns false

In [3]:
// var count = 0;

// while (count < 10){
//   console.log(count);
// }

For Loop

for (init; condition; step){
  run some code
}
In [6]:
var str = "hello";

for (var i=0; i<str.length; i++){
  console.log(str[i]);
}
h
e
l
l
o

Functions

Functions let us wrap bits of code up into REUSABLE packages. They are one of the building block of Javascript.

Declare a function first:

In [7]:
function doSomething(){
  console.log("Hello World");
}

Then call it:

In [8]:
doSomething();
doSomething();
Hello World
Hello World

Function Arguments

In [10]:
function area(length, width){
  console.log(length * width);
}

area(9, 2)
18

The return Keyword

We use the return keyword to output a value from a function

This function capitalize the first char in a string;

In [11]:
function capitalize(str){
  return str.charAt(0).toUpperCase().slice(1);
}

var city = "paris";
var capital = capitalize(city);

// We can capture the returned value in a variable

The return keyword stops execution of a function

In [12]:
function capitalize(str){
  if (typeof str === number){
    return "that's not a string!";
  }
}

Function Declaration vs Function Expression

Function declaration

In [13]:
function foo(){
  return "foo";
}

Function expression

In [14]:
var bar = function foo(){
  return "foo";
}

If you change the value of variable bar afterwards, you will lose you function

Arrays

Create an Empty Array

We can initialize an empty array two ways:

In [15]:
var friends = [];
In [16]:
var friends = new Array();

Add Items in an Array

In [17]:
friends = ["Charlie", "Liz", "David"];
friends[3] = "Amelie";
Out[17]:
'Amelie'

Read an Array

Array are indexed starting at 0. We can use indices to retrieve data in an array

In [18]:
console.log(friends[0]);
Charlie

Update an Array

In [19]:
friends[0] = "Chuck";
friends[1] = "Lizzie";
Out[19]:
'Lizzie'

Arrays have a length property

In [21]:
var nums = [45, 37, 89, 24];
nums.length;
Out[21]:
4

Array Built-in Methods

Push and Pop

Use push(item) to add to the end of an array

In [23]:
var colors = ['red', 'orange', 'yellow'];
colors.push('green');
colors; ['red', 'orange', 'yellow', 'green'];

var col = colors.push('black');
col;
Out[23]:
5

Use pop() to remove the last item in an array

In [25]:
var colors = ['red', 'orange', 'yellow'];
colors.pop();
colors; ['red', 'orange'];

var col = colors.pop();
col;
Out[25]:
'orange'

Shift and Unshift

Use unshift(item) to add to the front of an array

In [27]:
var colors = ['red', 'orange', 'yellow'];
colors.unshift('infrared');
colors;
Out[27]:
[ 'infrared', 'red', 'orange', 'yellow' ]

Use shift() to remove first item in an array

In [28]:
var colors = ['red', 'orange', 'yellow'];
colors.shift();
colors;
Out[28]:
[ 'orange', 'yellow' ]

shift() returns the removed element

In [29]:
var col = colors.shift();
col;
Out[29]:
'orange'

IndexOf

Use indexOf(searchElement) to find the index of an item in an array Return -1 if the element is not found in an array

In [31]:
var friends = ['Charlie', 'Liz', 'David', 'Mattias', 'Liz'];
friends.indexOf("David");
Out[31]:
2
In [35]:
friends.indexOf("Liz");
Out[35]:
1
In [34]:
friends.indexOf("Hagrid");
Out[34]:
-1

Slice

Use slice(start, end) to copy parts of an array The original array remains intact

In [37]:
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
var citrus = fruits.slice(1, 3);

citrus;
Out[37]:
[ 'Orange', 'Lemon' ]
In [38]:
fruits;
Out[38]:
[ 'Banana', 'Orange', 'Lemon', 'Apple', 'Mango' ]

You can also use slice to copy an entire array

In [40]:
var nums = [1, 2, 3];
var otherNums = nums.slice();

otherNums;
Out[40]:
[ 1, 2, 3 ]

Splice

Use splice(start, deleteCount) to remove

In [42]:
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
fruits.splice(1, 1);
Out[42]:
[ 'Orange' ]
In [43]:
console.log(fruits);
[ 'Banana', 'Lemon', 'Apple', 'Mango' ]

Array Iteration

For vs. ForEach Loop

For Loop

To loop over an array using a for loop, we need to make use of the array. length property

In [44]:
var colors = ['red', 'orange', 'yellow', 'green'];

for (var i=0; i<colors.length; i++){
  console.log(colors[i]);
}
red
orange
yellow
green
ForEach Loop

In the below example, note there is no () after someFunction because adding () will cause alert to invoke immediately. We want forEach to invoke someFunction

In [79]:
// arr.forEach(fn(param){
//    do something
//});
In [77]:
var colors = ['red', 'orange', 'yellow', 'green'];

colors.forEach(function(color){
  // 'color' is a placeholder, call it whatever you want
  console.log(color);
});
red
orange
yellow
green
Anonymous Function

Anonymous function is a function with no name

In [82]:
// function (){
//   console.log("I'm a function");
// }

To run anonymous function: need to add () at the end

In [54]:
(function(){
  console.log("I'm a function");
})()
I'm a function

Objects

Store data in key-value pairs

In [69]:
var person = {
  name:"Travis",
  age:21,
  city:"LA"
};

Note: unlike arrays, objects have no order

Retrieving Data

You have two choices: bracket and dot notation:

Bracket Notation []

In [56]:
console.log(person["name"]);
Travis

Dot Notation .

In [57]:
console.log(person.name);
Travis

Differences between the 2 notations:

You cannot use dot notation if the property starts with a number

In [66]:
// someObject.2blah;    // invalid
// someObject["2blah"]; // valid

You can lookup using a variable with bracket notation

In [70]:
var str = "name";
console.log(person.str);
undefined
In [72]:
person[str];
Out[72]:
'Travis'

You cannot use dot notation for property name with spaces

In [73]:
// someObject.fav color;    // invalid
// someObject["fav color"]; // valid

Updating Data

Just like an array: access a property and reassign it

To update age

In [74]:
person["age"] += 1;
Out[74]:
22

To update a city

In [75]:
person.city = "London";
Out[75]:
'London'

Creating Objects

Like arrays, there are a few methods of initializing Objects

Make an empty object and then add to it

In [65]:
var person = {};
person.name = "Travis";
person.age = 21;
person.city = "LA";
Out[65]:
'LA'

All at once

In [64]:
var person = {
  name:"Travis",
  age:21,
  city:"LA"
};

Using the new keyword

In [63]:
var person = new Object();
person.name = "Travis";
person.age = 21;
person.city = "LA";
Out[63]:
'LA'

DOM

Document Object Model

  • The Document Object Model is the interface between your Javascript and HTML + CSS
  • The browser turns every HTML tag into a Javascript object that we can manipulate
  • Everything is stored inside of the document object
<!DOCTYPE html>
<html>
<head>
    <title>My title</title>
</head>
<body>
    <a href="someLink">My link</a>
    <h1>My header</h1>
</body>
</html>

DOM_Object

The Process

SELECT the element and then MANIPULATE

Change the <h1> color

var h1 = document.querySelector("h1");
h1.style.color = "pink";

Select the <body> and change its color every second

var body = document.querySelector("body");
var isBlue = false;

setInterval(function(){
  if (isBlue){
    body.style.background = "white";
  } else {
    body.style.background = "#3498db";
  }
  isBlue = !isBlue;
}, 1000);

DOM Selectors

The document comes with a bunch of methods of selecting elements.

<body>
  <h1>Hello</h1>
  <h1>Goodbye</h1>
  <ul>
    <li id = "highlight">List item 1</li>
    <li class = "bolded">List item 2</li>
    <li class = "bolded">List item 3</li>
  </ul>
</body>

document.getElementById()

Takes a string argument and returns the one element with a matching ID

var tag = document.getElementById("highlight");

document.getElementsByClassName()

Take a string argument and returns a list of elements that have a matching class

var tags = document.getElementsByClassName("bolded");
console.log(tags[0].innerHTML); // "List item 2"

document.getElementsByTagName()

Returns a list of all elements of a given tag name, like <li> or <h1>

var tags = document.getElementsByTagName("li");
console.log(tags[0]); // <li id = "highlight">List item 1</li>

document.querySelector()

Returns the first element that matches a given CSS-style selector

Select by ID

var tag = document.querySelector("#highlight");
tag; // <li id = "highlight">List item 1</li>

Select by Class

var tag = document.querySelector(".bolded");
tag; // <li class = "bolded">List item 2</li>

Select by Tag

var tag = document.querySelector("h1");
tag; // <h1>Hello</h1>

document.querySelectorAll()

Returns a list of elements that matches a given CSS-style selector

Select by Class

var tags = document.querySelectorAll(".bolded");
tags; // NodeList(2)[li.bolded, li.bolded]

Select by Tag

var tags = document.querySelectorAll("h1");
tags; // NodeList(2)[h1, h1]

DOM Manipulation

Changing an element's style

// SELECT
var tag = document.getElementById("highlight");

// MANIPULATE
tag.style.color = "blue";
tag.style.border = "10px solid red";
tag.style.fontsize = "70px";
tag.style.background = "yellow";
tag.style.marginTop = "200px";

Adding/ Removing classes

Rather than directly manipulating style with Javascript, we can define a CSS class and then toggle it on or off with Javascript

Instead of this:

var tag = document.getElementById("highlight");
tag.style.color = "blue";
tag.style.border = "10px solid red";

Define a class in CSS

.some-class{
  color:blue;
  border:10px solid red;
}

Add the new class to the selected element classList.add()

var tag = document.getElementById("highlight");
tag.classList.add("some-class");

classList

A read-only list that contains the classes for a given element. It is not an array

Add a class to the selected element: add()
tag.classList.add("another-class");
Remove a class remove()
tag.classList.remove("another-class");
Toggle a class toggle()
tag.classList.toggle("another-class");

Changing the content of a tag

textContent

textContent: Returns a string of all the text contained in a given element

<p>
  This is an <strong>awesome</strong> paragraph
</p>
// select
var tag = document.querySelector("p");

tag.textContent; // "This is an awesome paragraph"

//alter the textContent
tag.textContent = "blah blah blah";

innerHTML

innerHTML: Similar to textContent, except it returns a string of all the HTML contained in a given element

var tag = document.querySelector("p");

tag.innerHTML; // "This is an <strong>awesome</strong> paragraph"

Changing the attributes (src, href etc.)

Using getAttribute() and setAttribute() to read and write attributes like src or href

<a href = "www.google.com">I am a link</a>
<img src = "logo.png">
var link document.querySelector("a");

link.getAttribute("href"); // "www.google.com"

// Change href attribute
link.setAttribute("href", "www.dogs.com");

// To change the image src
var img = document.querySelector("img");
img.setAttribute("src", "corgi.png");

DOM Events

Events are everywhere

  • Clicking on a button
  • Hovering over a link
  • Dragging and Dropping
  • Pressing the Enter key

The Process

We select an element and then add an event listener

The Syntax

To add a listener, we use a method called addEventListener() with a callback function

Callback function:

  • Not invoked immediately (no bracket after function name)
  • Invoke whenever an event fires
element.addEventListener(eventType, callBackfunction);
<button>Click Me</button>
<p>No one has clicked me yet</p>
var button = document.querySelector("button");
var paragraph = document.querySelector("p");

button.addEventListener("click", function(){
  paragraph.textContent("Someone clicked the button");
});

So Many Events!

MDN lists over 300 different events! Here are some of the more common ones:

  • click
  • mouseover
  • mouseout
  • dblclick
  • keypress
  • drag

An Example

<p>I dare you to mouse over me</p>

We can DRY up our code with this

var paragraph = document.querySelector("p");

// Setup mouseover listener
paragraph.addEventListener("mouseover", function(){
  this.textContent = "Stop hovering over me";
});

// Setup mouseout listener
paragraph.addEventListener("mouseout", function(){
  this.textContent = "Phew, thank you for leaving me alone";
});