Skip to content

Instantly share code, notes, and snippets.

@fuzzylimes
Last active May 9, 2018 21:19
Show Gist options
  • Save fuzzylimes/0aead1d9eb412290a45db8a14ea066ed to your computer and use it in GitHub Desktop.
Save fuzzylimes/0aead1d9eb412290a45db8a14ea066ed to your computer and use it in GitHub Desktop.
Javascript Notes

Javascript Notes

Basics

Notes

  • No issue using either single ' or double " quotes, it's all preference/styling

Loging to console

console.log('hello world!');
console.log(123);
console.log(true);
var greeting = 'Hello');
console.log(greeting);
console.log([1,2,3,4]);
console.log({a:1, b:2})
console.table({a:1, b:2})

console.error('This is some error')
console.clear();
console.warn('This is a warning');
console.time('Hello'); // Time it takes to reach start to end of section
  console.log('hi');
  console.log('hi');
  console.log('hi');
  console.log('hi');
console.timeEnd('Hello');

Comments

// Single Line Comment

/*
Multi
Line
Comment
*/

Defining Variables

  • var - basic javascript variable that's been around since the beinging
  • const - used to define a constant that cannot be changed
  • let - new way of assigning a variable, good for scoping
var
var name = 'John Doe';
console.log(name);
name = 'Steve Smith';
console.log(name);

// Init var
var greeting;
console.log(greeting);
greeting = 'Hello';
console.log(greeting);

// Can only contain letters, numbers, _, $
// Can not start with a number
var name = 'John';

// leading with $ usually reserved to working with jquery
// leading with _ usually reserved to private variables
// just be safe and start with a letter

// Multi word vars
var firstName = 'John'; // Camel case, used for most variables
var first_name = 'Sara'; // Underscore
var FirstName = 'Tom'; // Pascal case, usually used with classes and objects
var firstname;
let
  • works identical to var on the global level
let name = 'John Doe';
console.log(name);
name = 'Steve Smith';
console.log(name);

let fruit;
const
  • value cannot be reassigned
  • can not be initialized as empty (must have value)
  • If set to object, values in object can be changed, but not the object itself.
const name = 'John';
// name = 'Sara';

// Cannot init empty
// const greeting;

const person = {
    name: 'John',
    age: 30
}

person.name = 'Sara';
person.set = 'F';
//person = 'Bob';

console.log(person);

const numbers = [1,2,3,4,5];
numbers.push(6);
// numbers = [1,2,3,4,5,6,7];
console.log(numbers);

Data Types

Background

  • Primitive
    • data is stored directly in the location that the variable acesses
    • stored on the statck
  • Reference
    • accessed by reference
    • objects that are stored on the heap
    • a pointer to a location in memory

Primitive Types

  • String - strings of characters
  • Number - ints, floats, doubles
  • Boolean - true/false
  • Null - intentionally null
  • Undefined - no value (value not assigned)
  • Symbols (ES6)

Reference Types

  • Arrays
  • Object Literals
  • Functions
  • Dates
  • Anything else

Examples

Primitive

String
const name = 'John Doe';
console.log(typeof name);
Number
const age = 45;
console.log(typeof age);
Boolean
const hasKids = true;
console.log(typeof hasKids);
Null
const car = null;
console.log(typeof car); // Incorrectly returns type of Object (early JS bug)
Undefined
let test;
console.log(typeof test);
Symbol
const sym = Symbol();
console.log(typeof sym);

Reference - Objects

Array
const hobbies = ['movies', 'music'];
console.log(typeof hobbies);
Object literal
const address = {
    city: 'Boston',
    state: 'MA'
}
console.log(typeof address);
Date
const today = new Date();
console.log(typeof today);

Type Conversions

Number to String

let val;
val = 5;

console.log(val); // 5
console.log(typeof val); // number
console.log(val.length); // undefined - only works on strings!
console.log(String(val)); // Convert number to string

val = string(4+4)
console.log(val); // '8'
console.log(typeof val); // string

Boolean to String

let val
val = String(true);
console.log(val); // 'true'
console.log(typeof val); // string

Date to String

let val
val = String(new Date());
console.log(val); // 'Date'
console.log(typeof val); // string

Array to String

let val
val = String([1,2,3,4]);
console.log(val); // '1,2,3,4'
console.log(typeof val); // string

toString()

let val
val = (5).toString();
val = (true).toString();

String to Number

let val
val = '5';
val = Number(val);
val = Number(true); // 1
val = Number(false); // 0
val = Number(null); // 0
val = Number('hello'); // NaN - Not a number
val = Number([1,2,3]); // NAN

console.log(val.toFixed(2)); // Returns number to two decimal places

parseInt

