Functions and Conditionals; Introduction to SVG and Illustrator

Thu, Sep 24, 2020

Functions

A function is another data type, just like numbers, strings, booleans, arrays and objects. You can assign functions to variables, just like the other data types.

//example of an empty function assigned to a variable. This does nothing,
//it's just an example.
var someVariable = function(){ };

But what exactly is a function? It’s a block of code that is stored into memory to await execution at a time when the function is run. When we place code in a function, it is read by the program, but the code is not executed immediately. Rather, it waits until we tell it to.

//A function that when called, will return a string with "Hello there"
var sayGreeting = function(){ return "Hello there"; }

This might seem confusing at first, especially when compared to other static data types like strings. It’s important to note that when we assign a function to a variable, we basically just make a special variable that has the ability to call the code in the curly braces. You call the function by using the parentheses characters.

var sayGreeting = function(){ return "Hello there"; }

//now run the function. This will output the string.
console.log(sayGreeting()); 

When the function is run, it returns some information — typically as a different data type. (This is the part that can be confusing). But this only happens when the function is run. For example:

var sayGreeting = function(){ return "Hello there"; }

var anotherVariable = sayGreeting();

//value of anotherVariable is the string "Hello there", 
//because that is what was returned.

Arguments

The parentheses have a special purpose, which is to include a variable called an argument. function(argument). This argument is passed into the function, and can be used as part of the return. Let’ take the following example:

var calculateTip = function(bill){ return bill * 0.20; }

calculateTip(10); //this will return 10 * 20%, or 2 dollars

We can see we have the argument bill which we can use in the function. This argument acts like a temporary variable whose value is determined when the function is run. This allows us to reuse the function numerous times to make multiple calculations.

var calculateTip = function(bill){ 
    return bill * 0.20; 
}

calculateTip(10);   //this will return 10 * 20%, or 2 dollars
calculateTip(100);  //this will return 20
calculateTip(1000); //this will return 200

Multiple Arguments

You can also specify multiple arguments, which can be passed into the function. We do this by separating them with commas.

var calculateTip = function(bill, tip){ 
    return bill * tip; 
}

calculateTip(10, 0.15);  //calculate a $10 bill with 15% tip
calculateTip(100, 0.10); //calculate a $100 bill with 10% tip
calculateTip(1000, 0);   //calculate a $1000 bill with 0% tip

It’s important to note that in the example above, the calculateTip() isn’t displaying the output anywhere. Normally we would do something with the returned result, like assign it to another variable, or output it onto the page.

Here is an example of writing a greeting onto the page:

var greeting = function(name, location){
    return "Hello " + name + " from " + location;
}

document.write( greeting("Jeremy", "Berkeley") );

//output to the page:
//Hello Jeremy from Berkeley

Above we’re using document.write(), which is a built-in function in the browser that allows us to output some text to the page. (Note: this is an archaic method of writing text to the page, typically we would use a JS library like jQuery or d3).

var makeBold = function(str){
    return "<strong>" + str + "</strong>";
}

document.write("Some " + makeBold("text") + " where parts are " + makeBold("bold"));

//output:
//Some text where parts are bold

In the above example, we’ve designed a function that takes a string, and adds some <strong> tags around them, then returns the new text. We can reuse the function over and over by sending new data, each time it would convert it to bold.

Another way to write functions

On a rare occasion, you might see functions written in a different way where they are not assigned to a variable. These are called function declarations. They differ slightly in a fairly technical way. When a function is declared (not assigned to a variable) then it is read into memory before all other code. This means you can technically call a function before you even declare it! This isn’t possible with variables, where everything needs to be in order.

var functionOne = function() {
    // Some code
};
function functionTwo() {
    // Some code
}

//they both do the same thing
functionOne(); 
functionTwo(); 

In the above example, both methods are identical. We can specify function someName() to declare it, or we can assign an anonymous function to a variable var someVar = function().

Here is where they differ:

