Conditionals
Conditionals are essential for decision-making and controlling the flow of your program. The simplest form of a conditional is the if
statement, which will execute a block of code if a given condition is true.
You can extend this with else if
and else
statements to manage more complex conditions. Conditionals are fundamental for things like form validation, feature toggles, or implementing game logic, but you can also use them in many creative ways. Note that else if
is basically another if
while else
is kind of the “catch all” for when none of the comparisons are true:
What’s up with the triple equals? In JavaScript, the
==
operator checks for equality of value, but not the type of value. For example,1 == "1"
would evaluate totrue
, even though the left item is aNumber
while the right is aString
.The
===
operator checks for both value and type, so1 === "1"
would evaluate to false. It’s generally good practice to use===
to avoid unexpected behavior.
Loops
Loops are repetitive execution of code. Imagine that you have a group of 5, 10, or even 100 things that you want to cycle through and manipulate. This is exactly where loops come in handy.
The for
loop is the most common type of loop, useful for going through arrays, strings, or executing a block of code a specific number of times.
There’s a lot going on inside the parentheses:
Initialize (or “set up”) a counter
var i = 0;
A variable – i
– is set up with the value of 0
. This variable serves as our “counter”, keeping track of how many times we’ve done the loop.
Check the condition
i < fruits.length;
The loop will continue as long as this condition is true.
So, on the first time through the loop, i
is 0
. Since 0
is < fruits.length
, we stop here for a second, then jump down into the code inside the braces:
for (...) {
console.log(fruits[i]); // <- do this stuff now
}
If you remember from the intro to JavaScript, [i]
at the end of fruits
is the way you access that particular piece of data. So on the first time through the loop, i
is 0
, so the code that runs is fruits[0]
, which means the first piece of data in fruits
, which is apple
.
We do this, then jump back to the parentheses at the top.
Increment the counter
i++
i
is increased by 1 after each time through the loop, which is what allows the loop to eventually end. ++
is a special symbol that increases a variable by 1.
The semi-colons separate the three parts of the loop.
So, this loop would write to the console, then stop:
apple
banana
cherry
Now let’s do something else with this same data:
This time, we’re using the split()
, reverse()
, and join()
built-in functions to reverse each string in the array:
split()
splits a string into an array of individual lettersreverse()
reverses the order of the elements in an arrayjoin()
joins all elements of an array into a string
"apple".split(""); // ["a", "p", "p", "l", "e"]
["a", "p", "p", "l", "e"].reverse(); // ["e", "l", "p", "p", "a"]
["e", "l", "p", "p", "a"].join(""); // "elppa"
These are built-in functions that are part of the JavaScript language (and a part of many other programming languages). So within the loop, we are accessing each item in the array, splitting it into an array of characters, reversing the order of the characters, and then joining them back together into a string.
This is a common pattern in JavaScript, chaining multiple methods together to manipulate data.
Functions
Functions serve as the building blocks of JavaScript code, encapsulating specific tasks or computations.
Functions can take input (also called arguments or parameters), perform actions, and then return an output. This modular approach makes your code easier to manage, and promotes code reusability, as functions can be called multiple times throughout your code.
Here is a function that takes two numbers, adds them, and prints them in the console:
Here’s a helpful diagram of the anatomy of a function:
Going back to an example from earlier in this lecture, we could wrap some control flow logic in a function, if we wanted to reuse it:
Functions can be used for all kinds of things. Think of them as reusable tools that you can use to build your program.
For example, you could write a function that takes a string as an argument and returns the string reversed (as we also did above):
With a function like this, you can easily reverse any string by calling reverseString()
with a string as an argument instead of having to write the same code over and over again.
What’s inside the parentheses is called a parameter. Parameters are variables that are used to store the data that is passed into a function. In this case, in the initial function definition the parameter is str
, which is a string. You could name that whatever you want, but it’s often useful to name it something generic that implies the type of data that the parameter expects you to give it.
When you call the function, you pass in an argument, which is the actual value that is passed into the function.
So now our reverse fruits program could be:
This is a great example of a small program.
A program is a set of instructions that a computer can execute. It usually (but not always) contains:
Variables: Used to store data values
Functions: Blocks of code designed to perform a particular task
Control structures: Conditional statements (if/else/else if) and loops that control the flow of the program
Aside: return
vs console.log
Throughout these examples I’ve used both console.log()
and return
. What’s the difference?
return
and console.log()
serve different purposes in JavaScript:
return
return
is used in a function to specify the value that the function should output when it is called. When a return
statement is executed, the function stops running and returns the specified value to the place where the function was called.
function sum(a, b) {
return a + b;
}
var result = sum(5, 3); // result is 8
console.log()
console.log()
is a built-in function that prints the provided value to the console. It’s a way to check values or debug code. Using console.log()
doesn’t affect the execution or the output of a function.
function showValue(value) {
console.log(value);
}
showValue("Hello, World!"); // Prints "Hello, World!" to the console
Here, showValue
prints the value of value to the console. There is no return
statement, so the function doesn’t produce an output that can be used elsewhere in the code.
In summary, use return
when you need to get a value from a function to use in your code. Use console.log
when you want to display a value for debugging or information purposes.
Recap
- Conditionals allow you to perform different actions based on different conditions. They are the decision-makers of your code.
- Loops enable you to execute a block of code repeatedly, a powerful tool for handling repetitive tasks.
- Functions turn code into reusable blocks.
Looking Ahead
A key area we’ll delve into in the future is DOM manipulation – the part of JavaScript that allows you to dynamically change the content, structure, and style of your web pages.
However, none of that would have been comprehensible without first grasping the foundational programming concepts we’ve covered so far. What we’ve discussed here, and in the introductory lecture, are the fundamentals common to all programming languages and essential to computer science as a whole.