Base
- Variable declaration
var variable_name; // declare a variable using var
var can be redeclared and updated, and it is function-scoped, which means that it is accessible within the function in which it is declared, and also accessible outside the function if it is declared in the global scope
let variable_name; // declare a variable using let (block-scoped)
let cannot be redeclared, but it can be updated, and it is block-scoped, which means that it is only accessible within the block in which it is declared (e.g., inside a loop or an if statement)
const variable_name; // declare a variable using const (block-scoped), must be initialized at the time of declaration and cannot be reassigned, unless it is an object or array, in which case the properties or elements can be modified but the variable itself cannot be reassigned
const cannot be redeclared or updated, and it is block-scoped, which means that it is only accessible within the block in which it is declared (e.g., inside a loop or an if statement)
- Data types
JavaScript has several built-in data types, including:
Primitive types: string, number, boolean, null, undefined, symbol
string: a sequence of characters enclosed in single quotes, double quotes, or backticks
number: a numeric value, which can be an integer or a floating-point number
boolean: a logical value that can be either true or false
null: a special value that represents the absence of any object value
undefined: a special value that represents the absence of any value
symbol: a unique identifier used as an object property key
Object types: object, array, function
For reference types, '=' assigns the reference to the value, not the value itself.
This means that if I assign an object or array to a new variable, both variables will reference the same underlying data, and changes made through one variable will affect the other variable as well.
And the '===' operator checks for strict equality, which means that it checks both the value and the type of the operands.
For primitive types, this means that two values are considered equal if they have the same value and type. However,
for reference types, two variables are considered equal only if they reference the same underlying data.
This means that even if two objects or arrays have the same properties and values, they will not be considered equal unless they reference the same underlying data.
And also, the '==' operator checks for loose equality, which means that it performs type coercion if the operands are of different types.
For example, if you compare a string and a number using '==', JavaScript will attempt to convert the string to a number before making the comparison.
This can lead to unexpected results, so it is generally recommended to use '===' for comparisons in JavaScript to avoid unintended type coercion.
object: a collection of key-value pairs, where the keys are strings and the values can be any data type
array: an ordered list of values, which can be of any data type
function: a block of code that can be executed when called, and can also be treated as a first-class object
- Operators
JavaScript has several types of operators, including:
Arithmetic operators: +, -, *, /, %, ++, --
- Array
Arrays are ordered lists of values, which can be of any data type.
They are defined using square brackets and can contain any number of elements, including other arrays and objects.
To access an element in an array, you can use its index, which starts at 0.
For example, to access the first element of an array called myArray, you would use myArray[0].
You can also use various array methods to manipulate arrays, such as push(), pop(), shift(), unshift(), splice(), slice(), and many others.
typeof an array is "object", means array is an object with special properties and methods for working with ordered data.
example:
const myArray = [1, "hello", true, [2, 3], { name: "Alice" }];
var firstElement = myArray[4]; // access the fifth element of the array, which is an object
var name = new Array("Ludviko", "Bob"); // create a new array using the Array constructor
console.log(firstElement.name); // output: "Alice"
console.log(myArray[0]); // output: 1
get the length of an array:
myArray.length; // returns the number of elements in the array, which is 5 in this case
length is a writable property, which means that you can change the length of an array by assigning a new value to it.
However, changing the length of an array can have unintended consequences, such as truncating the array or creating empty slots, so it should be done with caution.
myArray.length = 3; // this will truncate the array to the first three elements, and the remaining elements will be removed
myArray.length = 10; // this will create empty slots in the array from index 5 to index 9, which will be undefined
To read the array:
myArray[index]; // returns the element at the specified index
myArray[4]["name"]; // returns the value of the "name" property of the object at index 4, which is "Alice"
To update the array:
myArray[index] = newValue; // updates the element at the specified index with a new value
The empty of an array:
myArray.length = 0; // this will empty the array by setting its length to 0, and all elements will be removed
var RandomArray = [1, , 3];
console.log(RandomArray[1]); // output: undefined, because the second element is empty
Traversal of an array:
for (var i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
}
for (var i in myArray) {
console.log(myArray[i]);
}
The methods of an array:
isArray(): returns true if the value is an array, false otherwise
push(): adds one or more elements to the end of an array and returns the new length of the array
pop(): removes the last element from an array and returns that element
shift(): removes the first element from an array and returns that element
unshift(): adds one or more elements to the beginning of an array and returns the new length of the array
splice(): changes the contents of an array by removing or replacing existing elements and/or adding new elements in place
slice(): returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included)
join(): joins all elements of an array into a string and returns that string
indexOf(): returns the first index at which a given element can be found in the array, or -1 if it is not present
lastIndexOf(): return the last index at which a given element can be found in the array, or -1 if it is not present
includes(): determines whether an array includes a certain value among its entries, returning true or false
find(): returns the value of the first element in the array that satisfies the provided testing function, or undefined if no such element is found
concat(): merges two or more arrays and returns a new array
sort(): sorts the elements of an array in place and returns the sorted array, it'll change the original array, and the default sort order is according to string Unicode code points
reduce(): applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value
some(): tests whether at least one element in the array passes the test implemented by the provided function, returning true or false
every(): tests whether all elements in the array pass the test implemented by the provided function, returning true or false
reverse(): reverses the order of the elements of an array in place, and returns the reference to the same array, it'll change the original array
flat(): creates a new array with all sub-array elements concatenated into it recursively up to the specified depth, default depth is 1
fill(): fills all the elements of an array from a start index to an end index with a static value, and returns the modified array
forEach(): executes a provided function once for each array element
map(): creates a new array with the results of calling a provided function on every element in the array
filter(): creates a new array with all elements that pass the test implemented by the provided function
examples:
const myArrayII = [1, "hello", true];
myArrayII.push(3.14); // adds 3.14 to the end of the array, returns 4
myArrayII.pop(); // removes the last element (3.14) from the array, returns 3.14
myArrayII.shift(); // removes the first element (1) from the array, returns 1
myArrayII.unshift("world"); // adds "world" to the beginning of the array, returns 3
myArrayII.splice(1, 1, "hi"); // removes 1 element at index 1 ("hello") and adds "hi" at index 1, returns ["hello"]
myArrayII.slice(0, 2); // returns a new array containing the first two elements of the array, which is [1, "hi"]
myArrayII.join(", "); // joins all elements of the array into a string separated by ", ", returns "world, hi, true"
myArrayII.indexOf(true); // returns the index of the first occurrence of true in the array, which is 2
myArrayII.lastIndexOf(true); // returns the index of the last occurrence of true in the array, which is also 2
myArrayII.includes("hi"); // returns true, because "hi" is an element of the array
myArrayII.find(function(element) {
return element === "hi";
}); // returns "hi", because it is the first element in the array that satisfies the condition
myArrayII.concat([4, 5]); // returns a new array that is the concatenation of myArrayII and [4, 5], which is ["world", "hi", true, 4, 5]
myArrayII.sort(); // sorts the elements of the array in place, returns ["hi", "world", true], because the default sort order is according to string Unicode code points, and true is converted to "true" for sorting
myArrayII.reduce(function(accumulator, currentValue) {
return accumulator + currentValue.toString();
}, ""); // returns "worldhitrue", because it concatenates the string representation of each element in the array, starting with an empty string as the initial value of the accumulator
myArrayII.some(function(element) {
return element === true;
}); // returns true, because at least one element in the array is true
myArrayII.every(function(element) {
return typeof element === "string";
}); // returns false, because not all elements in the array are strings
myArrayII.reverse(); // reverses the order of the elements in the array in place, returns [true, "hi", "world"]
myArrayII.flat(); // returns a new array with all sub-array elements concatenated into it, which is [true, "hi", "world"], because there are no sub-arrays in this case
myArrayII.fill(0, 1, 2); // fills the elements from index 1 to index 2 (not included) with 0, returns ["world", 0, true]
forEach() example:
myArrayII.forEach(function(element) {
console.log(element);
}); // output: "world", "hi", true, function is the callback function, which is called for each element in the array, and the current element will be passed as an argument to the function, which is then logged to the console
map() example:
var newArray = myArrayII.map(function(element) {
return element.toString();
}); // creates a new array with the string representation of each element, which is ["world", "hi", "true"]
filter() example:
var filteredArray = myArrayII.filter(function(element) {
return typeof element === "string";
}); // creates a new array with only the string elements, which is ["world", "hi"]
- Objects
Unordered sets defined by curly braces, with key-value pairs
keys are strings, values can be any data type, including functions (methods)
To read a property:
objectName.propertyName
objectName["propertyName"]
To update a property:
objectName.propertyName = newValue
objectName["propertyName"] = newValue
To add a new property:
objectName.newPropertyName = value;
objectName["newPropertyName"] = value;
The difference between dot notation and bracket notation is that dot notation can only be used when the property name is a valid identifier
(i.e., it does not contain spaces or special characters), while bracket notation can be used with any string as a property name. Additionally,
bracket notation allows you to use variables to access properties, while dot notation does not.
To delete a property:
delete objectName.propertyName;
delete objectName["propertyName"];
To check if a property exists:
"propertyName" in objectName; // returns true if the property exists, false otherwise
Traversal of objects:
for (var i in objectName) {
console.log(i, objectName[i]);
}
Quote(same address):
var obj1 = { name: "Alice" };
var obj2 = obj1; // obj2 references the same object as obj1
// change the name property of obj2, which also changes the name property of obj1
obj2.name = "RandomGuy";
Example:
const person = {
name: "Alice",
"hair color": "golden",
age: 17,
ability: function(){
console.log("do six impossible things before breakfast");
}
};
var Me = {
name: "Ludviko",
age: 7023,
"hobby": "being",
BooksCollection: [
{ title: "Book I", author: "Author I" },
{ title: "Book II", author: "Author II" },
],
};
console.log(person.name); // output: "Alice"
console.log(person["hair color"]); // output: "golden"
console.log(Me.BooksCollection[0].title); // output: "Book I"
person.age = 18; // update the age property
- functions
Functions are blocks of code that can be executed when called, and can also be treated as first-class objects.
They are defined using the function keyword, followed by the function name, a list of parameters enclosed in parentheses, and a block of code enclosed in curly braces.
To call a function, you simply use its name followed by parentheses, and pass any required arguments inside the parentheses.
Functions can also be assigned to variables, passed as arguments to other functions, and returned from other functions, which is what makes them first-class objects in JavaScript.
When return, the function will stop executing and return the specified value to the caller.
If a function does not have a return statement, it will return undefined by default.
Example:
function greeting(name) {
console.log("Greetings! " + name + "!");
}
greeting("Alice"); // output: "Greetings! Alice!"
var add = function(a, b) {
return a + b;
}; // this is a function expression, which assigns an anonymous function to the variable add
console.log(add(2, 3)); // output: 5
The difference between anonymous functions and named functions is that anonymous functions do not have a name and are often used as function expressions or as arguments to other functions,
while named functions have a name and can be called by that name from anywhere in the code.