functionOne(); //gives an error, because it doesn't exist yet!
functionTwo(); //This is fine, because declared functions are read first

var functionOne = function() {
    // Some code
};
function functionTwo() {
    // Some code
}

If you’re curious about more ways to write functions, check out this StackOverflow article or this comprehensive article about named functions.

Variable Scope

There is another unique quality of functions, and that is an issue called variable scope. This is where variables you declare (create with var) within a function, only exist within that function.

var myCoolFunction = function(){
    var data = [1, 2, 3, 4]; //created an array variable
}

console.log(data); //ERROR! data variable doesn't exist outside the function!

Also, any argument variables only exist within that function.

var calculateTip = function(bill){
    return bill * .20;
}

console.log(bill); //ERROR! bill doesn't exist outside the function

Variable scope will become important later.

Functions as values inside objects

Remember that an object literal can store any data type. This includes functions.

var person = {
    name     : "Joe",
    age      : 25,
    greeting : function(){ return "Hello!"; }
}

person.name       //value is Joe as a string
person.age        //value is Joe as a number
person.greeting() //this runs the function, and returns the string "Hello!"

“this” keyword

One of the most confusing aspects of JavaScript function is the use of this keyword. Basically, there is a special variable called “this” which automatically exists inside every function. So, what is it’s value? The value of this is the object that called the function.

This makes the most sense when the function is a value of an object, like in the earlier example.

var person = {
    name     : "Joe",
    age      : 25,
    greeting : function(){
        console.log(this.name); 
        //this will output "Joe", because this refers to the parent object
    }
}

Conditionals

One of the hallmarks of programming is the conditional operator. It gives the programs the ability to logically assess a variable, and decide a course of action depending on the result.

We use these operators to find out if a particular condition is true, and to pick a course of action depending on the result.

Conditional operators use the keyword if to find out if a certain condition—which is surrounded in parenthesis—is true or false. If the condition is true, then code that is surrounded by curly brackets is executed. Here is an example:

var score = 5;

if(score == 10){
    document.write("Congratulations! you won");
}

In the above example, we are assessing the condition x == 10 to see if this is true. The double-equals symbols is the equivalency operator, and checks to see if both sides of the equation are equal. This is different than the single-equals symbol, which is the assignment operator, and performs a different action of assigning a value to a variable.

In the above example, the code within the curly brackets would not execute, because the value score is not 10, and the condition was not true. So, our program would skip over the code in the curly brackets.

Here are some possible operators that can be used to establish conditions:

Operator   Description
== Equivalency Operator. Checks whether both sides are equal.
!= Bang Operator. Checks whether both sides are not equal.
> Greater than. Checks whether the left side is larger, but not equal to, the right side.
< Less than. Checks whether the left side is smaller, but not equal to, the right side.
>= Greater than or equal to. Checks whether the left side is greater or equal to right side.
<= Less than or equal to. Checks whether the left side is less than or equal to the right side.

Checking if value is more than or less than

In these examples, we check to see if the value is more than or less than another value. It’s important to note that all of these conditions will have either true or false result. If the condition is true, the code within the curly braces will be executed.

var x = 7;
var y = 10;

if(x > y){
    document.write("You win!");
}

In the above example, the value of x is not more than y, therefore, the code in the curly braces will not execute.

var age = 12;
var requirement = 12;

if(age >= requirement){
    document.write("You can ride the ferris wheel!");
}

In the above example, the code would be executed because the condition is true, age is more than or equal to the requirement variable. Else Statement

Sometimes you want some code to execute on when a condition is not met. We can optionally provide an alternative action using the else keyword, and a second set of curly brackets. Observe the following example:

var age = 20;

if(age >= 21){
    document.write("Have a beer!");
} else {
    document.write("Sorry, have a juice box instead.");
}

In the example above, the age variable is 20, which does not meet the condition of being more than or equal to 21. So the code inside the first set of curly brackets will not execute. The else statment provides an alterative when the condition fails, or is false. Negated Conditions

