Learn to code with free online courses, programming projects, and interview preparation for developer jobs.
freeCodeCamp Basic JavaScript Course Notes Part 1
As I mentioned before, now that there’s a new freeCodeCamp learning curriculum, I resolved to go through each of the lessons and finish all of them.
I was able to finish all the Responsive Web Design courses including all the projects. Check out the following articles for more info about these projects:
Tribute Page
Survey Form
Product Landing Page
Technical Documentation Page
Personal Portfolio Webpage
Check out the following articles for the notes I took while going through the course:
Flexbox Notes
CSS Grid Notes
Now that I’m done with the Responsive Web Design Certification course, the next course is the Javascript Algorithms And Data Structures Certification course.
The first part of that course is Basic JavaScript. The following are the first part of the notes I took while going through this course:
// - in-line comment
/* */ - multi-line comment
7 data types in JavaScript
undefined
null
boolean
string - collections of characters, enclosed in quotation marks, you can use either single or double. Just make sure you start and end with the same type of quote
symbol
number - represents numeric data
object
Variables
Used to “store and manipulate data in a dynamic fashion”
Instead of using the data itself, you use the variable to point to that data
You can store any of the 7 data types in a variable
Basically, it’s a name that you use to represent the data you want to refer to
They can “store different values at different times”
Use var to create or declare a variable
Variable names can be made up of numbers, letters, and $ or _, but may not contain spaces or start with a number.
End JavaScript statements with a semi-colon (;).
assignment operator - use this to store a value in a variable
harryPotter = 11;
This assigns the Number value 11 to harryPotter.
Assignment always goes from right to left. Everything to the right of the = operator is resolved before the value is assigned to the variable to the left of the operator.
“Initialize a variable to an initial value in the same line as it is declared”
var hogwartsStudent = "Ron Weasley";
When JavaScript variables are declared, they have an initial value of undefined. If you do a mathematical operation on an undefined variable your result will be NaN which means "Not a Number". If you concatenate a string with an undefined variable, you will get a literal string of "undefined".
All variables and function names are case sensitive.
Capitalization matters.
Write variable names in camelCase, meaning “multi-word variable names have the first word in lowercase and the first letter of each subsequent word is capitalized”.
Operators
+ - used as “addition operation when placed between two numbers”
- - for subtraction
* - for multiplication
/ - for division
++ (plus plus) - used to increment or add one to a variable
- - (minus minus) - used to decrement or decrease a variable by one
% - remainder operator, this gives the remainder of the division of two numbers. “Sometimes incorrectly referred to as the "modulus" operator. It is very similar to modulus, but does not work properly with negative numbers”
+= - operator that does both a “mathematical operation and assignment in one step”
-= - same as += but this one is for subtraction
*= - for multiplication
/= - for division
i++ is the same as i = i + 1;
i- - (no space) is the same as i = i - 1;
For more info, refer to this: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment_()
We can store decimal numbers in variables too. Decimal numbers are sometimes referred to as floating point numbers or floats.
Not all real numbers can accurately be represented in floating point. This can lead to rounding errors.
var sampleDecimalNumber = 1.7;
You can multiply 2 decimals just like you can with whole numbers.
var fred = 2 * 2; var george = 2.0 * 2.5;
You can also divide decimals and whole numbers.
var padma = 4 / 2; var parvati = 5.2 / 3.3;
5 % 2 = 1 because Math.floor(5 / 2) = 2 (Quotient) 2 * 2 = 4 5 - 4 = 1 (Remainder)
In mathematics, a number can be checked to be even or odd by checking the remainder of the division of the number by 2.
17 % 2 = 1 (17 is Odd) 48 % 2 = 0 (48 is Even)
var hermione = 11 % 3; //the answer is 2
var draco = 11; draco +=5; 16 console.log(draco); //returns 16
+= is basically the same as saying draco = draco + 5
var crabbe = 10; crabbe -= 5; 5 console.log(crabbe); //returns 5
-= is basically the same as saying crabbe = crabbe - 5
goyle = goyle * 3 can be rewritten as goyle *= 3
pansy = pansy / 4 can be rewritten as pansy /= 4
String Variables
var ravenclawStudent = "Luna Lovegood";
"Luna Lovegood" is called a “string literal. It is a string because it is a series of zero or more characters enclosed in single or double quotes.”
\ - backslash, use this to escape a quote, so it won’t be considered as “an end of string quote by placing a backslash (\) in front of the quote”. This allows you to add literal quotes in your strings.
var harrysMessage = "Harry Potter said, \"Voldemort is back.\"."; harrysMessage "Harry Potter said, "Voldemort is back."." console.log(harrysMessage); Harry Potter said, "Voldemort is back.".
Another example of escaping quotes:
var chamberOfSecrets = "The message on the wall says, \"The Chamber of Secrets has been opened. Enemies of the Heir beware.\". But who is the Heir of Slytherin? Who opened the Chamber?"; console.log(chamberOfSecrets); The message on the wall says, "The Chamber of Secrets has been opened. Enemies of the Heir beware.". But who is the Heir of Slytherin? Who opened the Chamber?
var sorcerersStone = 'Harry said, "Let\'s save the Sorcerer\'s Stone." Ron and Hermione agreed with him.'; console.log(sorcerersStone); Harry said, "Let's save the Sorcerer's Stone." Ron and Hermione agreed with him.
In the above example, since the string started with single quotation marks, if you don’t use the backslash in the “let’s” and “Sorcerer’s” part, you’ll get an error because those words also use the single quotation mark. So it will be mistaken as the end of the string unless you use the backslash to escape it.
var pomonaSprout = "<a href=\"http://www.pomona-sprout.com\" target=\"_blank\">Pomona Sprout</a>"; var filiusFlitwick = '<a href="http://www.filius-flitwick.com" target="_blank">Filius Flitwick</a>';
You can also escape other characters:
var minervaMcGonagall = "Minerva McGonagall is the Head of Gryffindor House.\n\t\\She is the Hogwarts Transfiguration Professor.\n\tShe is the Deputy Headmistress of Hogwarts.\n\t\bShe is a member of the 'Order of the Phoenix'.";
The above will print out:
Concatenating Strings with Plus Operator
You can also use the plus (+) sign to concatenate strings. When used in this way, it is called the concatenation operator. Note that you will need to add the spaces yourself.
var severusSnape = "Severus Snape " + "is the" + " Hogwarts Potions Professor" + " and the " + "Head of Slytherin House" + "."; severusSnape "Severus Snape is the Hogwarts Potions Professor and the Head of Slytherin House."
The += operator can also be used to concatenate “a string onto the end of an existing string variable”
var luciusFamily = "Lucius Malfoy is the husband of Narcissa Black. "; luciusFamily += "Lucius Malfoy is the father of Draco Malfoy."; "Lucius Malfoy is the husband of Narcissa Black. Lucius Malfoy is the father of Draco Malfoy."
You ca use the concatenation operator to insert one or more variables in a string.
var firstName = "Narcissa"; var lastName = "Black"; var son = "Draco"; var husband = "Lucius"; var newLastName = "Malfoy"; var narcissaBlack = firstName + " " + lastName + " is the mother of " + son + " " + newLastName + " and the wife of " + husband + " " + newLastName; narcissaBlack "Narcissa Black is the mother of Draco Malfoy and the wife of Lucius Malfoy"
Just as we can build a string over multiple lines out of string literals, we can also append variables to a string using the plus equals (+=) operator.
var hogwartsHouse = "Slytherin"; var dracoMalfoy = "Draco Malfoy is a "; dracoMalfoy += hogwartsHouse; "Draco Malfoy is a Slytherin"
Use .length to find the length of a string.
var nymphadoraTonks = "Nymphadora Tonks"; nymphadoraTonks.length; 16
var firstNameLength = 0; var firstName = "Andromeda"; firstNameLength = firstName.length; 9
Use Bracket Notation to Find the First Character in a String
Bracket notation is a way to get a character at a specific index within a string.
Zero-based indexing - JavaScript starts counting from 0 instead of 1
var firstLetterOfFirstName = ""; var firstName = "Ted"; firstLetterOfFirstName = firstName[0]; "T"
var tedTonks = "Ted Tonks"; tedTonks[1]; "e"
String values are immutable, which means that they cannot be altered once created.
var harryPotter = "Harry"; harryPotter[0] = "B";
You can’t change the value of harryPotter to Barry because the contents of the variable harryPotter cannot be altered.
Note that this does not mean that harryPotter cannot be changed, just that the individual characters of a string literal cannot be changed. The only way to change harryPotter would be to assign it with a new string, like this:
var harryPotter = "Harry"; harryPotter = "The Boy-Who-Lived";
Use Bracket Notation to Find the Nth Character in a String
var firstName = "Bellatrix"; var secondLetterOfFirstName = firstName[1]; secondLetterOfFirstName "e"
To find the last character in a string, just subtract 1 from the string’s length.
var firstName = "Bellatrix"; var lastLetterOfFirstName = firstName[firstName.length - 1]; lastLetterOfFirstName "x"
Use Bracket Notation to Find the Nth-to-Last Character in a String
var firstName = "Bellatrix"; var thirdToLastLetterOfFirstName = firstName[firstName.length - 3]; thirdToLastLetterOfFirstName "r"
JS Word Game
function aurors(noun, adjective, verb, adverb) { var sentence= "The " + adjective + " " + noun + " " + adverb + " tried to " + verb + " the Death Eaters."; return sentence; } aurors("aurors", "brave", "capture", "quickly"); //returns The brave aurors quickly tried to capture the Death Eaters. "The brave aurors quickly tried to capture the Death Eaters."
function hermionesCat(noun, adjective, verb, adverb) { var catSentence= "Crookshanks, Hermione's " + adjective + ", ginger-colored " + noun + ", " + adverb + " " + verb + " after Wormtail, Peter Pettigrew's rat animagus form."; return catSentence; } hermionesCat("cat", "big", "ran", "quickly"); //returns Crookshanks, Hermione's big, ginger-colored cat, quickly ran after Wormtail, Peter Pettigrew's rat animagus form. "Crookshanks, Hermione's big, ginger-colored cat, quickly ran after Wormtail, Peter Pettigrew's rat animagus form."
Arrays
Used to store multiple values in one variable
Multi-dimensional Array - you can nest arrays within other arrays, an array of arrays
var marauders = ["Sirius Black", "James Potter", "Peter Pettigrew", "Remus Lupin"];
var blackFamily = [["Sirius Black", "Regulus Black"], ["Bellatrix Black", "Andromeda Black", "Narcissa Black"]];
Access Array Data with Indexes
Array indexes are written in the same bracket notation that strings use, except that instead of specifying a character, they are specifying an entry in the array. Like strings, arrays use zero-based indexing, so the first element in an array is element 0.
var ages = [11,12,13]; ages[0]; //equals 11 var data = ages[1]; //equals 12
Unlike strings, the entries of arrays are mutable and can be changed freely.
var numbers = [14,15, 16]; numbers[0] = 17; //the numbers array will now return [17, 15, 16]
Access Multi-Dimensional Arrays With Indexes
When you use brackets to access your array, the first set of brackets refers to the entries in the outer-most (the first level) array, and each additional pair of brackets refers to the next level of entries inside.
var arr = [ [1,2,3], [4,5,6], [7,8,9], [[10,11,12], 13, 14] ]; arr[3]; // equals [[10,11,12], 13, 14] arr[3][0]; // equals [10,11,12] arr[3][0][1]; // equals 11
.push()takes one or more parameters and "pushes" them onto the end of the array.
var gryffindors = ["Harry", "Ron", "Hermione"]; gryffindors.push("Neville"); //gryffindors is now ["Harry", "Ron", "Hermione", "Neville"]
var slytherins = ["Draco", ["Crabbe", "Goyle"], "Blaise", "Theo"]; slytherins.push(["Astoria", "Daphne"]); //slytherins now equals ["Draco", ["Crabbe", "Goyle"], "Blaise", "Theo", ["Astoria", "Daphne"]]
.pop()is used to "pop" a value off of the end of an array. We can store this "popped off" value by assigning it to a variable. In other words, .pop()removes the last element from an array and returns that element.
Any type of entry can be "popped" off of an array - numbers, strings, even nested arrays.
var hogwartsFounders = ["Rowena", "Helga", "Salazar", "Godric", "Helena"]; var helenaRavenclaw = hogwartsFounders.pop(); console.log(helenaRavenclaw); //returns Helena console.log(hogwartsFounders); //returns ["Rowena", "Helga", "Salazar", "Godric"]
var hogwartsStudents = [["Harry", 11], ["Ron", 12], ["Hermione", 13], ["Cho", 14]]; var ravenclawStudent = hogwartsStudents.pop(); console.log(ravenclawStudent); //returns Cho, 14 console.log(hogwartsStudents); //returns [["Harry", 11], ["Ron", 12], ["Hermione", 13]]
.shift() - opposite of .pop(). This one removes the first element from an array.
var marauders = ["Peter", "Sirius", "James", "Remus"]; var traitor = marauders.shift(); console.log(traitor); //returns Peter console.log(marauders); //returns Sirius, James, Remus
.unshift() - similar to .push(). This one adds elements at the beginning of an array.
var triwizardChampions = ["Viktor", "Fleur", "Cedric"]; triwizardChampions.unshift("Harry"); console.log(triwizardChampions); //returns Harry, Viktor, Fleur, Cedric
var triwizardChampions = [["Cedric", "Hogwarts"], ["Viktor", "Durmstrang"], ["Fleur", "Beauxbatons"]]; triwizardChampions.unshift(["Harry", "Hogwarts"]); console.log(triwizardChampions); //returns [["Harry", "Hogwarts"], ["Cedric", "Hogwarts"], ["Viktor", "Durmstrang"], ["Fleur", "Beauxbatons"]]
Multi-Dimensional Array Shopping List
var hogwartsShoppingList = [["Work Robes", 3], ["Pointed Hat", 1], ["Dragon Hide Gloves", 1], ["Winter Cloak", 1], ["Cauldron", 1], ["Wand", 1], ["Chocolate Frogs", 5], ["Cauldron Cakes", 10]];
Functions
function welcomeMessage() { console.log("Hello, welcome to Hogwarts School of Witchcraft and Wizardry."); } welcomeMessage(); //each time this function is called, it will print out the sentence: "Hello, welcome to Hogwarts School of Witchcraft and Wizardry." on the dev console.
All of the code between the curly braces will be executed every time the function is called.
Passing Values to Functions with Arguments
Parameters are variables that act as placeholders for the values that are to be input to a function when it is called. When a function is defined, it is typically defined along with one or more parameters. The actual values that are input (or "passed") into a function when it is called are known as arguments.
Here is an example of a function with 2 parameters:
function siblings(sibling1, sibling2) { console.log(sibling1 + " and " + sibling2 + " are siblings."); } siblings("Fred Weasley", "George Weasley"); //returns Fred Weasley and George Weasley are siblings. siblings("Parvati Patil", "Padma Patil"); //returns Parvati Patil and Padma Patil are siblings.
function voldemortsHorcruxes(horcrux1, horcrux2) { console.log(`${horcrux1} and ${horcrux2} are 2 of the Dark Lord Voldemort's Horcruxes.`); } voldemortsHorcruxes("Tom Riddle's Diary", "Marvolo Gaunt's Ring"); //returns Tom Riddle's Diary and Marvolo Gaunt's Ring are 2 of the Dark Lord Voldemort's Horcruxes. voldemortsHorcruxes("Salazar Slytherin's Locket", "Helga Hufflepuff's Cup"); //returns Salazar Slytherin's Locket and Helga Hufflepuff's Cup are 2 of the Dark Lord Voldemort's Horcruxes.
function functionWithArgs(num1, num2) { console.log(num1 + num2); } functionWithArgs(1, 2); //returns 3 functionWithArgs(7, 9); //returns 16
Global Scope and Functions
Scope refers to the visibility of variables. Variables which are defined outside of a function block have Global scope. This means, they can be seen everywhere in your JavaScript code.
Variables which are used without the var keyword are automatically created in the global scope. This can create unintended consequences elsewhere in your code or when running a function again. You should always declare your variables with var.
Local Scope and Functions
Variables which are declared within a function, as well as the function parameters have local scope. That means, they are only visible within that function.
function darkLord() { var tomRiddle = "Dark Lord Voldemort"; console.log(tomRiddle); } darkLord(); //logs "Dark Lord Voldemort" console.log(tomRiddle); //returns an error: tomRiddle is not defined because tomRiddle is not defined outside the function
Global vs Local Scope in Functions
It is possible to have both local and global variables with the same name. When you do this, the local variable takes precedence over the global variable.
var diadem = "Rowena Ravenclaw's Diadem"; function horcrux() { var diadem = "Voldemort's Horcrux"; return diadem; } horcrux(); //will return "Voldemort's Horcrux" because the local version of the variable diadem is present
Return a Value from a Function with Return
We can pass values into a function with arguments. You can use a return statement to send a value back out of a function.
function plusThree(num) { return num + 3; } var answer = plusThree(5); // 8
plusThree takes an argument for num and returns a value equal to num + 3.
Understanding Undefined Value returned from a Function
A function can include the return statement but it does not have to. In the case that the function doesn't have a return statement, when you call it, the function processes the inner code but the returned value is undefined.
Assignment with a Returned Value
Everything to the right of the equal sign is resolved before the value is assigned. This means we can take the return value of a function and assign it to a variable.
In Computer Science a queue is an abstract Data Structure where items are kept in order. New items can be added at the back of the queue and old items are taken off from the front of the queue.
Write a function which takes an array and a string as arguments. Add the string to the end of the array, then remove the first element of the array. The function should then return the element that was removed.
var weasleys = ["Harry", "Arthur", "Molly", "Ginny"]; function weasleyFamily(weasleysArray, weasleyBrothers) { weasleysArray.push(weasleyBrothers); //adds the value of weasleyBrothers to the end of the weasleys array return weasleysArray.shift(); //removes the first element of the weasleys array (in this case, it will remove "Harry") } console.log(weasleyFamily(weasleys, "Bill"));
The function weasleyFamily will return the element that was removed. In this case, it will return “Harry”.
console.log(weasleys); //will now return ["Arthur", "Molly", "Ginny", "Bill"]
Boolean Values
data type
can only be either true or false values
never written with quotes
function voldemortIsBack() { return true; //this function will return true } function harryIsLying() { return false; //this function will return false }
Use Conditional Logic with If Statements
Use if statements to make decisions in code
the keyword if will execute the code inside the curly braces if the conditions have been met
the conditions are Boolean conditions and can only be either true or false
so if the condition evaluates to true, then the if statement will run
if the condition is false, then the if statement will not run
function chamberOfSecrets(open) { if (open) { return "It's true. The Chamber of Secrets has been opened."; } return "It's false. The Chamber of Secrets has not been opened."; } chamberOfSecrets(true); //returns "It's true. The Chamber of Secrets has been opened." chamberOfSecrets(false); //returns "It's false. The Chamber of Secrets has not been opened."
If chamberOfSecrets is called with a value of true, then the if statement evaluates whether open is true or not. Since it’s true, the function returns that the chamber has been opened.
If we call chamberOfSecrets with a value of false, then the open is not true, so the if statement in curly braces will not be run or executed. This is why the function will return that the chamber has not been opened.
Comparison with the Equality Operator
There are many Comparison Operators in JavaScript. All of these operators return a boolean true or false value.
Equality operator == (double equals sign)
The equality operator compares two values and returns true if they're equivalent or false if they are not. Note that equality is different from assignment (=), which assigns the value at the right of the operator to a variable in the left.
The equality operator “attempts to convert both values being compared to a common type”
If the values being compared are not of the same type, the equality operator will perform a type conversion, and then evaluate the values.
function harrysAge(age) { if (age == 11) { return "Harry's age is equal to 11."; } return "Harry's age is not equal to 11"; }
Strict Equality Operator === (triple equals sign)
does not perform a type conversion
If the values being compared have different types, they are considered unequal, and the strict equality operator will return false
the strict equality operator will compare both the data type and value as-is, without converting one type to the other
typeof operator - used to determine the type of a variable or value
typeof 3 // returns 'number' typeof '3' // returns 'string'















