JavaScript Fundamentals: A free course with challenges + video

JavaScript has been the most popular language for the past 6 years, and we don’t see that slowing down anytime soon. If you’re newer to JavaScript — awesome — this post is for you!

This free course outline of the CSX Precourse will cover the JavaScript basics such as variables/constants, strings, data types, arrays, and loops. CSX is Codesmith’s free online JavaScript learning journey, you can make an account and work through the Precourse Unit here.

The Precourse is designed to give an introduction to core JavaScript functionality so you can move on to tackle more advanced challenges. As you work your way though this unit on CSX, you’ll be working in an in-browser code editor, and viewing your results in the console.

This unit is made up of a combination of introductory reading material, 25 challenges to test your understanding of the concepts covered, and 1 in person (LA/NY)/online workshop to help you cement the JavaScript fundamentals.

A warning — the CSX precourse moves very quickly and is more focused on challenges to test understanding of concepts than pure explanation. You need to be comfortable with these basic JavaScript building blocks — and part of that is just repetition and familiarity. There are numerous online resources for these initial foundations and each person finds the one that fits them best. The key is to not stop building these foundations. The ones I recommend are —

  • Codecademy — Text-only teaching and challenges — free. You should complete the Introduction to JavaScript units 1–8
  • Team treehouse — Video-based — great introductory tutorials — but monthly subscription. You should complete parts 1–3 of their Learn JavaScript track before CSX
  • Freecodecamp — All the foundations you need in JavaScript, HTML and CSS. Also has an incredible community. You should complete Basic JavaScript (10 hours) before CSX

Let’s start the learning!

1: An Introduction to Variables/Constants

JavaScript has many different types of values. Some of these types are numbers, strings, and booleans. Variables are used in order to store these values. In the code below, the variable is named favoriteShow and the value that is being stored under the name favoriteShow is currently “Shameless”.

var favoriteShow = "Shameless";

The word var is a keyword in JavaScript that means we are going to create a variable. This is followed by the variable name, then the equals sign assigns whatever is to the right of the equals sign to the variable name.

Once you create a variable with the var keyword, you can also update that variable's value. First, we create a variable called tvShow and assign it the value "Black Mirror". Then, without using the var keyword we reassign tvShow to equal "Parks and Recreation".

var tvShow = "Black Mirror";
tvShow = "Parks and Recreation";

There are multiple keywords used to create variables in JavaScript. These are var, let and const. let and const come with additional restrictions on how the variable can be used.

Using the var and let keywords allows us to reassign a variable's value. Using the const keywords forbids reassigning a variable - const is short for constant, meaning that the assignment of the variable cannot change, it must be constant.

Consider the following:

const pet = "cat";

pet = "dog";

This would result in the error “Assignment to constant variable”

In the example below, you can see that the value of variables declared with the var and let keywords may be reassigned.

let fridge = "empty";
fridge = "full";

var house = "dirty";
house = "clean";

At this point you may be asking “what’s the difference between let and var?" This is a more advanced topic relating to how let and var (and const) are scoped. You'll learn more about scope in later lessons.

2. Challenge: Variable/Constant Assignment

Let’s first start off with an introduction to comments and console logs.

