### Javascript Profit Margin Calculator

Hello Everyone!

I have been working on a project recently and that project required a profit margin calculator. I had built a few other types of calculators before, never one to calculate profit margins.

It took me a little digging and some web searching to figure out what I need to do as I am not the best at math!

Now I want to share my findings with you on how to build your own profit margin calculator! Now I won’t be building anything in HTML or Javascript in this post for our calculator. I will just show you the steps to take to do the calculations.

## The Code

Let’s dive right in shall we?

To figure our profit margin of to number this is pretty straight forward, I will show you the formula then how to reproduce in code.

## The Formula

Markup Percentage = Profit / Cost = 25 / 100 = 25%

```var cost = 10;
var sale = 20;
var margin = (sale - cost) / cost * 100
// margin = 100
```

Ahh that was pretty easy, right? As you can see with only a few lines of code we have figured out what the percentage of margin is of two numbers!

## Calculate Sale Price

Now, what if we need to figure out what the sale price would be of say \$12.50 with a profit margin of 60% is? We can do this pretty easily too!

```var cost = 12.50;
var sale;
var margin = 60;

sale = (margin / 100) * cost + cost;
// sale = 20```

Hopefully, you understand what we did there. If not I will do my best to explain.

We started at a cost of \$12.50 and wanted to know what the sale price would be with a 60% markup. To do this we take the 60% markup and divided by 100 this gives us 0.6. This is the fraction we need to calculate our sale price.

Now we take 0.6 and multiply by the cost which now gives us 7.5 which is 60% of 12.5. We can check this by dividing this by 12.5 which will give us 0.6 or 0.6X100=60%

The last thing to do is add that to the cost to get our sale price so, 12.5 + 7.5 = sale price of 20

I deceided to wrap these in a couple function to make using them a bit easier:

```// Calculate Margin
function calcMargin(price, cost){
var cost = Math.round(cost*100)/100;
var price = Math.round(price*100)/100;
var diff = price - cost;
var margin = (diff / cost) * 100
return margin;
}

// Calculate Sale Price
function calcSalePrice(cost, margin){
var cost = Math.round(cost*100)/100;
var margin = Math.round(margin*100)/100;
var sale = (margin / 100) * cost;
var number = sale + cost;
return number;
}```

## Final Thoughts

As you can see this wasn’t too difficult to figure out and for someone who isn’t the best at math I had fun doing this!

Till Next Time, Keep Coding & Have Fun!

### FullCalendar 4 Custom Request Headers

Hello Everyone!

So I have been using FullCalendar recently on a project and in this project, it requires that the header X-Request-With : XMLHttpRequest bet set.

After digging around I could not find a way to set extra headers in version 4 of FullCalendar. Although the following solution is not ideal it does do the trick!

I modified the main.js file @ around line 4242. Here is the modified code from that file.

```/*!
FullCalendar Core Package v4.3.1

function requestJson(method, url, params, successCallback, failureCallback) {
method = method.toUpperCase();

}

var body = null;
if (method === 'GET') {
url = injectQueryStringParams(url, params);
}
else {
body = encodeParams(params);
}
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);

for(var prop in obj){
if (!obj.hasOwnProperty(prop)) continue;
}
}
}

if (method !== 'GET') {
}

if (xhr.status >= 200 && xhr.status < 400) {
try {
var res = JSON.parse(xhr.responseText);
successCallback(res, xhr);
}
catch (err) {
failureCallback('Failure parsing JSON', xhr);
}
}
else {
failureCallback('Request failed', xhr);
}
};
xhr.onerror = function () {
failureCallback('Request failed', xhr);
};
xhr.send(body);
}```

```extraParams = {
action: 'get_event',
{"X-Requested-With":"XMLHttpRequest"}
]
}; ```

If you know of another way to add custom headers without modifying the main.js file please let me know in the comments below!

### PHP Returning A Variable From An Include

Hey Everyone!

