javascript Closure IIFE Immediately Invoked Function

Javascript Closure

This is an example of how to use iffe closure example to avoid collisions with other global variables in your programs. By placing the variable in the function it makes it private and not accessible everywhere else that would create a problem.

// global variable bad because of collisions
// break other programs avoid globals
var names = ['zero', 'one', 'two', 'three', 'four', 'five'];

var digit_name = function (n) {
	return names[n];
}

console.log(digit_name(3)) // 'three'

// SLOW - because we have to create an variable array every time you try invoking it.
// prevents collision of global variables - names
var digit_name = function (n) {
	var names = ['zero', 'one', 'two', 'three', 'four', 'five'];
	return names[n];
}

console.log(digit_name(3)) // 'three'

// closure iife - immediate invoked function 
// it executes the function has access to the variable names in the iffy
var digit_name = (function () {
	var names = ['zero', 'one', 'two', 'three', 'four', 'five'];
	return function (n) {
		return names[n];
	}
})();

console.log(digit_name(3)) // 'three'

 

The third way to do this is the best. To avoid collisions.

Power Constructors

  1. Make an object
    • Object Lateral
    • new
    • Object.create
    • call another power constructor
  2. Define some some variables and functions
    • These become private members
  3. Augment the object with privileged methods.
  4. Return the object
function myPowerConstructor(x) {
	var that = otherMaker(x);
	var secret = f(x);
	that.priv = function () {
		//secret x that
	};
	return that;
}

 

Functional Inheritance

function gizmo(id) {
	return {
		id: id,
		toString: function () {
			return "gizmo " + this.id;
		}
	};
}

function hoozit(id) {
	var that = gizmo(id);
	that.test = function (testid) {
		return testid === this.id;
	};
	return that;
}

Source:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
https://en.wikipedia.org/wiki/Immediately-invoked_function_expression

Javascript – Simple For Loop Examples

These are some examples of simple for loop challenges and exercises I did for fun.

// Print 'hello' the string vertically
var str = 'hello';
for(var count = 0; count < str.length; count++) {
	console.log(str[i])
}
// print all numbers between -10 and 19

for(var i = -10; i < 20; i++) {
	console.log(i)
}

// print even numbers between 10 and 40

for(var i = 10; i < 40; i++) {
	if(i % 2 === 0){
	console.log(i)
	}
}
// print all odd numbers between 300 and 333
for(var i = 300; i < 333; i++) {
	if(i % 3 === 0){
	console.log(i)
	}
}
// print all numbers divisible by 5 and 3 between 5 and 50
for(var i = 5; i < 50; i++)	{
	if(i % 3 === 0 && i % 5 === 0) {
	console.log(i)
	}
}

How to Setup Babel es2015 Javascript on Windows 8.1?

First create a folder:
Then CD into that folder through CMD
Then do the follow in command-line

npm init
npm install -g babel-cli
npm install babel-preset-es2015–save-dev

Then create app.js.es6 file

Then use this example code:

class Person {
	constructor(name) {
		this.name = name;
	}
	greet(){
		return "Hello I am ${this.name}";
	}
}

let person = new Person("Tyler");
console.log(person.greet());

babel app.js.es6 –presets2015 | clip

Clip copies the string from commandline. Then you should get the follow code output:

"use strict";

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Person = (function () {
	function Person(name) {
		_classCallCheck(this, Person);

		this.name = name;
	}

	_createClass(Person, [{
		key: "greet",
		value: function greet() {
			return "Hello I am ${this.name}";
		}
	}]);

	return Person;
})();

var person = new Person("Tyler");
console.log(person.greet());

Now we want to create an index.html file

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title></title>
</head>
<body>
	<h2>ES2015</h2>

	<script src="app.js"></script>
</body>
</html>

babel app.js.es6 –presets es2015 > 5

Now we are going to create a file called .bablrc this file will shorten the command to compile the babel file

{
	presets: ["es2015"]
}

Next we type in this code to make compiling es2015 javascript faster.

babel app.js.es6 > app.js

babel_CMD_setup

https://github.com/JasonDeving/babel2015windowssetup

How to Benchmark Your Javascript?

This is a quick tutorial on how to benchmark your javascript with console.time(“arg”) and console.timeEnd(“arg”)
You would use developer tools to see how fast your script runs.
javascript_benchmark

Example Code:

Array.prototype.proto1 = function(){};
Array.prototype.proto2 = function(){};
Array.prototype.proto3 = function(){};
Array.prototype.proto4 = function(){};
Array.prototype.proto5 = function(){};

var objectLateral = {
  arrayBank: ['Some random string', 'Other String', 'More Stringy Spaghetti']
};

function runThisCode(){
  var things = objectLateral.arrayBank,
      list = "";
	console.time("time");  

  for(var i = 0, ff = things.length; i < ff; i++){
    list += (things[i] + " ");
  }

  console.timeEnd("time");
  return list.trim();
}

runThisCode();

Javascript – Magic 8 Ball Script

This is a magic 8 ball program written in html and javascript. So it’s very lean fast and quick. You are free to use this script because it’s open source I made this solely for fun. So fork it. This is basically a random answer generator which uses random number and switch statement to be written. Have fun. 😉

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Magic 8 ball</title>
</head>
<body>
	<input type="text" placeholder="Ask your question?">
	<button onclick="myFunction()">Answer</button>
	<p id="demo"></p>

	<script>
