Build with Code using Codesmith's Self-paced Learning Resources
Codesmith offers a variety of opportunities for learners at different stages of their coding...
In this article, you'll get a clear understanding of what functionality means in JavaScript, and how it’s built on three key concepts you should be aware of at any stage of your programming journey: variables, control flow, and looping.
By the end, you'll have gained valuable insights into how these elements work together to enable problem-solving, helping you control program execution (a fundamental skill in programming) and write more efficient JavaScript code.
Functionality in JavaScript rests on a few very important concepts. Variables, control flow, and looping are among their strongest foundations.
Variables allow us to store and reference meaningful information in memory.
Control flow enables us to run functionality based on certain conditions.
Looping allows us to repeat behavior until some condition has been met.
By starting with this set of fundamental principles, you will be able to problem-solve and communicate through almost any scenario in JavaScript.
What happens when JavaScript code runs? First, the engine goes through the code one line at a time and stores the information (data) we have written using special declaration keywords called — you guessed it — variables. JavaScript saving that data allows us to reference, change, or run functionality on it later.
We can store data in many different formats (called data types) in different ways. For example...
let num = 6;
let name = ‘jane’;
const storeOfInfo = {
name: ‘sebastien’,
home: [‘france’, ‘nyc’],
};
const randomList = [1,‘2’, [3], {4: undefined}];
let introToJavaScriptIsAwesome = true;
In this code, we store a number, a string, an object, an array, and a boolean to appropriately named variables.
Saving data to variables is the beginning of understanding functionality in JavaScript, but how can we move towards achieving that functionality?
We can execute different functionality based on specific conditions. We call this control flow, and in JavaScript it can be facilitated using conditional statements. What does this look like? Well, this gives us the ability to chain control flow statements using the if, else if, and else keywords.
We can use multiple "if" statements on the same data. Each new instance of a single if keyword will be considered the start of a new control flow. We do not need the else statement if we do not have a default case.
const myGrade = 75;
if (myGrade <= 70) {
console.log(myGrade + ‘is failing.’);
} else if(myGrade < 80) {
console.log(myGrade + ‘is passing.’);
} else {
console.log(myGrade + ‘is excellent.’);
}
if (myGrade === 100) {
console.log(‘a perfect grade!’);
}
// what if we re-assign myGrade to 100?
In this example of conditional statements, we check whether my grade lies within a specified range and take action accordingly. If a condition is not met, the code for that specified condition does not run. Using conditional statements effectively allows us to control the flow of our programs and respond to different scenarios as they arise.
We store data so we can retrieve it later and run functionality on it. Control structures like loops are used to manage the flow of a program, telling it when to perform a task and when to stop. These streamline repetitive tasks, allowing us to repeat a piece of code multiple times, so we don't have to write the same code block again and again.
We have a built-in tool in JavaScript syntax known as a for loop, which lets us access each index of an array (one by one) and do something with that element. We refer back to our saved data using the label, or variable name, we gave it, and we can access an element from our array using square brackets (bracket notation).
Let’s consider an example where we want to sum up some numbers and then find the average (assuming possible score is 100).
const myGrades = [50, 75, 90];
let sum = 0;
for (let i = 0; i < myGrades.length; i++) {
// what is sum?
// what is i?
sum = sum + myGrades[i];
// now what is sum?
}
// what happens first and why?
let average = sum / myGrades.length;
Another type of control structure is the while loop. Unlike the for loop, which runs a set number of times based on an index, a while loop keeps going as long as a condition is true. This makes it useful when you don’t know ahead of time how many times you’ll need to repeat an action.
For example, let’s say you want to keep summing numbers from an array until the total exceeds a certain value. You can use a while loop to handle that situation:
let sum = 0;
let i = 0;
const myGrades = [50, 75, 90];
while (sum <= 150 && i < myGrades.length) {
sum += myGrades[i];
i++;
}
// The loop stops once the sum is greater than 150 or we've gone through all the numbers
Here, the loop runs as long as the sum is 150 or less, stopping once the condition is no longer met.
What happens when we put a loop inside of another loop? Why would we might want to do this? It’s typically best practice to avoid nesting loops if possible; however, sometimes it’s necessary.
For example, if we want to see all possible sums for each number in an array, we would use an outer for loop to access each number in the array. As the outer loop iterates, we would employ an inner for loop to add each number in the array to the current number we are working with in the outer loop. This allows us to explore combinations of numbers and perform calculations based on those combinations.
const myNums = [50, 75, 90];
for (let i = 0; i < myNums.length; i++) {
const num1 = myNums[i];
// what is num1, i and myNums[i]?
for (let j = 0; j < myNums.length; j++) {
const num2 = myNums[j];
// what is num2, j and myNums[j]?
console.log(‘Sum: ’, num1 + num2);
}
};
When nesting loops, avoid using identical variable names in either loop. It is common to use i as the variable name for the outer for loop, and j for the inner.
It's important to properly manage loops to avoid the formation of infinite loops, which occur when a loop has no terminating condition, or the condition to exit the loop is never met.
As a result, the loop continues running indefinitely, which can cause the browser or system to freeze or crash (no error message—the program just keeps running indefinitely). This often happens accidentally when there's a mistake in the loop's logic.
We can use different combinations of functionality to accomplish our goals. What if we want to see if any two numbers in our array sum to the number 7?
We can use a combination of tools learned today (loops with control flow) to accomplish this task!
const myNums = [1, 2, 3, 4, 5];
for (let i = 0; i < myNums.length; i++) {
const num1 = myNums[i];
for (let j = 0; j < myNums.length; j++) {
const num2 = myNums[j];
if (num1 + num2 === 7) {
console.log(‘Lucky Seven!’);
}
}
}
Here, we are assigning an array to a variable called myNums, and using that variable in two for loops. In the inner for loop, we create a conditional to check if the numbers add up to 7 and, if they do, taking an extra action.
Variables, looping, and control flow comprise the fundamental principles of JavaScript. These foundational pieces of JavaScript let us store data and apply functionality on that data. This is the backbone of web development with JavaScript.
Let’s quickly go over what we’ve learned. Variables and execution refer to when we're writing code and run it we mainly store ‘data’ and run ‘functionality’ on it. There are different types of data we can store and different types of functionality. These are referred to as data types, and we can run code on that data. Control flow enables us to run some functionality based on different conditions, and looping enables us to run the same functionality over and over until a terminating status is attained.
As you’re hopefully beginning to see, these core concepts are essential in JavaScript and other programming languages, enabling us to create powerful applications for solving engineering problems.
Variables play a key role in controlling the flow of a program by storing and managing data that's used to make decisions or drive actions within the code. They hold data that's later evaluated in control structures like if statements or loops. For instance, in an if statement, a variable’s value can determine which block of code gets executed.
In loops, variables often track the progress or state of the loop, like counters or accumulators, which help control when the loop should stop (or continue).
Assigning different values to variables throughout a program allows for the flow to dynamically change. This flexibility means the program can react to different inputs or conditions during execution.
Exceptions are an important control flow mechanism in programming, allowing developers to handle errors or unexpected conditions gracefully. Exception handling provides a structured way to manage these issues, so programs can respond appropriately without crashing.
When an error occurs during the execution of a program, the code will throw exceptions. This interrupts the normal flow of control, allowing the program to jump to a predefined block of code designed to handle the exception. Using keywords like try, catch, and finally means we can encapsulate potentially problematic code within a try block. In the case of an error, the control is passed to the catch block, where we can define how to respond to the error—whether that’s logging it, providing feedback to the user, or attempting a corrective action.
An example of control flow in JavaScript is using an if-else statement to execute different blocks of code based on a condition. Here’s a simple example:
let temperature = 30;
if (temperature > 25) {
console.log("It's hot outside.");
} else {
console.log("It's cool outside.");
}
In this example, the flow of the program is controlled by the value of the temperature variable. If the temperature is greater than 25, the program will print "It's hot outside." If not, it will print "It's cool outside." The control flow determines which path the program follows based on the condition in the if statement.
Codesmith offers a variety of opportunities for learners at different stages of their coding...
We’re excited to share the launch of JavaScript for Beginners on Udemy! This course is for anyone...