Today I want to show you how to return values from an included file. If you have files that you want to include into another file in PHP and you would like to access the variables inside this other file there are a few ways we can go about this.

Let us create a couple files. One will be the one we will store some values in and the other will be one we will use to include the other. We will call the first one config.php and the second one we will call main.php

This first method will return from the included file. Let us take a look at the following example.

## Config.php File

```<?php
// Our Config.php
// This contains our configuration variables

\$config['someConfig'] = 'some string of data';

// Return the config array
return \$config;```

## Main.php File

```<?php
// Main.php

/**
* This will include the config.php
* We will access the variables stored
* in config.php in this file.
*/

// Include The Config File
\$myConfig = include 'config.php';

echo \$myConfig['someConfig]; // Prints 'some string of data'```

So as you can see we can return in the file and access those values in the file that we included it in. We could have accessed these values without doing a return by simply using the same name and the variables listed in the included file.

Let us take a look at another example where we don’t return those values from the included file and see how we can access them.

As before the same files.

## Config.php File

```<?php
// Our Config.php
// This contains our configuration variables

\$config['someConfig'] = 'some string of data';
```

## Main.php File

```<?php
// Main.php

/**
* This will include the config.php
* We will access the variables stored
* in config.php in this file.
*/

// Include The Config File
include 'config.php';

echo \$config['someConfig]; // Prints 'some string of data'```

As you see we have accessed the variables from the included file without returning them.

## One More Example

I want to show one more example where when including a file on how to access the values. This following example will use a function to do the include. Let’s look at the following example and I will explain it afterward.

## Config.php File

```<?php
// Our Config.php
// This contains our configuration variables

\$config['someConfig'] = 'some string of data';
```

## Main.php File

```<?php
// Main.php

/**
* This will include the config.php
* We will access the variables stored
* in config.php in this file.
*/

// A function that includes a file
function someFunction(){
// Include The Config File
include 'config.php';
echo \$config['someConfig]; // Prints 'some string of data'
}

echo \$config['someConfig]; // Doesn't Print Anything```

As you can see from the previous example that trying to access the variables from outside of the function doing the include, it doesn’t work. This has to do with scope. The variables only have scope within the function that did included the file.

One way to access the variables outside of the function that calls the include is to return them from that function.

## Main.php File

```<?php
// Main.php

/**
* This will include the config.php
* We will access the variables stored
* in config.php in this file.
*/

// A function that includes a file
function someFunction(){
// Include The Config File
include 'config.php';
// Return the \$config variable
return \$config;
}

\$config = someFunction();
echo \$config['someConfig]; // Prints 'some string of data'```

Alright, Everyone that’s all I have for today. I hope this was helpful and as always keep coding! Cheers!

### JavaScript Arrow Functions

Hey Everyone!

Today I wanted to talk about JavaScript Arrow Functions. Arrow functions, in my opinion, are great! The only downside, if you want to call it that, is they aren’t supported by all browsers. Now I won’t get into a browser war debate and if you want to see what browsers support arrow functions I will leave a link at the bottom of this post to check.

## The Basics

To start, let’s look at the basics of arrow functions and build on that. In the following example, I will show a regular function and then an arrow function.

```// Typical Function
function myFunction(){
console.log(this);
arrowFunction();
};

// Arrow Function
var arrowFunction = () => {
console.log(this);
};

// Get button click

Let’s examine what’s happening in the code above. We have two functions and an event listener for a button click. If we run the above code and add a button in an HTML document with the id of “example” when we click this button it will run the `myFunction()` function which will `console.log` `this` and then run the `arrowFunction()` function and it will also do a `console.log()` of `this`.

When you run this code if you look in the console, you will notice that `this` is logged in the `myFunction()` statement will reference the object that called the function, which in this case is the button.

`<button id="example">`

On the other hand, the arrow function reference to `this` is the owner of the function. In this case the window object

`Window http://someurl.someplace`