let val
val = parseInt('100'); // val = 100
val = parseInt('100.34'); // val = 100

parseFloat

let val
val = parseInt('100.34'); // val = 100.34

Numbers/Math

const num1 = 100;
const num2 = 50;
let val;

// simple math with numbers
val = num1 + num2; // 150
val = num1 * num2; // 5000
val = num1 - num2; // 50
val = num1 / num2; // 2
val = num1 % num2; // 0

// math object
val = Math.PI;
val = Math.E;
val = Math.round(2.8); // round to 3
val = Math.round(2.4); // round to 2
val = Math.ceil(2.4); // 3
val = Math.floor(2.8); // 2
val = Math.sqrt(64); // 8
val = Math.abs(-3); // 3
val = Math.pow(8,2); //64
val = Math.min(2,33,45,34,26); // 2
val = Math.max(2,33,45,34,26); // 45
val = Math.random(); // random number 0-1
val = Math.random() * 20; // random number 0-19
val = Math.floor(Math.random() * 20 + 1); // random int 1-20

Strings

const firstName = 'William';
const lastName = 'Johnson';
const age = 30;
const str = 'Hello my name is Brad';
const tags = 'web design,webdevelopment,programming';
let val;

val = firstName + lastName; // WilliamJohnson

// Concat
val = firstName + ' ' + lastName;
// Append
val = 'Brad ';
val += 'Traversy';
val = 'Hello, my name is ' + firstName + ' and I am ' + age;
// Escaping
val = 'That\'s aswesome, I can\'t wait';
// Length
val = firstName.length; // don't need parens, property not method
// concat()
val = firstName.concat(' ', lastName); // William Johnson
// Change case
val = firstname.toUpperCase(); // WILLIAM
val = lastName.toLowerCase(); // johnson
// Get character at position
val = firstName[2];
// indexOf()
val = firstName.indexOf('l'); // 2
val = firstName.lastIndexOf('l'); // 3
// charAt()
val = firstName.charAt('2'); // l
// Get last char
val = firstName.charAt(firstname.length -1); // m
// substring()
val = firstName.substring(0, 4); // Will
// slice()
val = firstname.slice(0,4); // Will
val = firstname.slice(-3); // iam
// split()
val = str.split(' '); // ['Hello', 'my', 'name', 'is', 'Brad']
val = tags.split(','); // ['web design','web development','programming']
// replace()
val = str.replace('Brad', 'Jack');
// includes() - returns bool if item is present in string
val = str.includes('Hello'); // true
val = str.includes('Foo'); // false

Template Literals

const name = 'John';
const age = 31;
const job = 'Web Developer';
const city = 'Miami';
let html;

// Without template strings (es5)
html = '<ul><li>Name: ' + name + '</li><li>Age: '+ age + '</li><li>Job: ' + job + '</li><li>City: ' + city + '</li></ul>';

html = '<ul>' +
       '<li>Name: ' + name + '</li>' +
       '<li>Age: ' + age + '</li>' +
       '<li>Job: ' + job + '</li>' +
       '<li>City: ' + city + '</li>' +
       '</ul>';

// With template strings (es6)
function hello() {
    return 'hello';
}

html = `
  <ul>
    <li>Name: ${name}</li>
    <li>Age: ${age}</li>
    <li>Job: ${job}</li>
    <li>City: ${city}</li>
    <li>${2 + 2}</li>
    <li>${hello()}</li>
    <li>${age > 30 ? 'Over 30' : 'Under 30'}</li>
  </ul>
`;

document.body.innerHtml = html;

Arrays and Array Methods

const numbers = [43, 56, 33, 23, 44, 36, 5];
const number2 = new Array(22, 45, 33, 76, 54);
const fruit = ['Apple', 'Banana', 'Orange', 'Pear'];
const mixed = [22, 'Hello', true, undefined, null, {a:1, b:1}, new Date()]; // can hold any type
let val;

// Get array length
val = numbers.length; // 7
// Check if is array
val = Array.isArray(numbers); // true
val = Array.isArray("string"); // false
// Get single value
val = numbers[3]; // 23
val = numbers[0]; // 43
// Insert into array
numbers[2] = 100;
// Find index of value
val = numbers.indexOf(36); // 5
// Mutating arrays
numbers.push(250); // append to end of array
numbers.unshift(120); // prepend to start of array
numbers.pop(); // pop item from end
numbers.shift(); // remove item from start
// splice()
numbers.splice(1,1); // position to start, and end removal
numbers.splice(1,3); // removes 56, 33, 23
// reverse()
numbers.reverse(); // returns array in reverse order
// Concat array
val = numbers.concat(numbers2); // array with both values in it
// sort()
val = fruit.sort(); // sorted alphabetically
val = numbers.sort(); // sorts by first number, not what you want
// use "compare function"
val = numbers.sort(function(x,y){
    return x - y;
});
// reverse sort
val = numbers.sort(function(x,y){
    return y - x;
});
// find() - takes in a function for searching
function under50(num){
    return num < 50;
}
val = numbers.find(under50); // iterates over items in list, passing value to function. Returns the first that satisfies function.