function myFunction() {
	function getRandomArbitrary(min, max) {
	return Math.floor(Math.random() * (max - min) + min);
	}
	var num = getRandomArbitrary(1,6);

	switch(num) {
	    case 1:
	        answer = "Yes";
	        break;
	    case 2:
	        answer = "No";
	        break;
	    case 3:
	        answer = "Try Again";
	        break;
	    case 4:
	        answer = "Outlook not so good";
	        break;
	    case 5:
	        answer = "Most definitely!";
	        break;
	}
	document.getElementById("demo").innerHTML = answer;
}
	</script>
</body>
</html>

 

Magic 8 Ball Demo

Building a Calculator With Angular Js

index.html

Angular js Simple Calculator Example Code

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-example68-production</title>
  

  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
  

  
</head>
<body ng-app="">
  First Num<input type="number" ng-model="number1">
Second Num<input type="number" ng-model="number2">
  <button ng-click="count = count + number1" ng-init="count=0">
  Add
</button>
<button ng-click="count = count - number2" ng-init="count=0">
  Subtract
</button>
<button ng-click="count = count * number2" ng-init="count=0">
  multiply
</button>
<button ng-click="count = count / number2" ng-init="count=0">
  divide
</button>
<button ng-click="count = 0" ng-init="count=0">
  clear
</button>
<span>
  count: {{count}}
</span>
</body>
</html>

app.js

it('should check ng-click', function() {
  expect(element(by.binding('count')).getText()).toMatch('0');
  element(by.css('button')).click();
  expect(element(by.binding('count')).getText()).toMatch('1');
});

Gulp To Create One Javascript File to Speed Up Your Production Server

First install node.js
Type this in commandline

npm install gulp
npm install gulp-concat –save-dev
npm install gulp-uglify –save-dev
npm install gulp-rename –save-dev

'use strick';

var gulp = require('gulp'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    rename = require('gulp-rename');

gulp.task("concatScripts", function(){
	//combine all these scripts
	gulp.src([
		'js/jquery.js', 
		'js/sticky/jquery.stick.js', 
		'js/main.js'])
	//create file
	.pipe(concat("app.js"))
	// put in folder destination
	.pipe(gulp.dest("js"));

});

gulp.task("minify", function(){
	gulp.src("js/app.js")
		.pipe(uglify())
		.pipe(rename("app.min.js"))
		.pipe(gulp.dest("js"));

});

gulp.task("default", ["hello"], function(){
	console.log("this is the default task");
});

Then type in gulp “task or functions”

https://github.com/osscafe/gulp-cheatsheet

How to create a simple calculator program with javascript

This is a tutorial about how to create a simple calculator program with javascript, css, and html.

First create index.html file

<html>
<head>
    <title>Dice Simulator 2015</title>
    <link rel="stylesheet" href="style.css">
</head>  
<body>
  <h1>Calculator Example</h1>
  <p>Open the JavaScript developer console to interact.</p>
  <script src="calculator.js"></script>

</body>
</html>


Then create style.css file

* {
  font-family: Helvetica, Arial, sans-serif;
  text-align: center;
}


create calculator.js file

var calculator = {
  sum: 0,
  add: function(value) {
    this.sum += value;
  },
  subtract: function(value) {
  this.sum = this.sum - value;
  },
  multiply: function(value) {
  this.sum = this.sum * value;
  },
  divide: function(value) {
  this.sum = this.sum / value;
  },
  clear: function() {
    this.sum = 0;
  }, 
  equals: function() {
    return this.sum;
  }
}


After open javascript console
Type in commands example
calculator.add(1)
calculator.add(1)
calculator.equals() // 3

Create a Dice with HTML, CSS, and Javascript

We are going to create a html, css, and javascript die with this code. For every block of code create the coodinating file extension be it .js .html .css and etc. It should work. Happy coding.

First create index.html


<html>
<head>
    <title>Dice Simulator 2015</title>
    <link rel="stylesheet" href="style.css">
</head>  
<body>
  <p id="placeholder">
  
  </p>
  <button id="button">Roll Dice</button>
  <script src="dice.js"></script>
  <script src="ui.js"></script>
</body>
</html>

Second we are going to create style.css

* {
  font-family: Helvetica, Arial, sans-serif;
  text-align: center;
}
button {
  background-color: rgb(82, 186, 179);
  border-radius: 6px;
  border: none;
  color: rgb(255, 255, 255);
  padding: 10px;
  text-transform: uppercase;
  width: 200px;
  cursor: pointer;
}
#placeholder {
  height: 100px;
  width: 100px;
  padding: 50px;
  margin: 50px auto;
  border: 1px solid gray;
  border-radius: 10px;  
  font-size:80px;
}

3rd we are going to create the ui.js

function printNumber(number) {
  var placeholder = document.getElementById("placeholder");
  placeholder.innerHTML = number;
}

var button = document.getElementById("button");

button.onclick = function() {
  var result = dice.roll();
  printNumber(result);
};

Finally create the object lateral of the javascript file dice.js

var dice = {
sides: 6,
roll: function () {
  var sides = 6;
  var randomNumber = Math.floor(Math.random() * this.sides) + 1;
  return (randomNumber);
}
}

refactored for dice.js using prototype

function Dice(sides) {
  this.sides = sides;
}
Dice.prototype.roll = function diceRoll () {
  var randomNumber = Math.floor(Math.random() * this.sides) + 1;
    return randomNumber;
  }
var dice = new Dice(6);

In conclusion, I hope you learned something from my source code.