JavaScript notes
Below you'll find my personal notes I've taken throughout my JavaScript journey. This is information I have been working on/with for weeks now. Enjoy!
let and const are your main line starters
&& = and
|| = or
console.log(); runs your code in the console
always end javascript statements with a semicolon ;
if…else statements serve as a “if this happens, do this”
you can run math in javascript using < and > operations
Operators: 7 types
Arithmetic
Assignment
Comparison
Equality
Ternary
Logical
Bitwise
use break to separate code in a block
switch allows case to be evaluated, such as assigning roles.
switch and case are essentially outdated if else statements. comes down to personal preference.
JavaScript has loops. for, while do…while for…in and for…of
for loop
for (let i = 0; i < 5; i++){ //this lets it run 5 times
console.log('hello world');
}
i ++ ads a value to i every time the loop runs, so it doesn’t run infinitely.
as long as i is less than 5, the statement will execute infinitely. i will eventually = 5 due to the i ++ statement
for (let i + 1; i <= 5; i++) {
if (i % 2 !== 0) console.log(i);
}
// this displays all odd numbers 1-5 because i divided by 2 should not equal 0 if it is an even number.
while loop
let i = 0;
while (i <= 5) {
if (i % 2 !== 0) console.log(i);
i++;
}
essentially while loops are the same thing but the variables are external.
do…while loop
let i = 0;
do {
if (i % 2 !== 0) console.log(i);
i++;
} while (i <= 5);
Make sure to add i++ as to not create an infinite loop, you will crash your computer.
for…in loop
const person = {
name: 'Micah',
age: 19
}
for (let key in person)
console.log(key, person[key]);
const colors = ['red', 'green', 'blue'];
for (let index in colors)
console.log(index, colors[index]);
for…of loop
const colors = ['red', 'green', 'blue'];
for (let color of colors)
console.log(color);
break is used to stop a loop from functioning.
purpose of an object is to group related variables.
// Object-oriented Programming (OOP)
const circle = {
radius: 1,
location {
x: 1,
y: 1
},
isVisible: true,
draw: function() {
console.log('draw');
}
};
circle.draw(); // Method
// Factory Function
function createCircle (radius) {
return {
radius,
draw() {
console.log('draw');
}
};
}
const cricle1 = createCircle(1);
console.log(circle1);
const circle2 = createCircle(2);
console.log(circle2);
// Constructor Function !Pascal Notation!
function Circle(radius) {
this.radius = radius;
this.draw = function(){
console.log('draw');
}
}
const circle = new Circle(1);
// Camel Notation: oneTwoThreeFour
// Pascal Notation: OneTwoThreeFour
you can put delete before dot notation to remove properties of objects.
const circle = {
radius: 1
}
circle.color = 'yellow';
circle.draw = function() {}
delete circle.color;
delete circle.draw;
console.log(circle);
inputing constructor in dot notation after your object name (circle.constructor) in order to reference the function that was used to create the object.
backticks are used for quotations on multiple lines.
Two Types
Value Types (primitives)
number, string, boolean, symbol, undefined, and null.
Reference Types:
object, function, array.
primitives are copied by value, objects are copied by reference.
use value property in order to make reference changes work.
for-in loops can only be used with arrays and maps.
‘in’ is used to see if properties exist within an object.
object.assign is used to clone the properties of an object into another object.
const another = Object.assign({}, circle);
// copying properties from circle to another
JavaScript has an allocated garbage collector. n
JavaScript has math functions built in. google javascript math and go to MDN.
// string primitive
const message = 'hi';
// string object
const another = new String('hi');
message.indexOf(’’) shows at what space the character starts.
message.trim(’’) removes spaces before/after statement
message.replace(’this’, ‘that’) replaces this with that in the message
message displays the message
message.toUpperCase() turns the message uppercase.
^^^ for these, look up javascript string on MDN
**n adds a new line to a string, can also use backticks like i said earlier ``. mainly use backticks, aka template literals**. template literals are much easier to deal with.
const now = new Date();
const date1 = new Date('May 11 2018 09:00');
const date2 = new Date(2018, 4, 11, 9, 0);
^ dates, javascript date on MDN.
months are 0-11, 0 being january 11 being december
year, month, day, hour, minute.
const does not stop you from modifying an array.
const numbers = [3, 4];
// end
numbers.push(5, 6);
// beginning
numbers.unshift(1, 2);
// middle
numbers.splice(2, 0,'a','b');
2 is for the index, 0 is how many elements we want to remove.
// indexOf returns the index of an array
const numbers = [1, 2, 3, 4];
console.log(numbers.indexOf('x'));
console.log(numbers.lastIndexOf(1));
// fill in x with a number or other element like a or b
console.log(numbers.includes(1))
// if this returns true, the element is in the array
const courses = [
{ id: 1, name: 'a' },
{ id: 2, name: 'b' },
];
const course = courses.find(function(course) {
return course.name === 'a';
});
or you can write that second part in an arrow function like this
const course = courses.find(course => course.name === 'a');
const numbers = [1, 2, 3, 4,];
// removing elements from an array
// end
const last = numbers.pop();
// beginning
const first = numbers.shift();
// middle
numbers.splice(2, 1);
// splice setup is (index, how many elements to remove)
emptying an array
let numbers = [1, 2, 3, 4];
let another = numbers;
// solution 1
numbers = [];
// only works if you have one source^
// solution 2
numbers.length = 0;
// solution 3
numbers.splice(0, numbers.length);
// solution 4
while (numbers.length > 0)
numbers.pop();
// not recommended^
combining and slicing arrays
const first = [1, 2, 3];
const second = [4, 5, 6];
const combined = first.concat(second);
const slice = combined.slice(2,4);
// start at index 2, end at 4^
spread aka …
const first = [1, 2, 3];
const second = [4, 5, 6];
const combined = [...first, 'a', ...second, 'b'];
const copy = [...combined]
iterating
const numbers = [1, 2, 3];
for (let number of numbers)
numbers.forEach(function(number){
});
joining
const numbers = [1, 2, 3];
const joined = numbers.join(',');
console.log(joined);
const message = 'This is my first message';
const parts - message.split(' ');
console.log(parts);
const combined = parts.join ('-')
console.log(combined);
sorting arrays
const numbers = [2, 3, 1];
numbers.sort();
// sorts in numerical order^
numbers.reverse();
// ^reverses order
const courses = [
{ id: 1, name: 'Node.js' },
{ id: 2, name: 'JavaScript'},
];
courses.sort(function(a, b) {
// a < b => -1
// a > b => 1
// a === b => 0
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
});
testing elements
const numbers = [1, 2, 3];
const allPositive = numbers.every(function(value) {
return value >= 0;
});
every() checks to see if EVERY element meets the criteria, while some() checks to see if any meet the criteria.
filtering arrays
const numbers = [1, -1, 2, 3];
const filtered = numbers.filter(function(value) {
return value >=0
});
// this causes only positive integers to show^
const filtered = numbers.filter(n => n >= 0);
// arrow'd version^
mapping arrays
const numbers = [1, -1, 2, 3];
const filtered = numbers.filter(n => n >= 0);
const items = filtered.map(n => '<li>' + n + '</li>');
const html = '<ul>' + items.join('') + '</ul>';
let’s clean it up
const numbers = [1, -1, 2, 3];
const items = numbers
.filter(n => n >= 0)
.map(n => ({ value: n }));
// did remove html^
reducing arrays
const numbers = [1, -1, 2, 3];
let sum = 0;
for (let n of numbers)
sum += n;
console.log(sum);
// this is for adding the numbers^
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
console.log(sum);
// this is another way to do it^
declaration vs expression
// function declaration
function walk() {
console.log('walk');
}
// named function expression
let run = function walk() {
console.log('run');
}
// anonymous function expression
let run = function() {
console.log('run');
};
let move = run;
run();
move();
hoisting
function declaration can hoist, aka moving function declarations to the top of the file.
arguments
this function allows you to pass multiple arguments
function sum(a, b) {
let total = 0;
for (let value of arguments)
total += value;
return total;
}
console.log(sum(1, 2, 3, 4, 5, 10));
rest operator (don’t confuse with spread)
this does the same thing as the arguments code above.
rest allows you to have an indefinite number of arguments.
function sum(...args) {
args.reduce((a, b) => a + b);
}
console.log(sum(1, 2, 3, 4, 5, 10));
let’s use it practically. shopping cart example.
function sum(discount, ...prices) {
const total = prices.reduce((a, b) => a + b);
return total * (1 - discount);
}
console.log(sum(1, 2, 3, 4, 5, 10));
default paremeters
function interest(principal, rate = 3.5, years = 5) {
return principal * rate / 100 * years
}
console.log(interest(10000,));
once giving a parameter a default value, you must give all parameters after that a default value or else you will get an error.
getters and setters
const person = {
firstName: 'Micah',
lastName: 'Raybuck'
get fullName() {
return `${person.firstName} ${person.lastName}`;
},
set fullName(value) {
const parts value.split(' ')
this.firstName = parts[0];
this.lastName = parts[1];
}
};
person.fullName = 'John Smith';
console.log(person);
// getters => access properties
// setters => change (mutate) them
*ask Drew about this because this seems really impractical. maybe not impractical but slightly confusing.
try and catch
const person = {
firstName: 'Micah',
lastName: 'Raybuck'
set fullName(value) {
if (typeof value !== 'string')
throw new Error('Value is not a string.');
const parts value.split(' ')
if (parts.length !== 2)
throw.new Error('Enter and first and last name.');
this.firstName = parts[0];
this.lastName = parts[1];
}
};
try {
person.fullName = '';
}
catch(e) {
alert(e);
}
console.log(person);
scope, local vs global
{
const message = 'hi';
}
console.log(message);
function start() {
const message = 'hi';
}
function stop() {
const message = 'bye';
}
start();
scope determines where the variable or constant is accessible.
local constants are inside a funciton’s block. local constants are prioritized over global. USE LOCAL USUALLY.
let vs var
function start() {
for (var i = 0; i < 5; i++) {
if (true) {
var color = 'red';
}
}
console.log(color);
}
start();
var color = 'red';
let age = 30;
var is limited to the function in which it’s defined rather than the block, so it’s not great to use. aka, var is function scope, not block scope like let.
“this” represents the object that is executing the current function.
const video = {
title: 'a';
play() {
console.log(this); // this references the video object
}
};
video.stop = function() {
console.log(this);
};
video.stop();
const video = {
title: 'a';
play() {
console.log(this); // this references the video object
}
};
function Video(title) {
this.title = title;
console.log(this);
}
const v = new Video('b');
clean it up.
const video = {
title: 'a';
tags ['a', 'b', 'c'],
showTags () {
this.tags.forEach(function(tag) {
console.log(this, tag);
}, this);
}
};
video.showTags();
changing this
const video = {
title: 'a';
tags ['a', 'b', 'c'],
showTags () {
this.tags.forEach(tag) => {
console.log(this.title, tag);
});
}
};
// separate codes.
function playVideo(a, b) {
console.log(this);
}
playVideo.call({ name 'Micah'}, 1, 2);
playVideo.apply({ name 'Micah'}, [1, 2]);
const. fn = play.Video.bind({name: 'Micah'});
fn();
playVideo();
we can use “self” instead of “this”
call and apply have little differences, but the main one being passing arguments.
in apply, you have to pass additional arguments as an array [].
bind doesn’t call to the function, it returns a new function that points to the object permanently, binding it no matter what.
Object Oriented Programming (OOP)
a style of programming that is centered around objects rather than functions
the fewer the parameters, the better
4 pillars
encapsulation is grouping related variables and functions operating on them and turn them into objects.
abstraction hides the complexities of the code and gives it a simpler interface. also reduces impact of change.
inheritance allows you to eliminate redundant code.
polymorphism allows you to refactor ugly switch/case statements.
The DOM
The document object model (DOM) is basically a way or organizing the hierarchy of a document. Parent/child relationships
https://www.w3schools.com/jsref/prop_style_background.asp
Separation of Concerns
HTML is for content only. CSS is there to style the website. JavaScript is for behavior.
SUMMARY CHEAT SHEET
// The simplest way to create an object is using an object literal
const circle = {
radius: 1,
draw: function() {}
};
// To create multiple objects with the same structure and behaviuor (methods), use a factory or a constructor.
// Factory function
function createCircle(radius) {
return {
radius,
draw: function() {}
}
}
// Constructor function
function Circle(radius) {
this.radius = radius;
this.draw = function() {}
}
// Every object has a "constructor" property which returns the function that was used to construct or create that object.
const x = {};
x.constructor; // returns Object()
// In JavaScript, functions are objects. They have properties and methods.
Circle.name;
Circle.length;
Circle.constructor; // returns Function()
Circle.call({}, 1); // to call the Circle function
Circle.apply({}, [1]);
// Value types are copied by their value, reference types are copied by their reference.
// Value types in JavaScript are: String, Number, Boolean, Symbol, undefined and null
// Reference types are: Object, Function and Array
// JavaScript objects are dynamic. You can add/remove properties:
circle.location = {};
circle['location'] = {};
delete circle.location;
// To enumerate the members in an object:
for (let key in circle) console.log(key, circle[key]);
Object.keys(circle);
// To see if an object has a given property
if ('location' in circle)
// Abstraction means hiding the complexity/details and showing only the essentials.
// We can hide the details by using private members. Replace "this" with "let".
function Circle(radius) {
// Public member
this.radius = radius;
// Private member
let defaultLocation = {};
}
// To define a getter/setter, use Object.defineProperty():
Object.defineProperty(this, 'defaultLocation', {
get: function() { return defaultLocation; },
set: function(value) { defaultLocation = value; }
});
Leave a Reply