These are notes taken during self-learning sessions on the freeCodeCamp platform.
This notebook contains an overview of the fundamentals of JavaScript including variables, arrays, loops and functions.
Notes: brief records written down to aid the memory.
Last update: 2021/05/31 (ongoing changes)
Declare JavaScript variables
JavaScript has 8 data types: undefined
, null
, boolean
, string
, symbol
, bigint
, number
, object
.
Variables allow computers to store and manipulate data. Declare a variable by using the word var.
End statements with semicolons.
Storing values with the assignment operator
Store a value in a variable with the assignment operator =
.
Calculations are firstly performed on the right side of =
before the value is assigned to the left side.
Assigning the value of one variable to another
The value of one variable can be assigned to another variable by using the assignment operator.
Initializing variables with the asssignment operator
It’s totally right to attribute value to a variable in the same line that it is declared.
Understanding uninitialized variables
New variables 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
.
Understanding case sensitivity in variables
All variables and function names are case sensitive.
Capitalization is important.
Multi-word variable names have the first word in lowercase and the first letter of each subsequent word is capitalized, like camelCase.
Add two numbers with JavaScript
Number is a data type that represents numeric data.
Use +
as a symbol for an addition operator when placed between two numbers.
Substract one number from another
Use -
as symbol for substraction.
Multiply two numbers
Use *
for multiplication of 2 numbers.
Divide one number by another
Use /
for division.
Increment a number
Use ++
to increment or add 1 to a variable.
i++;
equals i=i+1;
Decrement a number
Decrease a variable by 1 with --
.
Create decimal numbers
Decimal numbers can also be called floating point or floats and be stored in variables as value.
Multiply two decimals
Decimal numebrs can be multiplied like the whole numbers.
Divide one decimal by another
Finding a remainder
%
is the remainder operator that gives the remainder of the division of two numbers.
Remainder division by 2 will determine if a number is Odd or Even.
Compound assignment with augmented addition
The +=
operator is used to add by addition and assign directly a value to a variable.
Compound assignment with augmented substraction
The operator -=
substracts a number from a variable.
Compound assignment with augmented multiplication
*=
multiplies a variable by a number.
Compound assignment with augmented division
/=
divides a variable by another number.
Declaring string variables
A string is a series of zero or more characters enclosed in single or double quotes.
Escaping literal quotes in strings
Place a backslash \
in front of the quote so that the quote "
appears inside the string.
Quoting strings with single quotes
Single and double quotes work the same.
A string has the exact kind of quote at the beginning and the end.
One special use case is when <a>
is present. Use single quote '
for outer quotes.
Escape sequences in strings
Reasons to use escaping characters : usage of special characters such as carriage return \r
(or new line \n
or tab \t
) and represent multiple quotes in a string without misrepresentation.
Concatenating strings with plus operator
The concatenating operator is the +
operator used with a String
value.
Concatenating strings with the plus equals operator
concatenate: linked together in a chain or series.
Use +=
to concatenate a string onto the end of an existing string variable.
Constructing strings with variables
One or more variables can be inserted into a string by using the concatenation operator +
.
Appending variables to strings
It is possible to append more than one variables to a string by using +=
.
Find the length of a string
To know the length of a string value, you write .length
after the string variable or string literal.
var firstName = "Charles";
var firstLetter = firstName[0];
Understand string immutability
immutable: can’t be altered after creation.
String values are immutable.
You can not change an individual character of a string.
The only way to change this string is to assign it with a whole new string.
Use bracket notation to find the Nth character in a string
Bracket notation []
is necessary to get the character at any position inside a string.
Use bracket notation to find the last character in a string
Substract one from the string’s length in order to get the last letter. .length - 1
.
Use bracket notation to find the Nth-to-last character in a string
Use .lenght - nth
to get the value of the nth-to-last caharacter in a string value.
Word blanks
Mad Libs is a game of filling words in the missing pieces of a sentence.
array
.
var sandwich = ["peanut butter", "bread", 2021]
var myArray = [["jump", 100],["dance", 150], ["walk", 50]];
Access array data with indexes
Access to data inside arrays is done with indexes.
array indexes have the same bracket notation as strings and are zero-based.
var myData = myArray[0];
Modify array data with indexes
Entries of arrays are mutable.
myArray[0] = 45;
Access mutli-dimensional arrays with indexes
Multi-dimensional arrays are an array of arrays.
Manipulate arrays with push()
.push()
function is used to append data at the end of an array.
.push()
takes one or more parameters.
Manipulate arrays with pop()
.pop()
function is used to pop a value off of the end of an array which will be store by assigning it to a variable.
Manipulate arrays with shift()
.shift()
function removes the first element from an array.
Manipulate arrays with unshift()
.unshift()
function is used to add elements in front of an array.
var myList = [["peanuts", 10],["books", 9],["shirts", 8],["lamps", 7],["shoes", 7],["watches", 6]];
functionName();
.
function functionName() {
console.log("Hello World");
}
function testFun(param1, param2) {
console.log(param1, param2);
}
function functionWithArgs(param1, param2) {
console.log(param1 + param2);
};
functionWithArgs(144, 256);
Global scope and functions
Scope means the visibility of variables.
Variables which are defined outside of a function block have global scope, meaning that they can be seen everywhere in the code.
Always declare variables with var
. Without var
, they are created in the global scope.
Local scope and functions
Variables that are only visible within a function or function parameters have local scope.
Global vs. Local scope in functions
local variable takes precedence over the global variable.
return
statement is used to send a value back out of a function.function plusThree(num) {
return num + 3;
}
var answer = plusThree(5);
answer
has the value 8
.
var sum = 0;
function addSum(num) {
sum = sum + num;
}
addSum(3);
addSum
is a function without a return
statement. The function will change the global sum
variable but the returned value of the function is undefined
.
Assignment with a returned value
Whatever that’s on the right of the equal sign will be resolved before the value is assigned, even if it’s a return value.
function nextInLine(arr, item) {
arr.push(item);
return item = arr.shift();
}
Understanding boolean values
boolean is a data type that may only be: true
or false
.
These two states are mutually exclusive, one is on and other is off.
if (condition is true) {
statement is executed
}
function trueOrFalse(wasThatTrue) {
if (wasThatTrue) {
return "Yes, that was true"
}
return "No, that was false";
}
Comparison with the equality operator
==
is called the equality operator, one of many comparison operators.
It compares two values and returns true
if they’re equivalent or false
if they are not. It also operates a type conversion of the compared values(number, string, …)
Comparison with the strict equality operator
===
is called the strict equality and does not perform a type conversion.
Practice comparing different values
Determine the type of a variable or a value with the typeof
operator.
==
operator performs type conversion but ===
does not perform type conversion.
Comparison with the inequality operator
!=
is the inequality operator, meaning not equivalent and that it returns false
where equality would return true
and vice versa.
Comparison with the strict inequality operator
!==
means striclty not equal and does not convert data types.
Comparisson with the greater than operator
The greater than operator >
compares the values of two numbers.
It returns true
when the number on the left is greater than the number to the right.
Comparison with the greater than or equal to operator
>=
is called the greater than or equal to operator.
Comparison with the less than operator
<
is named the less than operator that compares the values of two numbers.
Comparison with the less than or equal to operator
The less than or equal to operator is <=
.
&&
is called the logical and operator.
It will return true
if and only if the operands to the left and to the right of it are true.
if (num > 5 && num < 10) {
return "Yes";
}
return "No";
||
returns true
if either of the operands is true
.
if (num > 10 || num < 5) {
return "No";
}
return "Yes";
Introducing else statements
With an else
statement, an alternate block of code gets executed. if/else
if
statements together with else if
statements.
if (num > 15) {
return "Bigger than 15";
} else if (num < 5) {
return "Smaller than 5";
} else {
return "Between 5 and 15";
}
Logical order in if else statements
Order is very important when working with if
and else if
statements.
if (condition1) {
statement1
} else if (condition2) {
statement2
} else if (condition3) {
statement3
. . .
} else {
statementN
}
var names = ["Hole-in-one!", "Eagle", "Birdie", "Par", "Bogey", "Double Bogey", "Go Home!"];
function golfScore(par, strokes) {
// Only change code below this line
if (par, strokes == 1) {
return "Hole-in-one!";
}
else if (par, strokes <= par - 2) {
return "Eagle";
}
else if (par, strokes == par - 1) {
return "Birdie";
}
else if (par, strokes == par) {
return "Par";
}
else if (par, strokes == par + 1) {
return "Bogey";
}
else if (par, strokes == par + 2) {
return "Double Bogey";
}
else {
return "Go Home!";
}
// Only change code above this line
}
golfScore(5, 4);
switch
statement when you have many options to choose from.case
statements define various possible values.switch
tests a value and can have many case statements.case
value until a break
is encountered.
switch(lowercaseLetter) {
case "a":
console.log("A");
break;
case "b":
console.log("B");
break;
}
case
values are tested with strict equality ===
.
The break
stops executing statements.
If break
is omitted, next statement will be executed.
function caseInSwitch(val) {
var answer = "";
switch(val) {
case 1:
return "alpha";
break;
case 2:
return "beta";
break;
case 3:
return "gamma";
break;
case 4:
return "delta";
break;
}
return answer;
}
caseInSwitch(1);
default
statement which will be executed if no matching case
statements are found.default
statement should come in the last position. default:
defaultStatement;
break;
var result = "";
switch(val) {
case 1:
case 2:
case 3:
result = "1, 2, or 3";
break;
case 4:
result = "4 alone";
}
switch
statements can be easier to write than many chained if/else if
statements.
function isEqual(a,b) {
return a === b;
}
return
statement is reached, the execution of the current function stops and
control returns to the calling location. function abTest(a, b) {
if (a<0 || b<0) {
return undefined;
}
return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));
}
abTest(2,2);