Single or Double quotes OK
"hello world"
'hello world'
Concatenation
"charlie" + "brown"
Escape character starts with "\"
"This is a backslash:\\" // "This is a backslash:\\"
"hello".length % "hi\\".length
Strings have a length property counting from 1
"hello world".length
Access individual character using [] and an index
"hello"[0]
"hello"[4]
("blah"+"blah")[6]
null is "explicitly nothing"
var currentPlayer = "charlie";
currentPlayer = null; // game over
Variables that are declared but not initialized are undefined
The following variables are undefined:
var name;
var age;
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 |
"==" performs type coercion while "===" does not
var x = 99;
x == "99"
x === "99"
var y = null;
y == undefined;
y === undefined;
true === "1"
0 == false
null == undefined
Javascript cannot compare non-numbers
NaN == NaN
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 |
Values that aren't actually true or false are still inherently "truthy" or "falsey" when evaluated in a boolean context
!"Hello World"
!""
!null
!0
!-1
!NaN
while (true){
// run some code
}
var str = "hello";
var count = 0;
while (count < str.length){
console.log(str[count]);
count++;
}
// var count = 0;
// while (count < 10){
// console.log(count);
// }
for (init; condition; step){
run some code
}
var str = "hello";
for (var i=0; i<str.length; i++){
console.log(str[i]);
}
Functions let us wrap bits of code up into REUSABLE packages. They are one of the building block of Javascript.
Declare a function first:
function doSomething(){
console.log("Hello World");
}
Then call it:
doSomething();
doSomething();
function area(length, width){
console.log(length * width);
}
area(9, 2)
We use the return
keyword to output a value from a function
This function capitalize the first char in a string;
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
function capitalize(str){
if (typeof str === number){
return "that's not a string!";
}
}
Function declaration
function foo(){
return "foo";
}
Function expression
var bar = function foo(){
return "foo";
}
var friends = [];
var friends = new Array();
friends = ["Charlie", "Liz", "David"];
friends[3] = "Amelie";
Array are indexed starting at 0. We can use indices to retrieve data in an array
console.log(friends[0]);
friends[0] = "Chuck";
friends[1] = "Lizzie";
var nums = [45, 37, 89, 24];
nums.length;
var colors = ['red', 'orange', 'yellow'];
colors.push('green');
colors; ['red', 'orange', 'yellow', 'green'];
var col = colors.push('black');
col;
Use pop()
to remove the last item in an array
var colors = ['red', 'orange', 'yellow'];
colors.pop();
colors; ['red', 'orange'];
var col = colors.pop();
col;
Use unshift(item)
to add to the front of an array
var colors = ['red', 'orange', 'yellow'];
colors.unshift('infrared');
colors;
Use shift()
to remove first item in an array
var colors = ['red', 'orange', 'yellow'];
colors.shift();
colors;
shift()
returns the removed element
var col = colors.shift();
col;
Use indexOf(searchElement)
to find the index of an item in an array
Return -1 if the element is not found in an array
var friends = ['Charlie', 'Liz', 'David', 'Mattias', 'Liz'];
friends.indexOf("David");
friends.indexOf("Liz");
friends.indexOf("Hagrid");
Use slice(start, end)
to copy parts of an array
The original array remains intact
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
var citrus = fruits.slice(1, 3);
citrus;
fruits;
You can also use slice
to copy an entire array
var nums = [1, 2, 3];
var otherNums = nums.slice();
otherNums;
Use splice(start, deleteCount)
to remove
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
fruits.splice(1, 1);
console.log(fruits);
var colors = ['red', 'orange', 'yellow', 'green'];
for (var i=0; i<colors.length; i++){
console.log(colors[i]);
}
In the below example, note there is no () after someFunction because adding () will cause alert to invoke immediately. We want forEach to invoke someFunction
// arr.forEach(fn(param){
// do something
//});
var colors = ['red', 'orange', 'yellow', 'green'];
colors.forEach(function(color){
// 'color' is a placeholder, call it whatever you want
console.log(color);
});
Anonymous function is a function with no name
// function (){
// console.log("I'm a function");
// }
To run anonymous function: need to add () at the end
(function(){
console.log("I'm a function");
})()
Store data in key-value pairs
var person = {
name:"Travis",
age:21,
city:"LA"
};
console.log(person["name"]);
console.log(person.name);
You cannot use dot notation if the property starts with a number
// someObject.2blah; // invalid
// someObject["2blah"]; // valid
You can lookup using a variable with bracket notation
var str = "name";
console.log(person.str);
person[str];
You cannot use dot notation for property name with spaces
// someObject.fav color; // invalid
// someObject["fav color"]; // valid
Just like an array: access a property and reassign it
To update age
person["age"] += 1;
To update a city
person.city = "London";
var person = {};
person.name = "Travis";
person.age = 21;
person.city = "LA";
var person = {
name:"Travis",
age:21,
city:"LA"
};
var person = new Object();
person.name = "Travis";
person.age = 21;
person.city = "LA";
<!DOCTYPE html>
<html>
<head>
<title>My title</title>
</head>
<body>
<a href="someLink">My link</a>
<h1>My header</h1>
</body>
</html>
SELECT the element and then MANIPULATE
Change the <h1> color
var h1 = document.querySelector("h1");
h1.style.color = "pink";
var body = document.querySelector("body");
var isBlue = false;
setInterval(function(){
if (isBlue){
body.style.background = "white";
} else {
body.style.background = "#3498db";
}
isBlue = !isBlue;
}, 1000);
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>
Takes a string argument and returns the one element with a matching ID
var tag = document.getElementById("highlight");
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"
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>
var tag = document.querySelector("#highlight");
tag; // <li id = "highlight">List item 1</li>
var tag = document.querySelector(".bolded");
tag; // <li class = "bolded">List item 2</li>
var tag = document.querySelector("h1");
tag; // <h1>Hello</h1>
var tags = document.querySelectorAll(".bolded");
tags; // NodeList(2)[li.bolded, li.bolded]
var tags = document.querySelectorAll("h1");
tags; // NodeList(2)[h1, h1]
// 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";
var tag = document.getElementById("highlight");
tag.style.color = "blue";
tag.style.border = "10px solid red";
.some-class{
color:blue;
border:10px solid red;
}
var tag = document.getElementById("highlight");
tag.classList.add("some-class");
tag.classList.add("another-class");
remove()
¶tag.classList.remove("another-class");
toggle()
¶tag.classList.toggle("another-class");
<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
: 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"
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");
We select an element and then add an event listener
To add a listener, we use a method called addEventListener()
with a callback function
Callback function:
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");
});
<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";
});