In JavaScript comments are usually notated by two forward slashes (//). In the CSX Precourse unit on the first challenge: variable assignment you’ll see them before the console.log statement on line 4. Commented lines are ignored when the code runs. Go ahead and run the code in the editor to the right with the "Run Code" button, and then uncomment the console.log statement by removing the forward slashes and run the code again to see what happens. They’re a great way to leave notes to yourself or other developers on your team what the code your writing is doing. If you’re writing complex code that gets to be lengthy, they’re a perfect way to separate out different functionality making your code much more readable and organized. You can read about multiple ways that comments are helpful in the comments on this quora question.

Now let’s chat about console logs — logging things to the console is a very handy way to see how JavaScript is interpreting values. We’ll be using it frequently throughout this CSX unit, so you’ll need to be familiar with this statement — if you’re iffy on them now I would give this a read. To use console logs, you need only type console.log() - whatever you pass between the parentheses will be logged.

Another note! The CSX Precourse unit uses ES6. You’ll run into this on the first challenge when const is used rather than var. To get a better sense of ES6 const, MDN can help you here.

To find out more about var, let, or const and when to use them, I recommend reading this excellent article.

Aha — now time to move on to your first challenge!

In this challenge you’ll start by declaring a constant named lastName and assign it the value of your last name. Make sure you wrap your name in quotation marks, e.g. "Smith".

We’ll then have you go back and modify the value of firstName to be your first name. Uncomment the console.log statement and run your code to test your answer; you should see ‘Jenny’ replaced by your first name—unless your first name is Jenny, of course.

Awesome — your first challenge is complete! If you have a question on CSX material you can always ask it to a mentor on the CSX Slack in the #csx-challenge-help channel.

Alright, let’s get going!

3. Challenge: Variable/Constant Reassignment

To start off a note that you can update variables that you declare with let and var. (What happens if you try to reassign the value of a const?)

Look at the example below and notice how the value assigned to the variable lastName changes:

let lastName = "Snow";
console.log(lastName); // should log: Snow
lastName = "Smith";
console.log(lastName); // should log: Smith

Now let’s practice reassigning — in this challenge you’ll reassign the variable firstName to your name.

CSX challenges will let you check your answer so be sure to click ‘is it working?’ to see if your answer passes the tests.

4. Challenge: Strings —

Strings are a data type in JavaScript. In short, they are bits of text written inside of quotation marks. You can use either single quotes ('), double quotes ("), or back ticks (`) as quotation marks to wrap a string, as long as the opening and closing symbols match. They are particularly useful for any data or value that can be represented as plain text.

Before beginning the challenge check out a few of the examples on the code editor in CSX.

In this challenge you’ll declare a variable myString whose value is a string to start getting used to the syntax.

5. Challenge: String Concatenation

Next, we’ll dive into string concatenation aka joining strings together. You’ve already seen an example in a previous exercise, which uses the + operator to concatenate strings. Remember this:

console.log("Hi, " + firstName);

Now for the challenge —

In this exercise you’ll use string concatenation to join the three provided strings (first, second, and third) and assign the resulting string to a variable called welcomeStatement. The value of welcomeStatement should be 'Welcome to the jungle!'

Welcome to the jungle that is JavaScript — wooo!

6. Challenge: Numbers — Addition/Subtraction -

Okay, so we were just discussing another data type in JavaScript that can be stored in variables/constants — numbers.

Pay close attention to the fact that the numbers are not wrapped in quotes. Keep in mind that if a value is wrapped in quotes, it becomes a string.

let age = 26;  // age is a number
let ageText = "26"; // ageText is a string

Numbers can be added or subtracted using the addition (+) and subtraction (-) operators.

let sum = 2 + 2; 
console.log(sum); // should log: 4

let age = 30;
let tenYrsAgo = age - 10;
console.log(tenYrsAgo); // should log: 20

Let’s dive in!

In this challenge you’ll create a variable birthYear and set it equal to the year of your birth.

Next, you’ll create a variable named age and set the value to your current age.

Finally, you’ll create a variable named in10Yrsand set the value to equal your age plus 10.

7. Challenge: Numbers — Multiplication/Division

Learning a little more about numbers…

Numbers can also be multiplied and divided using the multiplication (*) and division (/) operators.

console.log(6 * 5); // should log: 30
console.log(45 / 5); // should log: 9

Let’s play with this!

In this challenge you’ll perform the following multiplication/division operations in the CSX code editor:

  • Multiply 20 by 4 and save the result to a variable called twentyTimesFour
  • Divide 9 by 3 and save the result to a variable called nineOverThree
  • Multiply 200.3 * 3 and save the result to a variable called twoHundredTimesThree

A small note on floats!

Any number with the decimal point is a float. Notice that in the last exercise you multiplied 200.3 by 3 and the output from that was 600.9000000000001. What happened here? Why didn't we get 600.9?

The way floats are handled in JavaScript can cause these rounding errors. Some decimal numbers cannot be represented accurately. The reason has to do with how numbers are encoded. It’s something to be aware of when working with decimal numbers in JavaScript.

8. Challenge: Booleans —

Now it’s time for booleans! A Boolean (BOO-lee-uhn) is another data type in JavaScript. JavaScript boolean values can be either true or false. They are useful for determining whether or not blocks of code should be executed. They are also the default result for many evaluations.

let likesJavaScript = true;
let likesMath = false;

const numToCheck = 10;
console.log(numToCheck === 10) // should log: true

In the example above, we’re using the ===operator to compare numToCheck with 10 and determine if they are equal. If they are equal, both in value and data type, then JavaScript will log true. Otherwise, it will log false.

Booleans are extremely handy when dealing with conditional statements — you’ll learn more about them later in CSX.

For the following challenges, you will be using the comparison operators (==, ===, <, >, <=, >=) to compare two variables and see if the comparison yields true or false. You will assign the resulting boolean to a variable. For example:

let first = 7;
let second = 8;

let isFirstBigger = first > second;
console.log(isFirstBigger); // should log: false

first = 16;
console.log(isFirstBigger); // should log: true

Now you’ll need to make the following comparisons in the code editor:

  • Compare small and large using the < operator. Assign the result to a variable called isSmaller.
  • Compare num and string. First, use the == operator to compare the two variables, and assign the result to a variable calledisLooselyEqual. Second, use the === operator to compare the variables; assign the result to a variable called isStrictlyEqual.
  • Compare isTrue and isFalse using the !== operator. Assign the result to a variable called isTrueNotFalse.

Continue to experiment with different comparison operators and data types. You can see a full list of comparison operators here.

9. Challenge: Type Coercion —

Let’s start by looking at a few console logs and thinking about a few questions.

What do you think will be logged to the console? When you have an idea, uncomment and run the code. What happened?

console.log(10 + 5); // 15
console.log("10" + 5); // 105

The first statement adds the numbers as expected. But in the second statement, ‘105’ is logged to the console. Notice the quotation marks wrapped around the number 10 in the console.log statement; this means that the value is a string. There are no quotation marks around the number 5.

What happened is type coercion, an important concept in JavaScript. We can’t add a string value and a number value together; instead, JavaScript “coerces” (changes) the number into a string and treats the + operator as an instruction to concatenate strings.

console.log("10" + "5"); // 105
console.log("10" + 5); // 105

For this challenge we just want you to play around. Uncomment the code and see what happens. Then, try it out yourself and make sure you really understand the concept.

10. Challenge: Arrays — Examining Elements -

We know that if we need to hold on to a value, we can create a variable. But what if we need to store multiple values in a single place? One way to store a list of values is in an array.

Arrays are denoted by square brackets [], with each value inside of the array separated by commas like so:

let fellows = ["Brandon", "Sam", "Gordon"];

Notice that the array is a lot like a list. JavaScript uses a zero-based indexing system to keep track of values in the array, starting at 0 for the first array element, 1 for the second array element, and so on. This makes arrays very easy to work with, as you’ll see in the next section.

let letters = ['a', 'b', 'c']
// The index of 'a' is 0
// The index of 'b' is 1
// The index of 'c' is 2

What if we need to grab only a single element from our array? We can use the index of that element in the array to select it:

let friends = ['George', 'Thai', 'Brandon'];
console.log(friends[2]); // should log: 'Brandon'

Something that’s also very handy is knowing how many elements are in an array at any given time. Arrays come with a built-in length property that tells us how many items are currently in the array.

const myArray = [1, 3, 4, 2];

console.log(myArray.length); // should log 4

We can also add and remove items from our arrays using some additional built-in methods. To add an element to the end of an array, use the push method. To remove items from the end of an array, use the pop method.

let numbers = [1, 2, 3, 4];
numbers.push(5);
console.log(numbers); // should log: [1, 2, 3, 4, 5]

numbers.pop();
console.log(numbers); // should log: [1, 2, 3, 4]

Lot’s of crucial learning there!

Now time for a challenge :)

In this challenge create a variable called fourthItem and assign it the value of the fourth item in the horror array ('Ghostface'). Then console.log fourthItem to see the output.

11. Challenge: Arrays — Adding Elements —

To practice adding elements to an array in this challenge you’ll use a built-in JavaScript method to add another show to the netflixShows array. Then log your updated array to the console.

12. Challenge: For Loops — Fundamentals

Often times you’ll find yourself needing to repeat the same operation over and over. While it’s tempting to simply write out the logic by hand, there is a better way! Let’s talk about iteration statements or loops. Loops will allow you to write a block of code once, and repeat the execution of the code for a given number of times. There are a few different kinds of iteration statements in Javascript — but for now we’ll cover only the most basic one: a forloop.

Let’s take a look at the syntax:

for (let i = 0; i < 10; i++) {
// code to be repeated goes here
}

There are a few things going on here so let’s break this down. First off, we’re using the for keyword to tell JavaScript that we want to run a loop. Immediately after the for keyword, we’ll enclose a few conditions for the loop inside of a set of parentheses, separated by semicolons. for loops accept three conditions:

1. Initial Expression — this is simply a place for you to initialize any JavaScript expression (an expression is a bit of JavaScript code that evaluates to a single value). Most often, it’s used to declare a variable, in this case i, that will be used as a counter for how many times the loop iterates. You should definitely follow this pattern until you’re comfortable enough to try a more complex expression.

2. Conditional Expression — this should be a JavaScript expression that will evaluate to a true or false. In the example above, since i , which is currently set to 0 is indeed less than 10 , this will evaluate to true and execute the block of code inside of the curly braces {}. This condition is checked every time the loop runs, just before the code is executed. If this condition ever evaluates to false, the loop will stop and JavaScript will move on with executing code below it.

3. Increment Expression — this should be an expression that increments your loop counter as the loop runs. It will be executed after the code inside of the loop block is run. In the example above, i++ is shorthand for increasing the value of i by 1.

Finally, once you’ve declared your loop conditions, you can insert the code that you want to be repeated inside of the curly braces {}. Again this code will be executed until your condition (#2 above) evaluates to false.

Looping through Arrays

Now that we know how to write a loop, let’s talk about how to loop through an array.

Remember, a value in an array can be accessed using the index of its position in the array: myArray[0]. With this in mind, we can utilize our loop counter, i to access each successive element in an array as the loop runs. Let's take a look at an example:

const myArray = ['string1', 'string2', 'string3'];

for (let i = 0; i < myArray.length; i++) {
console.log( myArray[i] );
}

Let’s break this down a bit. We’ve declared a variable myArray and have assigned it a value of an array containing a few strings.

Next, we’ve declared a for loop that will run as long as i is less than the length of the array (remember, we're incrementing i by 1 each time the loop runs). Now, since both the arrays' indexes and i start at 0 and increment by 1, we can effectively use i to lookup the elements in the array in order, where i will correspond to an index in the array.

Now that the idea of using i as an index has been established, inside of our loops code block we can reference the current element of an array like so: myArray[i].

Okay time to test your understanding of this.

Using a for loop, decrement countDownby one each time the loop runs until it equals 0, making use of looping functionality instead of logging each number separately.

For loops and looping through arrays are going to show up everywhere in JavaScript and really any type of programming, so be sure these concepts really stick.

Let’s keep practicing —

13. Challenge: For Loops and Arrays -

In this challenge we’ll have you do a couple things —

  • Iterate through the synonyms array using a for loop, pushing a greeting string with the format "Have a [synonym] day!" into the greetings array.
  • Use a second for loop to iterate through the greetings and console.log() each greetings.

14. Challenge: For Loops and Array Indices —

In this challenge you’ll really need to test your understanding of for loops as well as arrays.

You’ll be given 3 different arrays, one of first names, last names and places. Imagine that each array element at a certain index corresponds to one user.

For example, my friends are Mary Snow, Kris Bowles, and Janelle Wong. I have two arrays, one of first names and one of last names. In order to get the full name of my friend, I need to access both arrays

onst firstNames = ["Mary", "Kris", "Janelle"];
const lastNames = ["Snow", "Bowles", "Wong"];

console.log(firstNames[1]) // returns Kris
console.log(lastNames[1]) // returns Bowles

For this challenge, you’ll loop through the arrays and push a string with the format “My name is [firstName] [lastName] and I am from [place]” into the array holding the respective bios.

15. Challenge: For Loops — Calculating Array Elements —

In this challenge you are given an array of five numbers called increaseByTwo. Use a for loop to iterate through the array and increase each number by two.

16. Challenge: While Loops — Fundamentals

Okay enough of for loops! Let’s take a look at another kind of iteration statement — a while loop. Though for loops are the more popularly used loop, while loops are also good to know.

JavaScript’s thread of execution will repeatedly process the code block until the while loop’s conditional expression evaluates to false. **Be careful to avoid an infinite loop!**

Let’s try it in a challenge…

Here you’ll need to use a while loop to increment count by 2 on each repetition of the block of code. Run the code block of your while loop until count is 8.

17. Challenge: While Loops — Conditional Expression -

In this challenge you’ll initialize a variable addThis to 0 and a variable sum to 0. Use a while loop to repeat a code block as long as addThis is less than 10. In the code block, add the value of addThis to sum, then increment addThis by 1. After the while loop runs, the value of sum should be the sum of the numbers 0 through 9.

18. Challenge: Control Flow — if statements

Sometimes there are certain conditions that need to be met in order for an event to occur. Let’s take dating as an example. If going out on a first date is a horrible experience, then there won’t be a second date. If the first date is wonderful, then there will probably be a second date. We use this same kind of logic in programming.

Using an if statement, we can execute a block of code if the condition inside the parentheses is met.

if (5 > 2) {
console.log("Math still works!"); // 'Math still works!'
}

If we wanted to chain more if statements together, we could use an else if block. In the example below, four is not less than two so we don't run the block of code inside the if statement. Next, we move to the else if statement. That condition is true, so the code runs.

if (4 < 2) {
console.log("This shouldn't log");
} else if (4 > 2) {
console.log("This should log"); // 'This should log'
}

You can also use an else statement to catch anything that your if and else if conditions don't meet.

let day = "Christmas";
if (day === "work day") {
console.log("Time to go to work!");
} else if (day === "sick day") {
console.log("Stay home and rest up!");
} else {
console.log("Enjoy your holiday!");
}

In the code above we have specific conditions for sick days and work days. However, there are other days that have special conditions. We don’t want to write a condition for every holiday; that would take too long. Instead we use an elseblock to catch those cases.

Control flow — if/else statements are incredibly important to understand.

Let’s dive into a challenge to see if everything is sticking…

In this challenge you’ll use an if statement to check if num is greater than 100. If num is greater than 100, reassign the value of final to null. Otherwise, set final to be two times the value of num.

Learn more about null here.

19. Challenge: fizzbuzz —

Fizzbuzz is an incredibly classic JavaScript algorithm.

To solve it you’ll need to use a loop to iterate through the numbers 1 through 16. Push each number into fb, but push the string "fizz" in place of numbers divisible by 3, "buzz" in place of numbers divisible by 5, and "fizzbuzz" in place of numbers divisible by both 3 and 5.

Log fb to the console to see the output.

Hint: Check out the remainder/modulo operator: %.

20. Solution: fizzbuzz 

We don’t provide solutions to all problems on CSX; we feel the best way to learn a new skill is by persevering through the “hard learning.”

However, we are always available to discuss best practices, and if you want to talk through your solution, you can share your code with us by emailing us at csx@codesmith.io.

We do though offer solution videos to multiple problems per unit where a CSX Mentor will explain their solution to a certain challenge.

Fizzbuzz is one of those solutions, so be sure to watch Xavyr explain his solution.

21. Challenge: Control Flow and Iteration

In this challenge you’ll iterate through the array and multiply a number by 10 if it is greater than or equal to 5.

22. Challenge: Objects — Examining Properties -

Objects are data structures used to store related data represented with keys and associated values. Keys are also referred to as properties. Keys give us an easy way to reference the values, so they are almost always descriptive strings. Values can be any valid data type: a number, string, array, even other objects that contain even more objects!

We can iterate through an object’s properties in much the same way we iterate through the elements of an array, though the implementation is a bit different. You should find some time researching for... in and Object.keysbefore continuing with these challenges.

In this challenge you’re provided with an object called checkObj. Using a for... in loop, determine if the object contains the property foundNum. If it exists, reassign the value of found to 1.

23. Challenge: Objects — Iterating with for… in —

You are provided with an empty array called objToArray. Using a for... inloop, fill the array with all of the numbers from the checkObj object if they are greater than or equal to 2.

24. Challenge: Objects — Iterating with a for loop —

You’ve almost made it through the CSX Precourse Unit! Keep it up :)

In this challenge, use the Object.values() method to return an array of checkObj's values, and assign this array to a constant called objToArray. Next, use a for loop to iterate through objToArray and determine if any of the numbers are divisible by 6. If so, reassign the value of divBy6 to true.

25. Challenge: Objects — Nested Arrays —

In this exercise you are provided with an empty array called nestedArr. Using a for loop starting at index 0, add 5 subarrays to nestedArr, with each nested array containing the string 'loop' concatenated with the corresponding index in nestedArr as its first element, and the index as its second element.

Example of a subarray: ['loop3', 3].

26. Challenge: Objects — Adding Properties

For this challenge, you are provided with an array, possibleIterable. Using a for loop, build out the object divByThree so that each key is an element of nestedArraythat is divisible by three. The value of each key should be the array index at which that key can be found in possibleIterable.

27. Challenge: Objects — Evaluating Keys —

YOU’VE MADE IT TO THE FINAL CHALLENGE!!!!

In this challenge you are given an object called sumMe containing several key/value pairs and a variable called total whose initial value is 0. Using a for... in loop, iterate through the keys of sumMe; if the value corresponding to a key is a number, add it to total.

Wow — what a ride it’s been.

Repetition is really crucial for grasping JavaScript fundamentals, so even if you’ve completed these challenges, we suggest finding more challenges that test similar concepts and working on those. You’ll thank yourself later when the fundamentals are clear, so you can focus on solving more advanced challenges and doing what we all love doing best: building with code.

28. Workshop — JS the Easier Parts — Variables, Data Types, and Control Flow (Schedule in Person) —

As we just learned in the CSX Precourse, JavaScript is just like learning a new language and there’s so much to know!

Codesmith workshops are a great way to meet other coders, form study groups, and help each other grow.

We also do pair programming, which will help you take your learning to the next level — check out the CSX bonus unit on pairing for more information.

Your first workshop at CSX is JS the Easier Parts — Variables, Data Types, and Control Flow — Schedule your free session here.

For more videos, challenges, and solutions like this be sure to make a free account on CSX, Codesmith’s free online JavaScript learning journey!

And on to the next CSX Unit: Functions and Execution Context to continue on the journey of mastering JavaScript.