As you can see the two functions reference to different representations of this.

To recap on this arrow functions `this` represents the owner of the function and regular function `this` represents the object that calls the function. Hope this is clear.

## Arrow Functions & Variables

With arrow functions, there are a few ways of passing variables. In the following examples, I will show a few different ways this can be done.

```// No Parentheses
var myFunc = x => x+1;
myFunc(1) // Returns 2

// Same as above with parentheses
var myFunc = (x) => x+1;
myFunc(1) // Returns 2

// Same as above with handelbars & parentheses
var myFunc = (x) => { x+1 };
myFunc(1) // Returns 2
```

## Arrow Functions & Objects

We can also create objects that use arrow functions. Let’s take a look at that!

```var myObj = {
myFunc: () => {
return 'My String';
},
anotherFunc: (x) => {
return x + 1;
}
};
myObj.myFunc(); // returns My String
myObj.anotherFunc(3) // returns 4```

Well everyone that is all I have for today! I will expand on this in the future. Hope you enjoyed, Thanks for reading!

### JavaScript Loops Basics

Hey again everyone! Back again today writing some more about JavaScript. I am wanting to create some posts that start with the basics of JavaScript and build up from there. That’s why I have been creating these JavaScript Basics posts.

So today I have decided to write about loops and how to use them.

Loops allow us to iterate or loop over some data such as an array or object. There are of course other methods for accessing data within an array or object, but sometimes using a loop is a more logical way of accessing our data.

## Loop Types

There are essential 2 main loop types. There are other forms and conditions that I won’t be discussing here today. These are the main two that are most commonly used.

The first type is called a for statement and the other a do…while statement. Both can take a little bit to get the hang of and lots of practice to master.

To start lets dive right in!

## For Loops

To start with let us look at the for loop which you may find yourself using quite often. A for loop looks something like the following:

```for (let i = 0; i < array.length; i++) {
// Do Something...
}```

As you can maybe see from the example above, we are counting up to the length of the array. If you don’t quite understand yet don’t worry I will explain further with other examples.

Let’s say that we have an array that contains objects which contain data you want to manipulate or print out. This can be done easily by doing the following:

```var array = [
{make:'GMC'},
{make:'Chevy'},
{make:'Ford'}
];
for (let i = 0; i < array.length; i++) {

// Add an id that's equal to the array index
array[i].id = i;

// print the vehicle make
console.log(array[i].make);
}```

As you can see from the example above we are able to iterate over our array add some information to each item and also print out some data. This can be very useful when dealing with a response from servers or databases.

If you are still having trouble understanding the above example I will break it down a little bit.

First, we have an array that contains some data we want to iterate over.

```var array = [
{make:'GMC'},
{make:'Chevy'},
{make:'Ford'}
];```

Next, we create our loop. In our loop, we have the 3 arguments. The first is “let i = 0;” What we are doing here is setting the start of our count. We could have set this to 3 but if the length of the array was less, then our loop would not have run.

For example:

```var array = ['a','b','c',]
for (let i = 3; i < array.length; i++) {
// Will not run 3 is greater than the length
console.log(i);
}```

The next argument is the condition statement. This is how we tell the for loop what condition has to be met in order to run. as you can see from the example above we stated that if i is less than array.length then go ahead and run the loop.

The last part of our for loop i++; is saying that we want to count up or add up to the same number as the length of the arrays indexes.

Now, this isn’t an exhaustive list of examples for the for loop but it should get you started and help you have a basic understanding of how it works.

## Do…While

Next is the do-while loop. This loop is used when you want to do something until a specified condition evaluates to false. To explain a little better let’s take a look at an example and then go over what’s happening!

```var array = [];
var count = 0;
do{
count += 1;
console.log(count)

<code> // add to the array </code>
<code>array.push(count);</code>

}while(count < 10);

console.log(array);```

Now if you understand what’s happening here great! If not no worries I will do my best to explain.