console.log(numbers);
console.log(val);

Object Literals

const person = {
    firstname: 'Steve',
    lastName: 'Smith',
    Age: 30,
    email: 'steve@aol.com',
    hobbies: ['music', 'sports'],
    address: {
        city: 'Miami',
        state: 'FL'
    },
    getBirthYear: function() {
        return 2017 - this.age; // need to use this to make it local to the object
    }
}
let val;

val = person;
// Get specific value
val = person.firstName; // 'Steve'
val = person['lastName'];
val = person.age; // 30
val = person.hobbies[1]; // sports
val = person.address.state; // FL
val = person['address']['city']; // Miami
val = person.getBirthYear(); // 1987

console.log();

// Array of objects
const people = [
    {name: 'John', age: 30},
    {name: 'Mike'}, age: 23},
    {name: 'Jane'}, age: 32}
];

for(let i = 0; i < people.length; i++){
    console.log(people[i].name);
}

Date and Times

let val;
const today = new Date(); // Current date/time
let birthday = new Date('9-10-1981 11:25:00');
birthday = new Date('September 10 1981');
birthday = new Date('9/10/1981');

val = today;
console.log(typeof val); // Date
val = birthday; // 

val = today.getMonth(); // numerical representation of month
val = today.getDate(); // numerical representation of date
val = today.getDay(); // numerical representation of day of week
val = today.getFullYear(); // year
val = today.getHours(); // hours
val = today.getMinutes(); // minute of hour
val = today.getSeconds(); // seconds of hour
val = today.getMilliseconds(); // milliseconds of hour
val = today.getTime(); // epoch time

birthday.setMonth(2); // March 10th
birthday.setDate(12); // March 12th
birthday.setFullYear(1985); // March 12th 1985
birthday.setHours(3);
birthday.setMinutes(30);
birthday.setSeconds(25);

console.log(val);

If Statemenets and comparison operators

const id = 100;

// Equal to
if(id == 100){
    console.log('CORRECT');
} else {
    console.log('INCORRECT');
}

// Not Equal to
if(id != 101){
    console.log('CORRECT');
} else {
    console.log('INCORRECT');
}

// equal to value & type
if(id === '100'){
    console.log('CORRECT');
} else {
    console.log('INCORRECT');
}

// not equal to value & type
if(id !== '100'){
    console.log('CORRECT');
} else {
    console.log('INCORRECT');
}

// Test if undefined
if(typeof id !== undefined){
    console.log(`The ID is ${id}`);
} else {
    console.log('NO ID');
}

// Greater or less than
if(id > 200){
    console.log('CORRECT');
} else {
    console.log('INCORRECT');
}

// if else
const color = 'red';

if(color === 'red'){
    console.log('Color is red');
} else if(color === 'blue'){
    console.log('Color is blue');
} else {
    console.log('Color is not red or blue');
}

// Logical Operators
const name = 'Steve';
const age = 20;

// And &&
if(age > 0 && age < 12) {
    console.log(`${name} is a child`);
} else if(age >= && age <= 19){
    console.log(`${name} is a teenager`);
} else {
    console.log(`${name} is an adult`);
}

// Or ||
if(age < 16 || age > 65){
    console.log(`${name} can not run in race`);
} else {
    console.log(`${name} is registered for the race`);
}

// Ternary operator
console.log(id === 100 ? 'Correct': 'Incorrect');

// without braces
if(id === 100)
  console.log('Correct');
else
  console.log('Incorrect');

Switches

const color = 'red';

switch(color){
    case 'red':
      console.log('Color is red');
      break;
    case 'blue':
      console.log('Color is blue');
      break;
    default:
      console.log('Color is not red or blue');
      break;
}

let day;
switch(new Date().getDay()){
    case 0:
        day = 'Sunday';
        break
    case 1:
        day = 'Monday';
        break
    case 2:
        day = 'Tuesday';
        break
    case 3:
        day = 'Wednesday';
        break
    case 4:
        day = 'Thursday';
        break
    case 5:
        day = 'Friday';
        break
    case 6:
        day = 'Saturday';
        break
}
console.log(`Today is ${day}`);

Functions expressions and Declarations

// declarations
function greet(){
    //console.log('Hello');
    return 'Hello';
}
console.log(greet());