It’s important to remember that the program assesses the expression inside the parenthesis, to determine if it’s a true or false statement. This can be tricky at times, especially when using negated conditions. There is an operator called the not operator (also called a bang) that means “not equal to.” This is sometimes useful when you want to ensure the value can be anything but an equavalency. Observe the example below:

var answer = 3;

if(answer != 3.14){
    document.write("This is not pi");
}

In the above example, the expression evaluates to a true statement, answer is not equal 3.14, so the program will execute the code between the curly brackets. Evaluating multiple conditions

There are times when you want to check if multiple conditions exist. JavaScript, and many other programming languages, offer two operators for determining if multiple conditions exist, the AND operator, and the OR operator. The AND operator is signified by two ampersands, like so &&. The OR operator is sigified by two bar or pipe keys, like so ||. Symbol Description

Symbol  Description
&& AND operator. Checks if all conditions are true.
|| OR operator. Checks if either condition is true.

In the example below, we use the AND operator to check if two conditions are true.

var minimumHeight = 48;
var maximumHeight = 78;
var rider = 40;

if(rider > minimumHeight && rider < maximumHeight){
    document.write("you're tall enough to ride the ferris wheel");
}

In the example above, the code between the curly brackets will only execute if—and only if—both conditions are true. If one of them is false, the entire statement evaluates to false. The above example would not run, since the rider variable is not more than the minimumHeight, even through it is less than the maximumHeight.

The figure below shows and example using the OR operator:

var userResponse = "Maybe";

if(userReponse == "yes" || userResponse == "no"){
    document.write("Thanks for answering the question");
} else {
    document.write("Only yes or no responses are accepted");
}

In the example above, either condition can be true for the whole statement to be true. In situations where both conditions are true, the entire statement evaluates to true.

Below are some additional examples using the OR and AND operators:

if(x == 1 && y == 2 && z == 3){
    document.write("All three conditions must be true to see this text.");
}

if(x == 1 || y == 2 || z == 3){
    document.write("Any of the conditions can be true to see this text.");
}

Using Additional Parenthesis To Combine AND and OR operators

In situations where you want to use both AND and OR operators, you will need to specify the order of operations with additional parenthesis, like so:

if((x == 1 || x == 10) && (y == 1 || y == 6)){
    document.write("For this to be seen, x needs to be 1 or 10 and y needs to be 1 or 6.");
}

Empty Strings and Zero-value Numbers

There are a couple of idiosyncrasies to JavaScript and the way it assesses certain variables. If a string is empty, the variable it is assigned to will assess as false. Also, any number that has a zero value, will also result in a false condition when assessed. Consider the following example:

var emptyString = "";

if(emptyString == true){
    document.write("This text would only appear if the string had content.");
} else {
    document.write("Empty strings are false.");
}

The same is true of zero-value numbers, which will result as a false statement. It should also be noted that it is possible to assess a variable without using the equivalency operator. Putting a variable in the parenthesis will assess whether the variable is true or false. This is also a great method to check if a variable has a value.

var num = 10;
num = num - 10; //num is now zero