Initially, we start with an empty array and a variable named count and set it 0. Then we create the do..while loop. Inside the do part of our loop we specify some code to execute.

## The code inside the do

Inside the do portion of our loop, we set the count to be added up from the previous iteration. Essentially every time the loop is run we add one more to the previous value stored in the count. then we log this value to the console.

Next, we use a built-in JavaScript function push() to push the count on to the end of the array. If your not familiar with this don’t worry about it. If you run this example and observe it in the console you will see an array printed out containing the numbers 1 thru 10

## The While Condition

Next is the while condition. This is the portion of our loop that checks for a condition on every iteration to know when to exit. If the condition is met then the loop exits else it runs again.

As you can see from the example above we have a condition that says (count less than 10) meaning if the count is less than 10 run the code inside the do again and once it reaches 10 exits.

## Final Thoughts

Well, I hope you all enjoyed this as much as I did. And this is by no means an exhaustive list of examples of looping over data but hopefully gives you a better understanding of how a couple of the main loop statements work in JavaScript.

Until next time, Keep Coding! 🙂

### JavaScript Object Basics

Hello everyone again! Today I am writing another post about some basics with JavaScript. JavaScript is a great client-side language that can make your pages more dynamic and intuitive.

Today we are going to talk a little bit about objects. Objects are similar to arrays. Essentially an array is an object. If you are not familiar with arrays you can read my other post on them here: http://blog.cooterscomputers.com/javascript-arrays-basics/

The main difference in using objects vs arrays is that you can use ordinal indexing vs keyed indexing with arrays.

Notice the following example:

```// An Object
var myObj = {
myKey:'myValue'
}
console.log(myObj.myKey)//Prints myValue

// An Array
var myArray = ['myValue'];
console.log(myArray); // Prints myValue```

As you can see from the example above using objects vs arrays gives us the ability to use ordinal indexing, meaning we can access our data with named keys rather than a pointer integer. This allows for easier access to our data.

To go a little further with our objects I will show you how we can use them to store more than just strings of data. We can store other types of data and information as well.

Take the following for example:

```var someObject = {
myString: 'Some string of information',
myFunction: function(x){
return x+1;
}
}

someObject.myFunction(3); // Returns 4```

As you can see we have created an object that contains a string as well as a function. You can see how this can be very helpful by allowing us to store some functions inside our object and allow us to access them from within a single space.

## Final Thought

JavaScript Object is very useful. They are a main part of the JavaScript language and are used anywhere you see JavaScript code. The sooner you learn to use them the easier your coding will become.

### JavaScript Arrays Basics

Hey Everyone!

This is my first post of many on JavaScript. I wanted to share a little information and some basics on arrays in JavaScript. Arrays are great for storing information to be accessed later.

To create an array in JavaScript it is very simple.

`var myArr = [];`

That’s it! Now, of course, our array isn’t very useful yet. It doesn’t contain any information. Let’s add some values to our array now and see how that looks.

`var myArr = ['car', 'truck', 'van'];`

Now we have populated our array with some values, this is great! But how do we access those values later? We can go about this a few different ways, but to keep things simple we will keep with the basics.

To access the values stored in our array we can access it by what’s called it’s “key”. Arrays have what’s called key/value pairs. For every value in the array, there is a key associated with it. We can use this key to access the value. To do that let’s look at the following example:

```var myArr = ['car', 'truck', 'van'];
myArr; // This will contain the value "car"
myArr; // This will contain the value "truck"
myArr; // This will contain the value "van"```

Now as you may have noticed that when accessing the values in our array we started with the number zero (0) to reference the first item, not the number 1.

That’s because arrays keys start from zero and count up from there, not from the number (1) as you might expect. If you are looking for a more detailed explanation of why that is, feel free to search around for a more in-depth explanation.

Well, I hope this gives you a little more explanation on arrays and how to access the values in them in JavaScript.

Stay tuned for more on JavaScript & Arrays!

Thanks!