Codecademy - JavaScript
Started with Codecademy Full stack engineer course to help understand web apps and dev better
1. JavaScript Syntaxes I
Voting Rights Validator by age
The most common minimum age to vote is 18. Write a function canIVote()
that takes in a number, representing the person’s age, and returns the boolean true
if they are 18 years old or older, and the boolean false
if they are not.
// Write your function here:
const canIVote = (number) => {
if (number >= 18) {
return true;
} else {
return false;
}
}
console.log(canIVote(19)) // Should print true
While loop
Return factorial of number
function factorial (num){
var result = num;
if (num===1){
return 1
} else {
while(num>1){
num--;
result = result*num
}
return result
}
}
console.log(factorial(5))
If else statements
Categorising People by age
// Write your function here:
const lifePhase = ( age ) => {
if (age>=0 && age<=3){
return 'baby';
} else if (age>3 && age < 13 ){
return 'child';
} else if (age>12 && age < 20 ){
return 'teen';
} else if (age>19 && age < 65 ){
return 'adult';
} else if (age>64 && age < 141 ){
return 'senior citizen';
} else {
return 'This is not a valid age'
}
}
console.log(lifePhase(5))
Task2:
Categorising student's grades by average grades
const finalGrade = (midterm, final, homework) => {
if ((midterm < 0 || midterm > 100) || (final < 0 || final > 100) || (homework < 0 || homework > 100)) {
return 'You have entered an invalid grade.'
}
let average = (midterm + final + homework) / 3
if (average < 60) {
return 'F'
}
else if (average < 70) {
return 'D'
}
else if (average < 80) {
return 'C'
}
else if (average < 90) {
return 'B'
} else {
return 'A'
}
}
ja
Taking inputs
Write a function, reportingForDuty()
, that has two string parameters, rank
and lastName
, and returns a string in the following format: ‘rank lastName reporting for duty!’
const reportingForDuty = (rank, lastName) => {
return `${rank} ${lastName} reporting for duty!`;
}
console.log(reportingForDuty('Private', 'Fido'))
Arithmetic if else
Though an object’s mass remains consistent throughout the universe, weight is determined by the force of gravity on an object. Since different planets have different gravity, the same object would weigh different amounts on each of those planets! Cool, huh?
Write a function, calculateWeight()
. It should:
have two parameters:
earthWeight
andplanet
expect
earthWeight
to be a numberexpect
planet
to be a stringreturn a number representing what that Earth-weight would equate to on the
planet
passed in.
Use parseInt( ...) to convert to integer
String(...) to convert to string
Handle the following cases:
'Mercury'
weight = earthWeight
* 0.378
'Venus'
weight = earthWeight
* 0.907
'Mars'
weight = earthWeight
* 0.377
'Jupiter'
weight = earthWeight
* 2.36
'Saturn'
weight = earthWeight
* 0.916
For all other inputs, return 'Invalid Planet Entry. Try: Mercury, Venus, Mars, Jupiter, or Saturn.'
const calculateWeight=(earthWeight, planet)=>{
earthWeight = parseInt(earthWeight);
planet = String(planet);
if(planet == 'Mercury'){
return earthWeight*0.378;
} else if (planet == 'Venus'){
return earthWeight*0.907;
} else if (planet == 'Mars'){
return earthWeight*0.377;
}else if (planet =='Jupiter'){
return earthWeight*2.36;
} else if(planet =='Saturn'){
return earthWeight*0.916;
} else {
return 'Invalid Planet Entry. Try: Mercury, Venus, Mars, Jupiter, or Saturn.';
}
}
console.log(calculateWeight(100, 'Jupiter')) // Should print 236
howold()
if else loops again
/*
Our solution is written as a function expression and uses string interpolation, but it would be equally acceptable to use a function declaration and/or string concatenation
*/
const howOld = (age, year) => {
// The following two lines make it so that our function always knows the current year.
let dateToday = new Date();
let thisYear = dateToday.getFullYear();
// It is totally ok if your function used the current year directly!
const yearDifference = year - thisYear
const newAge = age + yearDifference
if (newAge > age) {
return `You will be ${newAge} in the year ${year}`
} else if (newAge < 0) {
return `The year ${year} was ${-newAge} years before you were born`
} else {
return `You were ${newAge} in the year ${year}`
}
}
emoticon practice
const toEmoticon = (x) =>{
switch (x){
case 'shrug' :
return '|_{"}_|';
case 'smiley face' :
return ':)';
case 'frowny face' :
return ':(';
case 'winky face' :
return ';)';
case 'heart' :
return '<3';
default:
return '|_(* ~ *)_|';
}
}
// Uncomment the line below when you're ready to try out your function
console.log(toEmoticon("shrug"))
Project 1 : Number Guesser
Create a compareGuesses()
function. This function will be called each round to determine which guess is closest to the target number.
This function:
Has three parameters representing the user (human) guess, a computer guess, and the secret target number to be guessed.
Determines which player (human or computer) wins based on which guess is closest to the target. If both players are tied, the human user should win.
Return
true
if the human player wins, andfalse
if the computer player wins.
let humanScore = 0;
let computerScore = 0;
let currentRoundNumber = 1;
// Write your code below:
const generateTarget = () =>{
return Math.floor(Math.random()*10);
}
const compareGuesses = (human,com,secretnum) =>{
let diffhuman = Math.abs(human - secretnum);
let diffcom = Math.abs(com - secretnum);
if(diffhuman < diffcom ){
return true;
} else if (diffhuman == diffcom) {
return true;
} else {
return false;
}}
const updateScore = (i) =>{
if (i == 'human'){
humanScore +=1;
} else if(i =='computer'){
computerScore +=1;
}
}
const advanceRound = () =>{
currentRoundNumber +=1
}

Capitalize Words in String
function capitalizeASingleWord(word) {
//console.log(word)
if (word.match(' ')) {
//console.log('Word value inside of if statement: ' + word);
return null;
}
let firstLetter = word.charAt(0);
const restOfWord = word.slice(1);
firstLetter = firstLetter.toUpperCase();
return firstLetter + restOfWord;
}
// Should return "Hey"
console.log("capitalizeASingleWord('hey') returns: " + capitalizeASingleWord('hey'));
// Should return null
console.log("capitalizeASingleWord('hey ho') returns: " + capitalizeASingleWord('hey ho'));
2. JavaScript Syntaxes II
Advanced Objects
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects
const robot = {
model: 'SAL-1000',
mobile: true,
sentient: false,
armor: 'Steel-plated',
energyLevel: 75
};
// .keys takes the keys of the object, argument must be object name
const robotKeys = Object.keys(robot);
console.log(robotKeys);
//entries create an array with the keys and values of the objects, argument same as object name
const robotEntries = Object.entries(robot)
console.log(robotEntries);
// Declare newRobot below this line:
const newRobot = Object.assign({laserBlaster: true, voiceRecognition: true}, robot)
console.log(newRobot);
Arrays Review:
Arrays are lists that store data in JavaScript.
Arrays are created with brackets
[]
.Each item inside of an array is at a numbered position, or index, starting at
0
.We can access one item in an array using its index, with syntax like:
myArray[0]
.We can also change an item in an array using its index, with syntax like
myArray[0] = 'new string'
;Arrays have a
length
property, which allows you to see how many items are in an array.Arrays have their own methods, including
.push()
and.pop()
, which add and remove items from an array, respectively.Arrays have many methods that perform different tasks, such as
.slice()
and.shift()
, you can find documentation at the Mozilla Developer Network website.Some built-in methods are mutating, meaning the method will change the array, while others are not mutating. You can always check the documentation.
Variables that contain arrays can be declared with
let
orconst
. Even when declared withconst
, arrays are still mutable. However, a variable declared withconst
cannot be reassigned.Arrays mutated inside of a function will keep that change even outside the function.
Arrays can be nested inside other arrays.
To access elements in nested arrays chain indices using bracket notation.
Using JavaScript on the Console ( CTRL + SHIFT + J)

Rather than typing
document.querySelector()
to select an element, you can type$()
. This syntax is inspired by jQuery, but it's not actually jQuery. It's just an alias fordocument.querySelector()
.debug(function)
effectively sets a breakpoint on the first line of that function.keys(object)
returns an array containing the keys of the specified object.
3. Node.js & its Global Objects
for writing server side JS code that runs in a computer itself instead of a browser
is written in C, C++ and JavaScript, built on open-source V8 JS engine which powers chrome (JS browser)
Node Global Objects
Node provides access to several important global objects for use with Node program files. When writing a file that will run in a Node environment, these variables will be accessible in the global scope of your file.
module
is an object referring to the functionality that will be exported from a file. In Node, each file is treated as a module, including:File System, OS, and Path for interacting with the file system, operating system, and file/directory paths.
require()
is a function used to import modules from other files or Node packages.process
is an object referencing to the actual computer process running a Node program and allows for access to command-line arguments and much more.
const fs = require('fs');
fs.readFile('./script.js', function(error, data) {
// error is null if no error occurred, but an Error object if it did
if (error) {
throw error;
}
// the file data will be passed into the callback if no error was thrown
console.log(data);
});
In this example, we are using Node’s built-in fs
module to read a script.js file. The callback function is called after the file-reading operation is completed. If an error occurred, it will be passed in as error
and thrown. If it doesn’t exist, the retrieved data from the file reading operation is logged to the console.
Running Node in Computer
Must be in same folder as the js script
node <name of file: for example scipt.js>
Node as a REPL (Read Eval Print Loop)
run REPL by typing node and press enter
interactive JavaScript environment

Use .load to load JS files (existing) into the REPL
$ node
> .load ./script.js
var a = 'Node REPL is fun!';
> a
'Node REPL is fun!'
This ensures the variables are accessible in the REPL
npm/yarn = package manager for Node
replit = inbrowser IDE for projects
Last updated