Javascript Basics for Non-Developer Types pt. 2/5

Part 1 of 5 is here.

In part 1, we covered the basics–numbers, strings, booleans, plus a few ways to use them.

If/Else

If/else can be used to evaluate conditional statements and do something. Eg. if (this condition), do this, else, do this.

if( "dayName".length <= 6 ) { console.log("Sunday, Monday or Friday"); } else { console.log("Tuesday, Wednesday, Thursday, Saturday"); }

In the statement above, if the length of your name is greater than or equal to eight, the console will print out, "Sunday, Monday or Friday", otherwise (else) it will print out, "Tuesday, Wednesday, Thursday, Saturday".

Variables

Variables store data. Declare them with var and note they are case sensitive.

var myDessert = "chocolate cake";

If we tell console.log(myDessert);, it will print out "chocolate cake". Variables can also be renamed, maybe you noticed sopapillas on the menu var myDessert = "sopapillas";.

FFFun with Functions

Functions are defined by the "function" keyword and contain parameters in between () and code to run between {}. When a function is invoked (or called), the code will run.

var pizzaSlice = function (price) { console.log(price * 3); };

The function above for pizza slices (at $3) will let us know our total cost dependent on how many slices we order.

pizzaSlice(6);

Therefore, $18! 🍕🍕🍕🍕🍕🍕

Stuffing If/Else Inside a Function

This statement will let you know if you are a crazy cat lady.

var catLady = function(numCats) { if (numCats >= 3) { return "You are a crazy cat lady!"; } else { return "You probably don't need more cats."; } };

If you owned six cats and entered that value when invoking the function:

catLady(5);

The function would let you know that you probably don't need anymore cats. 🐈

Next, Loops. Part 3.