Currently, I’m going through freeCodeCamp’s new learning curriculum. I just finished the first part, which was the Responsive Web Design Certification course.
While going through said course, I took notes on the following:
CSS Grid
CSS Flexbox
I also made several responsive web design projects as part of the course.
The second part of the freeCodeCamp curriculum was the Javascript Algorithms And Data Structures Certification course. The following is a list of all the notes I took while going through said course:
Learn to code with free online courses, programming projects, and interview preparation for developer jobs.
freeCodeCamp Object Oriented Programming Notes Part 1
I’m currently going through the new freeCodeCamp learning curriculum. I just finished the first part, which was the Responsive Web Design Certification course. Part of this course was to make responsive web design projects.
Check out the following articles for the notes I took while going through said 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. Check out this post for a list of all the notes I took while going through the first 5 parts of this course.
The sixth part of the JavaScript course is Basic Algorithm Scripting. Check out the notes I took while going through this course:
Part 1
Part 2
The seventh part of the JavaScript course is Object Oriented Programming. This is part 1 of the notes I took while going through said course.
At its core, software development solves a problem or achieves a result with computation. The software development process first defines a problem, then presents a solution. Object oriented programming is one of several major approaches to the software development process.
object oriented programming organizes code into object definitions. These are sometimes called classes, and they group together data with related behavior. The data is an object's attributes, and the behavior (or functions) are methods.
The object structure makes it flexible within a program. Objects can transfer information by calling and passing data to another object's methods. Also, new classes can receive, or inherit, all the features from a base or parent class. This helps to reduce repeated code.
Your choice of programming approach depends on a few factors. These include the type of problem, as well as how you want to structure your data and algorithms.
Create a Basic JavaScript Object
properties, define what makes up an object. Note that similar objects share the same properties, but may have different values for those properties. For example, all cars have wheels, but not all cars have the same number of wheels.
let owl = { name: "Hedwig", color: "white", owner: "Harry Potter", numLegs: 2 };
Use Dot Notation to Access the Properties of an Object
let mainCharacter = { name: "Harry Potter", age: 11, wizard: true, address: "4 Privet Drive", school: "Hogwarts School of Witchcraft and Wizardry" }; console.log(mainCharacter.name); //returns Harry Potter
Create a Method on an Object
let sirius = { name: "Sirius Black", wizard: true, pureblood: true, traitor: false, godson: "Harry Potter", brother: "Regulus Black", mother: "Walburga Black", father: "Orion Black", info: function() { return `${sirius.name} is the son of ${sirius.mother} and ${sirius.father}. He is the older brother of ${sirius.brother} and the godfather of ${sirius.godson}.`; } }; sirius.info(); //returns Sirius Black is the son of Walburga Black and Orion Black. He is the older brother of Regulus Black and the godfather of Harry Potter. console.log(sirius.info());
//object with method //function in method uses arrow functions var pansy = { firstName: "Pansy", lastName: "Parkinson", wizard: true, age: 11, house: "Slytherin", bloodStatus: "Pureblood", friends: ["Draco", "Daphne", "Blaise", "Theo"], info: () => `${pansy.firstName} ${pansy.lastName} is a ${pansy.house} ${pansy.bloodStatus} wizard.` }; console.log(pansy.info()); //returns Pansy Parkinson is a Slytherin Pureblood wizard.
Make Code More Reusable with the this Keyword
In the current context, this refers to the object that the method is associated with: duck.
If the object's name is changed to mallard, it is not necessary to find all the references to duck in the code. It makes the code reusable and easier to read.
let luna = { name: "Luna Lovegood", house: "Ravenclaw", friend: "Ginny Weasley", father: "Xenophilius Lovegood", info: function() { return `${this.name} is a ${this.house} student. Her father's name is ${this.father}. ${this.friend} is one of her friends.`; } }; console.log(luna.info()); //returns Luna Lovegood is a Ravenclaw student. Her father's name is Xenophilius Lovegood. Ginny Weasley is one of her friends.
Note: can’t use arrow functions with this keyword.
An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.
Refer to this for more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Define a Constructor Function
Constructors are functions that create new objects. They define properties and behaviors that will belong to the new object. Think of them as a blueprint for the creation of new objects.
function Cat() { this.name = "Crookshanks"; this.color = "Ginger"; this.numLegs = 4; this.species = "Half-Kneazle"; this.owner = "Hermione Granger"; } let hermionesCat = new Cat();
function Auror() { this.headquarters = "Ministry of Magic", this.enemies = ["Voldemort", "Death Eaters"], this.description = "Aurors protect the Wizarding World from Dark Wizards." } let nymphadoraTonks = new Auror(); console.log(nymphadoraTonks.enemies); //returns (2) ["Voldemort", "Death Eaters"] let kingsleyShacklebolt = new Auror(); console.log(kingsleyShacklebolt.description); //returns Aurors protect the Wizarding World from Dark Wizards.
Extend Constructors to Receive Arguments
The constructor is more flexible. It's now possible to define the properties for each Bird at the time it is created, which is one way that JavaScript constructors are so useful. They group objects together based on shared characteristics and behavior and define a blueprint that automates their creation.
function Pets(name, species, owner) { this.name = name; this.species = species; this.owner = owner; } let nevillesPet = new Pet("Trevor", "frog", "Neville Longbottom"); let harrysPet = new Pet("Hedwig", "owl", "Harry Potter"); let hermionesPet = new Pet("Crookshanks", "cat", "Hermione Granger"); let ronsPets = new Pet("Pigwidgeon", "owl", "Ron Weasley");
function Wand(owner, wood) { this.creator = "Ollivander", this.owner = owner, this.wood = wood, this.core = "Dragon Heartstring", this.info = function() { return `This ${this.core} wand is owned by ${this.owner}. It is made from ${this.wood} wood.` } } var minervasWand = new Wand("Minerva McGonagall", "fir"); console.log(minervasWand.info()); //returns This Dragon Heartstring wand is owned by Minerva McGonagall. It is made from fir wood. var luciusWand = new Wand("Lucius Malfoy", "elm"); console.log(luciusWand.wood); //returns elm console.log(luciusWand.core); //returns Dragon Heartstring console.log(luciusWand.info()); //returns This Dragon Heartstring wand is owned by Lucius Malfoy. It is made from elm wood.
Verify an Object's Constructor with instanceof
Anytime a constructor function creates a new object, that object is said to be an instance of its constructor. JavaScript gives a convenient way to verify this with the instanceof operator. instanceof allows you to compare an object to a constructor, returning true or false based on whether or not that object was created with the constructor. Here's an example:
let Wand = function(owner, wood, core) { this.owner = owner; this.wood = wood; this.core = core; this.maker = "Ollivander"; } let harrysWand = new Wand("Harry Potter", "holly", "Phoenix feather"); harrysWand instanceof Wand; let dracosWand = new Wand("Draco malfoy", "hawthorn", "Unicorn hair"); dracosWand instanceof Wand; let minervasWand = new Wand("Minerva McGonagall", "fir", "Dragon heartstring"); minervasWand instanceof Wand;
Understand Own Properties
function Teacher(name, subject) { this.name = name; this.subject = subject; this.school = "Hogwarts School of Witchcraft and Wizardry"; } let snape = new Teacher("Severus Snape", "Potions"); let snapeProperties = []; for (let property in snape) { if (snape.hasOwnProperty(property)) { snapeProperties.push(property); } } console.log(snapeProperties); //returns ["name", "subject", "school"]
Use Prototype Properties to Reduce Duplicate Code
function HPBook(title) { this.title = title; } HPBook.prototype.author = "J.K. Rowling"; let book1 = new HPBook("Harry Potter and the Philosopher's Stone"); console.log(book1.author); //returns J.K. Rowling let book2 = new HPBook("Harry Potter and the Chamber of Secrets"); console.log(book2.author); //returns J.K. Rowling
Iterate Over All Properties
Own properties are defined directly on the object instance itself. And prototype properties are defined on the prototype.
Add all of the own properties of beagle to the array ownProps. Add all of the prototype properties of Dog to the array prototypeProps.
function Dog(name) { this.name = name; } Dog.prototype.numLegs = 4; let beagle = new Dog("Snoopy"); let ownProps = []; let prototypeProps = []; for (let property in beagle) { if (beagle.hasOwnProperty(property)) { ownProps.push(property); } else { prototypeProps.push(property); } } console.log(ownProps); //returns ["name"] console.log(prototypeProps); //returns ["numLegs"]
function QuidditchMember(name, position) { this.name = name; this.position = position; } QuidditchMember.prototype.captain = "Oliver Wood"; QuidditchMember.prototype.team = "Gryffindor"; var fred = new QuidditchMember("Fred Weasley", "Beater"); var george = new QuidditchMember("George Weasley", "Beater"); var harry = new QuidditchMember("Harry Potter", "Seeker"); var ownProps = []; var prototypeProps = []; //using ternary operators instead of if-else statement for (let property in harry) { (harry.hasOwnProperty(property)) ? ownProps.push(property) : prototypeProps.push(property); } console.log(ownProps); //returns (2) ["name", "position"] console.log(prototypeProps); //returns (2) ["captain", "team"]
function DeathEater(name, house) {
this.name = name;
this.house = house;
}
DeathEater.prototype.leader = "Voldemort";
DeathEater.prototype.description = "Followers of Voldemort";
var peter = new DeathEater("Peter Pettigrew", "Gryffindor");
var lucius = new DeathEater("Lucius Malfoy", "Slytherin");
var ownProperty = [];
var prototypeProperty = [];
for (var property in peter) {
(peter.hasOwnProperty(property)) ? ownProperty.push(property) : prototypeProperty.push(property);
}
console.log(ownProperty);
//returns (2) ["name", "house"] console.log(prototypeProperty);
//returns (2) ["leader", "description"]
Understand the Constructor Property
Since the constructor property can be overwritten, it’s generally better to use the instanceof method to check the type of an object.
Write a joinDogFraternity function that takes a candidate parameter and, using the constructor property, return true if the candidate is a Dog, otherwise return false.
function Dog(name) { this.name = name; } function joinDogFraternity(candidate) { if (candidate.constructor === Dog) { return true; } else { return false; } }
function OrderMember(name) { this.name = name; } OrderMember.prototype.title = "Order of the Phoenix"; OrderMember.prototype.leader = "Albus Dumbledore"; OrderMember.prototype.symbol = "Phoenix"; var sirius = new OrderMember("Sirius Black"); function DeathEater(name) { this.name = name; } DeathEater.prototype.leader = "Voldemort"; var peter = new DeathEater("Peter Pettigrew"); //using arrow functions and ternary operators var joinOotP = (candidate) => (candidate.constructor === OrderMember) ? true : false; console.log(joinOotP(sirius)); //returns true console.log(joinOotP(peter)); //returns false var joinVoldemort = (candidate) => (candidate.constructor === DeathEater) ? true : false; console.log(joinVoldemort(sirius)); //returns false console.log(joinVoldemort(peter)); //returns true
Change the Prototype to a New Object
Add the property numLegs and the two methods eat()and describe()to the prototype of Dog by setting the prototype to a new object.
function Dog(name) { this.name = name; } Dog.prototype = { numLegs: 4, eat: function() { console.log("dog food"); }, describe: function() { console.log("Sirius Black's animagus form is a dog."); } };
function Hufflepuff(name) { this.name = name; } Hufflepuff.prototype = { houseName: "Hufflepuff", head: "Pomona Sprout", school: "Hogwarts", info: () => `Hufflepuff's head of house is Pomona Sprout, the Hogwarts Herbology teacher.` }; var susan = new Hufflepuff("Susan Bones"); console.log(susan.houseName); //returns Hufflepuff console.log(susan.info()); //returns Hufflepuff's head of house is Pomona Sprout, the Hogwarts Herbology teacher.
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.
-= 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
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.
.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"]
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.
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