// pass in arguements
function greet(firstName, lastName){
    //console.log('Hello');
    return 'Hello ' + firstName + ' ' + lastName;
}
console.log(greet('John', 'Doe'));

// default parameters in es5
function greet(firstName, lastName){
    if(typeof firstName === 'undefined'){firstName = 'John'}
    if(typeof lastName === 'undefined'){lastName = 'Doe'}
    return 'Hello ' + firstName + ' ' + lastName;
}
console.log(greet());

// default parameters in es6
function greet(firstName = 'John', lastName = 'Doe'){
    return 'Hello ' + firstName + ' ' + lastName;
}
console.log(greet());

// function expressions - putting a function as a variable assignment
const square = function(x = 3){
    return x*x;
};
console.log(square(8));

// Immidiately invokable function expressions - IIFEs
// Function runs as soon as declared
(function()){
    console.log('IFFE Ran...');
})();

// with parameters
(function(name)){
    console.log('Hello ' + name);
})('Brad');

// Property Methods
const todo = {
    add: function(){
        console.log('Add todo..');
    },
    edit: function(id){
        console.log(`Edit todo ${id}`);
    }
}
todo.delete = function(id){
    console.log(`Delete todo ${id}`);
}
todo.add();
todo.edit(22);
todo.delete(22);

Loops and itterations

Loops

// For loop
for(let i = 0; i < 10; i++){
    console.log(i);
}

// continue and break
for(let i = 0; i < 10; i++){
    if(i === 2){
        console.log('2 is my favorite number');
        continue; // Goes to next itteration without continuing
    }

    if(i === 5){
        console.log('Stop the loop');
        break; // kills the loop
    }

    console.log('Number ' + i);
}

// While loop
let i = 0;
while(i < 10){
    console.log(`Number ${i}`);
    i++;
}

// Do while - always runs at least once
let i = 0;
do {
    console.log(`Number ${i}`);
    i++;
} while (i < 10 );

// Looping through arrays
const cars = ['Ford', 'Chevy', 'Honda', 'Toyota'];
for(let i = 0; i < cars.length; i++){
    console.log(cars[i]);
}

// forEach array loop
const cars = ['Ford', 'Chevy', 'Honda', 'Toyota'];
cars.forEach(function(car){
    console.log(car);
});

// forEach extra parameters
const cars = ['Ford', 'Chevy', 'Honda', 'Toyota'];
cars.forEach(function(car, index, array){
    console.log(`${index}: ${car}`);
    console.log(array;)
});

// Map - create an array based on specified parameters
const users = [
    {id:1, name: 'John'},
    {id:2, name: 'Sarah'},
    {id:3, name: 'Karen'}
];
const ids = users.map(function(user){
    return user.id;
});
console.log(ids); // [1, 2, 3]

// For in loop (used with objects)
const user = {
    firstName: 'John',
    lastName: 'Doe',
    age: 40
}

for(let x in user){  // will set the key of each value in user to x
    console.log(x);
    console.log(`${x}: ${user[x]}`)
}

Window Methods, Objects, Properties

// Alert
window.alert('hello world');

// Prompt - pop up with text box
const input = prompt();
alert(input);

// Confirm - pop up confirmation box
if(confirm('Are you sure?')){
    console.log('YES');
} else {  // If cancel selected...
    console.log('NO');
}

// Outter height and width
let val;
val = window.outerHeight;
val = window.outerWidth;

// Inner height and width
let val;
val = window.innerHeight;
val = window.innerWidth;

// Scroll points - where the scroll bar is at
let val;
val = window.scrollY;
val = window.scrollX;

// Location Object - page information
let val;
val = window.location;
val = window.location.hostname;
val = window.location.port;
val = window.location.href
val = window.location.search;

// Redirect
window.location.href = 'http://google.com';

// Reload
window.location.reload();

// Hisotry Object
window.history.go(-1); // Goes back to last history by index
val = window.history.length;

// Navigator Object
val = window.navigator;
val = window.navigator.appName;
val = window.navigator.appVersion;
val = window.navigator.userAgent;
val = window.navigator.platform;
val = window.navigator.vendor;
val = window.navigator.language;

Scope

// Global Scope
var a = 1;
let b = 2;
const c = 3;

function test(){
    var a = 4;
    let b = 5;
    const c = 6;
    console.log('Function Scope: ', a, b, c);
}

test();

// Block scope
if(true){
    var a = 4; // global a will be overritten by this line. var is weird, and is always global
    let b = 5;
    const c = 6;
    console.log('Function Scope: ', a, b, c);
}

for(let a = 0; a < 10; a++){
    console.log(`Loop: ${a}`);
}

console.log('Global Scope: ', a, b, c);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment