Skip to content

Instantly share code, notes, and snippets.

@technoglot
Last active April 28, 2019 04:12
Show Gist options
  • Save technoglot/ae490be3a4e790037ac91828050074ec to your computer and use it in GitHub Desktop.
Save technoglot/ae490be3a4e790037ac91828050074ec to your computer and use it in GitHub Desktop.
Simple introduction to JavaScript ES6 with code examples
// this is an in-line comment

/*
this 
is
a
multi-line
comment
*/

// creating variables, 3 ways: var, let, const
var greet = 'hello world!'; // string with single quotes
let greet1 = "hello world, again!"; // string with double quotes
const greet2 = `hello world, yet again!`; // string with back ticks

// printing to console
console.log(greet);
console.log(greet1);
console.log(greet2);

// creating a function
function test() {
//in JS, arrays can contain different types of elements 
  const i = [ 'Hello' , 56, function t() { console.log('Wow') }]
  	return i[2]() // retrieves element in array at index position 2 and calls the method right away using '()'
}

// function call and printing to the console
console.log(test())

/*for loop*/
const beaches = ['Cas Abou', 'Jeremi', 'Kenepa']

for (let i = 0; i < beaches.length; i++) {
  console.log('Beach [' + i + ']: ' + beaches[i])
}

/*Creating objects in JavaScript*/

// Method 1
const student = new Object()
student.age = 20
student["address"] = 'Gosieweg'
console.log(student)

// Method 2
const employee = {}
	employee.firstName = 'John'
	employee["lastName"] = 'Marcha'
	employee.isActive = true
	employee.salary = function() {
	  return 160*25
	}
	employee["5"] = 5 // allowed
	// employee.5 = 5 // not allowed
	employee["streetName"] = 'Rooseveltweg'
	employee.address = {
	  streetName: 'Jan Noorduynweg',
	  houseNumber: 5,
	  country: 'Curacao'
	}
	const key = "age"
	employee[key] = 34

console.log('Employee first name: ' + employee.firstName + ' ' + employee.lastName)
//console.log('Employee 5 property: ' + employee.5) // not allowed

console.log('Employee address: ' + employee.address['streetName'] + ' ' + employee.address.houseNumber)

console.log('Employee age: ' + employee.age)

// Method 3
const teacher = {
  age: 34,
  name: 'Pete',
  address: {
  streetName: 'Caracasbaaiweg',
  houseNumber: 5,
  country: 'Curacao'
  },
}

console.log(teacher)

let x = 'Hello'
x = 45

console.log('Value of x overridden: ' + x)

if ( typeof teacher === 'object' ) {
  console.log('teacher is of type object!')
}

const testTypeOfForFunction = [ 
  'Hello' , 
  56, 
  function t() { 
    console.log('Only executed this function in the loop!') 
  },
  false
]

for ( let i = 0; i < testTypeOfForFunction.length; i++ ) {
  
  console.log('Current index tested: ' + i)
  
  if ( typeof testTypeOfForFunction[i] === 'function' ) { // if current index in array includes a function, then execute it
    testTypeOfForFunction[i]()
  } else {
    console.log(testTypeOfForFunction[i]) // otherwise just print the index value
  }
}
// anonymous assigned to constant average
const average = function() {
  return (1+2+3+4+5+6) / 6;
}

console.log('Average:', average())

// function within function
function a() {
  var c = 5;
  let e = 6;
  
  function b() {
    console.log(c)
  }
  return b
}
const d = a()
console.log('')
console.log(d)
console.log(d())

// function returning options tomorrow and yesterday
function example() {
  return {
    tomorrow: function() { 
      const date = new Date()
      date.setDate(date.getDate()+1)
      return date
    },
    yesterday: function() { 
      const date = new Date()
      date.setDate(date.getDate()-1)
      return date
    }
  }
}

console.log('')
const t = example()
console.log('Tomorrow:', t.tomorrow())
console.log('Yesterday:', t.yesterday())

// iife using previous function () {
const showDates = (function() {
  return {
    tomorrow: function() { 
      const date = new Date()
      date.setDate(date.getDate()+1)
      return date
    },
    yesterday: function() { 
      const date = new Date()
      date.setDate(date.getDate()-1)
      return date
    }
  }
})()

console.log('')
console.log('iffe: tomorrow:', showDates.tomorrow())
console.log('iffe: yesterday:', showDates.yesterday())
// Creating objects in JavaScript

// Method 1
const o = new Object()
	o.firstName = 'Pierre';
	o.lastName = 'Lopez';
	o.isTeaching = true
	o.greet = function () {
	  console.log('Hi')
	}

// Method 2
const o2 = {}
	o2.firstName = 'John'
	o2['lastName'] = 'Johnson'
	const key = 'isTeaching'
	o2[key] = true
	o2['greet'] = function() {
	  console.log('Hi2')
	}

// Method 3
const o3 = {
  firstName: 'Tommy',
  lastName: 'Wilson',
  isTeaching: true,
  greet: function() {
    console.log('Hi3')
  },
  address: {
    number: 123,
    street: 'Testweg'
  }
}
console.log(o3.address.street);
function makeFunctionArray() {
  const arr = []
  
  for ( var i = 0; i < 5; i++ ) {
    arr.push(function() { console.log(i) })
  }
  
  return arr
}

const functionArray = makeFunctionArray()
functionArray[0]()
// overflow
function recurse() {
  console.log('recursion!')
  return recurse()
}

recurse()
// immediately invoked function expression
const sayHello = (function () {
  var message = 'Hello!'
  
  function sayHello() {
    console.log(message)
  }
  
  return sayHello
})()

console.log('typeof message: ', typeof message)
console.log(sayHello.toString())
sayHello()
var thisIsAVar = 51
thisIsAVar = 50
var thisIsAVar = 'Hello'
a = 300

//console.log('a: ' + a)
//console.log('b: ' + b)
console.log(typeof null)

//console.log(thisIsHoisted)
//let thisIsALet = 61
//thisIsALet = 60
//let thisIsALet = 'World!'
//const thisIsAConst = 90
//thisIsAConst = 91


function thisIsHoisted() {
  console.log('This is a function declared at the bottom of a file')
}

var thisIsHoisted = function() {
  console.log('Should this be hoisted?')
}

var a = 100
let b = 200
function map(arr, fn) {
  const newArr = []
  
  for ( let i = 0; i < arr.length; i++ ) {
    let val = arr[i]
    newArr.push(fn(val))
  }
  
  return newArr;
}

function addOne(num) { 
  return num + 1 
}

const myArray = [1, 2, 3, 4, 5]
console.log(map(myArray, addOne))
function hang(seconds) {
  const doneAt = Date.now() + (seconds * 1000)
  
  while ( Date.now() < doneAt ) {}
}

hang(10)
console.log('hello')
// Let's create a Set class
// data structure that does not allow duplicate elements
class Set {

	constructor(arr) { // new Set([1,2,3,4,5])
		this.arr = arr
	}
	
	add(val) {
		if ( !this.has(val) ) {
		this.arr.push(val)
		}
	}
	
	delete(val) {
		this.arr = this.arr.filter(x => x !== val)
	}
	
	has(val) {
		return this.arr.includes(val)
	}
	
	get size() {
		return this.arr.length
	}
}

const myArray = new Set([1,2,3,4,5])
console.log(`My array's size before is: ${myArray.size}`)

myArray.add(5)
myArray.add(4)
console.log(`My array's size after is: ${myArray.size}`)

myArray.add(6)
console.log(`My array's size after is: ${myArray.size}`)
console.log(`My array's has value 6: ${myArray.has(6)}`)

myArray.delete(6)
console.log(`My array's size after delete is: ${myArray.size}`)
console.log(`My array's has value 6: ${myArray.has(6)}`)
class MySet extends Set {
	constructor(arr) {
		super(arr)
		this.originalArray = arr // backup [4,5,6,7,8,9]
	}
	
	reset() {
		return new MySet(this.originalArray)
	}
}

let mySet = new MySet([4,5,6,7,8,9])
console.log(`My set's size before is: ${mySet.size}`)

mySet.add(10)
mySet.add(100)
console.log(`My set's size after is: ${mySet.size}`)

mySet = mySet.reset()
console.log(`My set's size after reset is: ${mySet.size}`)
const statelessSumOld = function(a, b) {
	return a+b
}

const statelessSumNewOne = (a, b) => {
	return a+b
}

const statelessSumNewTwo = (a, b) => a+b

const bla = function(c) {
	return c++
}

const aNew = (c) => {
	return c++
}

const aNewTwo = c => c++
let a = 0

const statefulSum = () => a++

console.log(statelessSumOld(3,5))
console.log(statelessSumNewOne(3,5))
console.log(statelessSumNewTwo(3,5))
console.log(statefulSum())
console.log(statefulSum())

const calculate = function(c, d) {
	return c*d
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment