JavaScript Functions

Functions are the fun part of JavaScript!

What are functions? They are pieces of code that perform actions. Without functions, JavaScript wouldn’t really do anything.

If you’ve been following along with me in previous posts, you already know some functions! For example, these are functions:

alert()
prompt()

Note: The () next to the function names mean to execute (also called ‘run’ or ‘call’) the function.


When using functions, we can either use existing JavaScript functions, or create our own functions.

How to create a function

1) Function Declaration

Declare/create the function:

function sayHello() {
    console.log("Hello");
}

Call the function:

sayHello();

2) Function Expression

Assign a function to the sayBye variable:

var sayBye = function() {
    console.log("Bye");
}

Use variable to call the function:

sayBye();

Note: When using this, the function itself doesn’t actually have a name. The function has simply been assigned to a variable (sayBye). This is called using an Anonymous Function.


Rather than using an anonymous function, we could have done this instead:

var sayBye = function byebye() {
console.log("Bye");
}

This would have created a function called ‘byebye’.


Examples of declaring and calling functions

Declare the function:

function sing() {
console.log("AHHHHHHH");
console.log("TEEEEEEE");
}

Call the function:

sing();

In this case, if I wanted to later change the song being sung by this function, I’d have to manually type it in and change the function. That would be tiresome.


A better way to do it

Declare the function:

function sing(song) {
console.log(song);
}

Now, any time I want to change the song, I can type:
Input:

sing("I'm just a girl");
sing("I'd rather not be");
sing("Cuz they won't let me drive late at night");

Output:

I'm just a girl
I'd rather not be
Cuz they won't let me drive late at night

Another example

Declare the function:

function multiply(a, b) {
return a * b;
}

Input:

multiply(5, 10);

Output:

50

Note: ‘Return’ is how we get the function to give us something, rather than just log the result in the console. Once you return in a function, the function stops running.


Using IF statements in functions

Declare the function:

function multiply(a, b) {
if (a > 10 || b > 10) {
return "that's too hard";
} else {
return a * b;
}
}

Input:

multiply(5, 10);

Output:

"that's too hard"

Congrats, you’ve made it through learning functions. The best way to become competent with functions is to keep playing with them. Functions may be the hardest part of JavaScript, but they are also where the fun is! Make sure you get a good understanding of functions before moving on to the next topic.

JavaScript Conditionals & Operators

Notes on what I learned from the JavaScript section of The Complete Web Developer in 2018: Zero to Mastery class on Udemy


Conditionals

Q: What are conditional expressions?
A: Conditional expressions perform different computations or actions depending on whether a specified Boolean condition evaluates to true or false.


Types of Conditionals

IF statement

var name = prompt(“What is your name?”);
    Creates a popup that asks the user “What is your name?” and gives them a place to input


if (name === “Kandis”) {
    alert(“Hi Kandis!”);
}
    If the user input “Kandis”, there’s another popup that says “Hi Kandis!” If any other input is made, nothing happens.


Else statement

var name = prompt(“What is your name?”);
    Creates a popup that asks the user “What is your name?” and gives them a place to input


if (name === “Kandis”) {
    alert(“Hi Kandis!”);
 } else {
    alert(“User unknown. Please try again.”);
}
    If the user input “Kandis”, there’s another popup that says “Hi Kandis!” If any other input is made, the popup says “User unknown. Please try again.”


Else If statement

var name = prompt(“What is your name?”);
    Creates a popup that asks the user “What is your name?” and gives them a place to input


if (name === “Kandis”) {
    alert(“Hi Kandis!”);
} else if (name === Susy”) {
    alert(“Hi Susy!”);
} else {
    alert(“User unknown. Please try again.”);
}
    If the user input “Kandis”, there’s another popup that says “Hi Kandis!” If the user input “Susy”, there’s another popup that says “Hi Susy!” If any other input is made, the popup says “User unknown. Please try again.”

Logical Operators

Q: What are logical operators?
A: Logical operators are programming-language symbols that denote a logical operation.


Types of Logical Operators

AND (&&)

if (firstName === “Jane” && lastName === “Smith”) {
    alert(“Hi Jane Smith!”);
}
    If firstName is Jane and lastName is Smith, a popup is created that says “Hi Jane Smith!” If any other input is made, nothing happens.


OR (||)

if (name === “Kandis” || name === “Sally”) {
    alert(“Hi Kandis or Sally!”);
}
     If name is Jane or name is Sally, a popup is created that says “Hi Kandis or Sally!” If any other input is made, nothing happens.


IF NOT (!) 

(returns true if an answer is not equal to something)

Input:
name = “Sally”
if (!(name === “Kandis”)) {
    alert(“Hi Kandis”);
}
    If (name is equal to Kandis) is NOT true, return “true”.


Output:
true

JavaScript Types & Variables

Notes on what I learned from the JavaScript section of The Complete Web Developer in 2018: Zero to Mastery class on Udemy

Q: What is JavaScript?
A: It’s the programming language that makes things happen on the website you visit. Pop-ups, replying to a Facebook post, tweeting, posting a YouTube video… ALL JavaScript!

Cool fact: JavaScript was created by Netscape in an effort to give it a competitive advantage. (bonus points: who actually remembers Netscape? If you don’t know what it is, go google it. RIP Netscape.)


JavaScript Types (values that JavaScript can have)

1. Number: Integers like 1, 2, 3, or math like 1 + 2 (returns 3) or 6 / 2 (returns 3). There’s also something called a modulo calculation, which I’ve explained below if you’re unfamiliar with the concept (I was super confused by it when I first saw it).

Note: % = Modulo. Modulo is a calculation of what is remaining after you divide one number by another. So 3 % 2 = 1, because if you divide 3 by 2, you end up with 1 left over. 12 % 6 = 0, because 12 is able to be divided up into two buckets of 6, with nothing remaining.


2. String: Text, indicated by putting something in single or double quotes. “hello world” ‘bob’, “Hello ” + “there” returns “Hello there” (don’t forget the space after the ‘o’!). You can also turn numbers into strings: “3”.

Note: If your string contains a quote, there are a couple ways to handle it:
a) Use double quotes on the outside, and single quotes on the inside: “This isn’t going to return an error.”
b) Use a backslash (\) to indicate that the single quote within the string should not be considered code: ‘This isn\’t going to return an error.’ (The \ doesn’t print)

Performing calculations with strings:

Example 1: Adding a number and a “number” (a number with type equal to string)

Input: 10 + “34”

Output: “1034”


Why? JavaScript looks at the input (10) and sees that you’re trying to add it to a string, so it makes the entire thing a string to make it work. So if you added “SillyBilly” + “34”, you’d get “SillyBilly34”. It’s treating the 10 like SillyBilly (a string).

Example 2: Subtracting a “number” from a number

Input: 10 – “3”

Output: 7

Q: What the heck?! Why is subtraction treated differently than addition? Why JavaScript gods, WHY?!
A: Sometimes the gods have a reason. Have a little faith. The reason is this – while you can add two strings together (i.e. “hello ” + “there” = “hello there”), you can’t really subtract a string from another string. Because of this, JavaScript helpfully(?) decides to subtract 3 as a number rather than return an error, because it assumes you know what you’re doing (a dangerous assumption in my case, but thanks for the vote of confidence, JavaScript gods!).


3. Boolean: True/False (example: 3 > 4 would return False, 3 >= 3 would return True)
Examples:

Input

5 > 10
5 < 10
5 <= 5
2 = 2
2 === 2 (does 2 equal 2?)
3 !== 3 (is 3 not equal to 3?)

Output

False
True
True
Error
True
False

Q: Ok, I’m with you, except for the triple equal signs. What’s up with that?
A: I’m actually not sure. I’ve seen double equal signs used in Python, but this is my first time seeing triple. I’ll come back and explain it when I understand it. All I know for now is that if you want to ask if something is equal to another thing in JavaScript, you need to use triple equal signs.


JavaScript Variables

Variable rules:
1) Must start with a letter, underscore or dollar sign (cannot be a number or any other symbol)
2) Variable names should be in camel case (exampleVariable, newBook, badApple)

Example of using variables with prompts:

var currentJob = prompt(“Enter your current job title”);
var dreamJob = prompt(“Enter your dream job title”);

User is prompted and inputs: “Teacher” and “Web Developer”

After user has input:

Input: currentJob

Output: “Teacher”

Input: dreamJob

Output: “Web Developer”


Another example, this time with numbers input as variable values:

var luckyNumber = prompt(“What is your lucky number?”);
var unluckyNumber = prompt(“What is your least lucky number?”)

User is prompted and inputs: “5” and “2”

After user has input:

Input: luckyNumber

Output: “5”


Input: unluckyNumber

Output: “2”

(See the quotes? Those are strings!)

In order to turn a string back into a number, we’d change the Type:

Input: Number(luckyNumber)

Output: 5

Add the numbers together:
var sum = Number(luckyNumber) + Number(unluckyNumber)
Return the sum to the user:
alert(sum);