if(num){
    document.write("This text won't display since
            num is zero, and false");
} else {
    document.write("This text will display, since 
            num is zero, and thus false.");
}

Introduction to Scalable Vector Graphics (SVG)

Before we work with charting programs like D3, we need to first understand Scalable Vector Graphics (SVG). An SVG is a type of language which can also be displayed as image in a web browser. It can also be saved as its own file type (.svg) and opened in programs like Adobe Illustrator or InkScape.

Raster versus Vector

SVGs are vector graphics, which mean they work differently than the jpg images that you see on the web.

  • RASTER (jpg, gif) — These are images made up of square pixels. They are usually taken by a camera, and depict real subject matter. If you zoom in too much, these images will get pixelated and lose quality.
  • VECTOR (svg) — These are graphics made up of paths and points. They are usually drawn with illustration software. They never lose quality when zooming in.

Raster vs Vector example

Creating an SVG inside of HTML

There are many ways to create an SVG. One of the most basic methods is to simply add it directly to your HTML document.

<svg xmlns="http://www.w3.org/2000/svg" width="300px" height="200px">

</svg>

This will create a box to hold a SVG code right on your page. It’s important to set a width and a height, otherwise your graphic may not show up. Between these tags, we will add a number of special SVG tags for creating shapes.

Positioning of elements inside an SVG

Elements inside an SVG are positioned on an X and Y Cartesian coordinate system. The coordinate system might be a little different than other applications, such as those found in basic mathematics, because the 0,0 point is in the upper left-hand corner, and a positive Y axis goes downward.

Example of svg rect on grid

In this figure, the rectangle has an X coordinate of 2.5 units, and a Y of 2.5 units. If the Y value was a negative, the shape would go above the X axis.

A note about namespaces

SVG is its own markup language, and has unique tags that differ from HTML. Because of this, when you type an <svg> tag, it's important to include a special attribute called a namespace which tells the browser this is a different language other than HTML. The namespace for SVGs vary, but the more common one is xmlns="http://www.w3.org/2000/svg".

Circle Tag

The circle tag adds a circle shape to your SVG.

<svg xmlns="http://www.w3.org/2000/svg" width="300px" height="200px">
    <circle cx="150" cy="100" r="20" fill="red" stroke="black" stroke-width="3px"></circle>
</svg>

The above code would create a red circle, and appear as follows:

The circle tag has the following attributes:

  • cx — This is the x value of the center of the circle (center-X)
  • cy — This is the y value of the center of the circle (center-Y)
  • r — This is the radius of the circle. The radius is half the diameter across.

There are also some attributes which apply to most SVG shapes:

  • fill — This is the fill color of the shape, which can also use rbg or hex values.
  • stroke — This is the stroke color (stroke is like a border), which can also use rbg or hex values.
  • stroke-width — This is width, or thickness, of the stroke. It needs to have a unit of measure, like px.

Rectangle Tag

The rectangle tag adds a rectangle to your SVG.

<svg xmlns="http://www.w3.org/2000/svg" width="300px" height="200px">
    <rect x="50" y="50" width="100" height="50" fill="green"></rect>
</svg>

The above code would create a green rectangle, and appear as follows:

The rectangle tag has the following attributes:

  • x — This is the x value of the upper-left edge of the rectangle.
  • y — This is the y value of the upper-left edge of the rectangle.
  • width — This is width of the rectangle.
  • height — This is the height of the rectangle.

Line Tag

The line tag adds a straight line to your SVG.

<svg xmlns="http://www.w3.org/2000/svg" width="300px" height="200px">
    <line x1="25" y1="25" x2="100" y2="100" stroke="blue" stroke-width="4px"></line>
</svg>

The above code would create a blue line, and appear as follows:

The line tag has the following attributes:

  • x1 — This is the starting x value of the line.
  • y1 — This is the starting y value of the line.
  • x2 — This is the ending x value of the line.
  • y2 — This is the ending y value of the line.

Polygon Tag

The polygon tag adds a shape with multiple straight sides to your SVG.

<svg xmlns="http://www.w3.org/2000/svg" width="300px" height="200px">
    <polygon points="10,15 50,20 40,100 15,90" fill="yellow" stroke="black"></polygon>
</svg>

The above code would create a yellow polygon, and appear as follows:

The polygon tag has one primary attribute which defines its sides.

  • points — The value is a set of space-separated x,y coordinates which define each point, like connect-the-dots.

Path Tag

The path tag adds a free form shape, with a combination of either straight or curved sides, to your SVG.

<svg xmlns="http://www.w3.org/2000/svg" width="300px" height="200px">
    <path d="M24.229,37.582c0,0,0.872-15.561,7.377-7.525c0,0,9.144,1.383,3.276,7.123
    c0,0-5.103,2.806-1.276,6.632l3.444,11.48l-12.5,5.484L2.929,
    33.352l2.041-21.025l13.459-6.398c0,0-4.337,10.459-2.679,10.204
    s7.438,2.699,8.332,9.586s-15.857-1.933-10.627,1.128S17.214,
    40.643,24.229,37.582z" stroke="orange" stroke-width="1px"></path>
</svg>

The above code would create a black free form shape, and appear as follows:

The path tag has a single attribute which defines its shape, the d attribute. Inside, is a series of comma-separate coordinate numbers, each preceded by a letter. Each letter stands for a different way the path is drawn:

  • M — moveto
  • L — lineto
  • H — horizontal lineto
  • V — vertical lineto
  • C — curveto
  • S — smooth curveto
  • Q — quadratic Bézier curve
  • T — smooth quadratic Bézier curve to
  • A — elliptical Arc
  • Z — closepath

An example of a square would look like:

<path d="M25,25 L25,50 L50,50 L50,25 Z" />

In the above example, the coordates refer to

  • M (move to) x 25, y 25
  • L (line to) x 25, y 50
  • L (line to) x 50, y 50
  • L (line to) x 50, y 25
  • Z (close the path)

Curves in paths can be tricky and requires a basic understanding of Bezier curves. MDN has a good tutorial if you’re interested.

Text Tag

The text tag adds text to your SVG. The text is slightly different than HTML text, because it’s vector-based and can be manipulated as such.

<svg xmlns="http://www.w3.org/2000/svg" width="300px" height="200px">
    <text x="25" y="50" font-size="36px" fill="brown">hello world!</text>
</svg>

The above code would create a brown text, and appear as follows:

hello world!

The text tag has the following attributes:

  • x — This is the x value of the upper-left hand corner of the text box.
  • y — This is the y value of the upper-left hand corner of the text box.
  • font-family — This is the font stack (i.e. Helvetica, Arial, sans-serif) of the text.
  • font-size — This is the size of the text.

TSpan Tag

SVG Text cannot wrap to a new line like HTML. Instead, you need to specify the exact position of each line of text using the tspan tag. The tspan tag is designed to go inside the text tag.

<svg xmlns="http://www.w3.org/2000/svg" width="300px" height="200px">
    <text x="0" y="0" font-size="36px">
        <tspan x="0" dy="30" fill="green">hello</tspan>
        <tspan dx="-50" dy="40" fill="red">world!</tspan>
    </text>
</svg>

The above code would create a blue line, and appear as follows:

hello world!

The tspan tags can use either an x y attributes, which are absolute and take precedence from its parent text tag, or it can use the dx dy, which is a relative measurement:

  • x — Absolute x value of this line of text (overrides the x value from the parent text tag.)
  • y — Absolute y value of this line of text (overrides the y value from the parent text tag.)
  • dx — Relative to the tag before it. If it’s the second tspan, it’s relative to the end of the first line of text
  • dy — Relative to the tag before it. If it’s the second tspan, it’s relative to the end of the first line of text

Notice we put a negative dx in the second line of text. This is because the starting point is at the end of the first line of text.

Grouping Tag

The grouping tag is a way to group multiple shapes together so that they can be positioned in a specific location in your SVG. The group tag alone doesn’t actually display anything, it’s designed to wrap around other shapes. The group tag is denoted by a <g>.

<svg xmlns="http://www.w3.org/2000/svg" width="300px" height="200px">
    <g transform="translate(125, 50)">
        <circle cx="0" cy="0" r="10" fill="red"></circle>
        <text x="0" y="25" text-anchor="middle">A red circle</text>
    </g>
</svg>

The above code would create a red circle with text below it, and appear as follows:

A red circle
  • transform — An attribute used to apply a number of transformation effects. The most basic is translate which can move the grouping to a different starting X and Y point. You also have rotate to rotate an element, and scale to make an element larger or smaller. You can combine multiple translate values together like so:
<g transform="translate(2,10)rotate(-90)scale(1.1)">
</g>