This page is just an information dump for the lecture portion of codecamp courses so far for my own notetaking purposes
JavaScript
What is a Code Editor and IDE?
Code editor is an application that lets you edit code files, and IDE(Integrated Development Environment) lets you compile, run and debug code. IDEs are Visual Studio, Xcode, Android Studio. Code editors are VS code, sublime text, notepad++. There are also cloud based editors to write code online such as replit, github codespaces, and ona.
How to Install Visual Studio Code onto Your Computer
This article tells you to download VS code and install it on 3 different OS.
-
How to Create a Project and Run Your Code Locally in VS Code
VS code uses workspaces, you will need to use command lines to create a direction for your project. You can use command prompt commands such as cd ~ to go back to home directory. mkdir my-project to make a folder that is called my-project. After opening a new directory get the live server extension to host your website and view changes.
What Are Several Useful Keyboard Shortcuts for Maximizing Productivity in VS Code?
Goes over keyboard shortcuts like ctrl s to save, ctrl c copy, ctrl v paste. Shift+alt+f will run your configured formatter such as prettier. Ctrl Shift F to search all the text in your workspace. Ctrl Shift H to find and replace. Ctrl Shift K to delete a line. Ctrl b to hide the file list. Ctrl + or minus to make scaling bigger or smaller. Ctrl Shift P to see a list of commands.
-
What Are Some Good VS Code Extensions You Can Use In Your Editor?
Goes over some useful extensions. Better Comments, code spell checker, error lens, indent rainbow, vs code great icons, colorize, eslint, prettier, vs code pets, power mode, discord presence.
-
What Is JavaScript, and How Does It Work with HTML and CSS?
Javascript is a language that is designed to bring interactivity and dynamic behavior to websites. Compares javascript to CSS and HTML. JavasScript is a programming language, HTML/CSS markup languages.
-
What is a Data Type, and What Are the Different Data Types in JavaScript?
Data types refer to the kind of value a variable can hold. A variable is a name container to store a specific value. Number is the first data type and represents integers and floating point values. Next is string which is a sequence of characters. Boolean is another type which represents true or false. Next two are undefined(undeclared) and null(nothing).
Another type is Object which is made of keys and labels to store data. A symbol type is a value that is unique and cannot be changed. BigInt is the last one which is for very large numbers it is created by adding a n at the end of a large number.
-
What Are Variables, and What Are Guidelines for Naming JavaScript Variables?
Variables are containers for storing data that you can access and modify. You can declare a variable using the let keyword. The assignment operator is =, which isn't quite equal.
Naming variables should be descriptive so the code is easier to understand. Variables must begin with a letter, an underscore, or a dollarsign. They cannot start with a number. Variables are case sensitive and important to stick with a convention like camelCase. You cannot use keywords as names for variables such as let, const, function, or return. Avoid special characters other than underscore and dollar signs.
-
How Do let and const Work Differently When It Comes to Variable Declaration, Assignment, and Reassignment?
Variables are usually declared by let or const. Let lets you declare variables that can be updated and reassigned later. Const is meant for variables that are constant and you cannot reassign them. You can also use the var keyword but it is not recommended over let since it has a wider scope and is likely to cause problems.
-
What is a String in JavaScript, and What is String Immutability?
A string is a sequence of characters used to represent text data. To create a string you can use '' or "" but not a mix like '". Strings are immutable which means that once they are created they cannot be changed.
-
What Is String Concatenation, and How Can You Concatenate Strings with Variables?
String Concatenation is joining pieces of text together. The + operator can be used to concatenate strings like firstName + LastName. One of the weaknesses of + operator is the spacing can sometimes be problematic. You can also use the += operator or the concat() method.
A function is a reusable block of code that performs a specific task and a method is a type of function that is associated with an object. Concat is useful when you want to concatenate multiple strings together.
-
What Is console.log Used For, and How Does It Work?
console.log() is a simple tool to display messages or output to a browser. Console log method helps you monitor code as it runs and spot mistakes throughout the code.
-
What Is the Role of Semicolons in JavaScript, and Programming in General?
The ; is used to delineate statements and improve code readibility. It represents the end of a statement. This helps to separate individual instructions for proper execution. Javascript has automatic semicolon insertion (ASI) which can add them automatically but explicitly including them helps prevent errors. ; is used in C, C++, and Java.
-
What Are Comments in JavaScript, and When Should You Use Them?
Comments are used to provide additional context for code or for notetaking. They are ignored when the code is executed and single line comments are created using //. You can also create multi line comments with /* */. Try not to overcomment especially when the function is obvious.
-
What Is Dynamic Typing In JavaScript, and How Does it Differ From Statically Typed Languages?
Javascript is dynamically typed because you don't have to specify variable types on declaration. This flexibility makes JavaScript easy for quick scripting but it can make bugs harder to catch as programs get larger. In a static language like C++ you must declare a variable type when created and it can't change. Dynamic languages are flexible, static languages have fewer runtime errors.
-
How Does the Type of Operator Work, and What Is the Type of Null Buiig in JavaScript?
The typeof operator lets you see the data type of a variable or value. It returns a string indicating the type. It will return something like "number", "boolean", etc.There is a bug where nulls will sometimes return "object".
-
What Is Bracket Notation, and How Do You Access Characters From a String?
Bracket notation allows you to retrieve the strings sequence of characters. You can do this with its index which is zero based, meaning it starts with 0,1,2. It uses [] and the index of the character you want to access. You can get multiple characters by + and writing out both variable[index]. This is useful when extracting initials or checking a specific letter for validation.
-
How Do You Create a Newline in Strings and Escape Strings?
You can create new lines using an escape sequence. Most common is \n. Another important concept is escaping characters. This is important when you want to include quotes in output. You can fix this by putting a \ in front of the quotes like statement = "She said, \"Hello!\"";
-
What Are Template Literals, and What Is String Interpolation?
Template literals are defined with backticks or `. They allow for string manipulation like putting directly directly in a string or string interpolation. String interpolation can be much easier to read when using multiple variables. Template literals also allow you to make multiline strings without using \n. The ${name} syntax is an example of string interpolation.
-
How Can You Find the Position of a Substring In a String?
Sometimes you may need to find the specific substring within a larger string. Like hello or world within hello world. You can use the indexOf() method to search for a substring. If the substring is found it will return the first index of that substring. If the substring is not found it returns -1. indexOf() requires two arguments the substring you want to find, and the position you want to start the search from. You can express both variables like indexOf("JavaScript", 10);.
-
What is the prompt() Method, and How Does It Work?
The prompt method opens a dialog box that asks the user for some input, then returns it as a string. If a user types a name and presses okay, it will be stored. If they cancel it will be set to null. The rest of the code will not run until the user interacts with the dialog box. The second optional box is what the input initially contains.
-
What is ASCII, and How Does It Work with charCodeAt() and fromCharCode()?
ASCII (*AMerican Standard Code for Information Interchange) is a character encoding standard that assigns a numeric value to each character. Example A is 65, a is 97. The ASCII standard covers 128 characters including A-Z,a-z, 0-9, common punctuation, and control characters.
You can easily access teh code of a character by using charCodeAt(). This method will call a string and return the ASCII code of the character at a specified index (console.log(letter.charCodeAt(0)). fromCharCode() will let you do the opposite, convert ASCII code to the character. This can be useful to check cases and to dynamically generate characters.
-
How Can You Test if a String Contains a Substring?
A substring is a smaller part of a string. You can check whether input has a specific word or character by using the includes() method. This method will return a boolean. Includes is case sensitive, and you can also test if it starts at a specific index using the second parameter. Ex. let result = text.includes("JavaScript", 7);
-
How Can You Extract a Substring from a String?
If you want to take a certain substring from a larger string you can use the slice() method. This does not modify the original string but lets you take just a part (string.slice(startIndex, endIndex);. The endIndex part is optional, because it will go to the end of the string without it.
-
How Can you Change the Casing for a String?
You may need to change strings to all uppercase or lowercase in different situations. You can do these with 2 methods, toUpperCase() and toLowerCase(). Neither method changes the original string, just creates a new string with the requested credentials.
-
How Can You Trim Whitespace from a String?
White space refers to spaces, tabs, linebreaks. You can trim this using the methods trim(), trimStart(), trimEnd(). trim() removes white space from beginning and end. trimStart beginning, trimEnd from the end.
-
How Can You Replace Parts of a String with Another?
In JavaScript, there are many scenarios where you need to replace a portion of a string with another. The replace() method in JavaScript allows you to find a specificied value and replace it with another value. The basic syntax is
string.replace(searchValue, newValue);searchValue is the value you want to search for in a string. The newValue is the value you will replace it with.let newText = text.replace("JavaScript", "coding");In this JavaScript is replaced with coding. replace() is case sensitive. replace() also only replaces the first value found. -
How Can You Repeat a String x Number of Times?
When working with JavaScript you may encounter situatiuons where you need to repeat a string. The repeat() method provides a way to do this. The syntax is as follows:
string.repeat(count);string what you want to repeaet, count is the number of repeats. Here's an example:let repeatedWord = word.repeat(3);In this example the value of repeatedWord is repeated 3 times. The count parameter must be a non-negative number. Count has to be finite therefore the special value Infinity that represents infinity cannot be used. If the count is rational it will round it down to the nearest integer. -
What is the Number Type in JavaScript, and What Are the Different Types of Numbers Available?
In JavaScript a number represents a numeric value. It includes decimals and negatives, Infinity and NaN(not a number). Floating numbers are numbers with decimal points they're often referred to as floats by JS devs. When you try to divide a number by zero you get the value of infinity. If you try to divide a value that isn't a number by a value, then you will get NaN. JS also supports other base systems including base 2, base 8, and base 16.
-
What Are the Different Arithmetic Operators in JavaScript?
JavaScript provides tools to perform basic arithmetic opoerations on numbers, add, sub, mult, div(+,-,*,/). Also some more complex ones like remainder or exponentation. The remainder operation is the % which returns the remainder of division. The exponentation operator is ** and raises one number to the power of another value. JS uses operator precedence to determine the order of operations.
-
What Happens When You Try to Do Calculations with Numbers and Strings?
JavaScript is a language where things can work in weird ways sometimes, like when mixing strings and numbers. The + sign works double duty, it is for both addition and string concatenation. If you use the + with a number and a string, it will join them and create a string. If you do other operations with a string/number you will find that JS will convert it to a number if possible then calculate. If the string doesn't look like a number it will typically result in NaN. When using booleans true becomes 1 and false becomes 0 typically and the operation is performed. Null is treated as 0 and undefined is treated as NaN.
-
How Does Operator Precedence Work?
If you write an expression with several operators in JavaScript operator precendence comes in. JavaScript treats multiplication as a higher precendence than addition. You can use () to make something have precedence. Mult/Div always take priority over +/-. Exponents and equal are right to left associative. a = b = 5, means b is 5 first, then a is 5.
-
How Do the Increment and Decrement Operators Work?
Increment and decrement operators are ++ and --. They both allow you to adjust the value by 1. There is also prefix ++x and postfix x++. Prefix increases the value of the variable first, then returns a new value. Postfix returns the current value then increases it.
-
What Are Compound Assignment Operators in JavaScript, and How Do They Work?
Compound assignment operators allow you to perform a mathematical operation and reassign the result back to the variable in one line of code. You can use += and -= to perform the operation and assign. You can also use *= and /= to use multiply/divide. %=, **= &= which is a bitwise and assignment, |= bitwise or assignment operator.
-
What Are Booleans, and How Do They Work with Equality and Inequality Operators?
Booleans are a type that represent true/false. They are essential when you want to determine if something happened or not. You can use variable inside a conditional like this
let isOldEnoughToDrive = true; if (isOldEnoughToDrive) { console.log("You're old enough to drive"); // You're old enough to drive } else { console.log("Sorry, you are not old enough to drive"); }
To compare two values you can use either the equality or strict equality operator. The equality operator is represented by ==. The strict operator === does not perform type coercion so 5 === '5' is false unlike ==. You can also use != and !== (strict) for not equal. Strict is usually preferred. -
What Are Comparison Operators, and How Do They Work?
Comparison operators allows you to compare two values and return true or false. These include >, <, >=, <=.
-
What Are Unary Operators, and How Do They Work?
Unary operators are operators that act on a single operand to perform operations like a type conversion, value manipulation, or certain conditions. Unary plkus operator converts its operand into a number. If you have a string like 42 and you use = +variable you will convert that value to a number. You can also use - and flip the sign = - will flip the sign of the value. ! is hte logical operator for not, flips a boolean to its opposite value. The bitwise not operator is a less commonly which is ~ it inverts the binary representation of the number. If you use ~num on a number that is 5, you will get back -6. The void keyword is a unary operator that evaluates the expression and returns undefined. There is also typeof.
-
What Are Bitwise Operators, and How Do They Work?
Bitwise operators work on the binary representation of numbers. In computing a bit is the most basic unit of information, it can only have two values.. 0 or 1. The binary representation of the number 10 is 1010. JS provides several bitwise operators including & and, | or, ^ xor, ~ not, << left shift, >> right shift. If a = 5 (Binary: 101) and b = 3(binary: 011), a&b returns 1 because only the ones digit is set in both numbers. a | b will return 7(binary: 111) becasue it returns a 1 in each position for which eihter of the corrsponding bits have a 1 in that value. The bitwise XOR return a 1 in each position where there is only 1 in one of the numbers position not both. Therefore it returns 6 for this case because it is binary 110 because both numbers have a 1 in the ones place. the bitwise ~ inverts all bits in the operand. So not a(binary 101) is -6. The << used on just a by 1 will result in 10 because it was oriignally 101(5) and shifting it one place over will effectively multiply it by 2 resulting in 1010 or 10. The >> will effectively divide by two and rounding down so the resullt of a >> 1 will be 2.
-
What Are Conditional Statements, and How Do If/Else If/Else Statements Work?
Conditional statements let you make decision in your code. They allow the program to flow in a particular way based on certain conditions. If statements takes a condition and runs a block of code to determine if that condition is truthy. Truthy values: non-empty strings, any number other than 0 or -0, arrays, objects, the boolean true. Falsy values: boolean false, 0, empty strings, null, undefined, and NaN. When using just an if statement if the condition is false the code block will not run. If you use an if else statement when the if statement condition is false, the else code will run. You can use elseif you want to check additional paths before the else. You can use a ternary statement like this one
const weather = temperature > 25 ? 'sunny' : 'cool';this will return It's sunny if the temperature is greater than 25. Cool otherwise. Only use ternary when you want a compact simple logic statement, if/else for more complex conditions. -
What Are Binary Logical Operators, and How Do They Work?
Binary logical operators help you evaluate two expressions and return a result based on their truth. The logical AND operator is represented by && it checks if both operands are true and returns a result. If both operands are true then it returns hte one on the right. If one is false, it returns the false one. If both are false then it returns the first false value. The logical OR operator checks if at least one is truthy. It will then return the value that is truthy. If both are false then it returns the last false value. The nullish coalescing operator is more sophisticated it is represented by a ??. It helps in scenarios where you want to return a value on if the first one is null or undefined.
-
What Is the Math Object in JavaScript, and What Are Some Common Methods?
When exploring JavaScript you will discover mathematical operations is a common task. JavaScript offers a built in Math object to tackle more complex math challenges. Math.random() generates a random floating-point number between 0 and 1. This value can be 0 but it will never be 1. Math.min() and Math.max() return the min/max values from that data set. If you want to round numbers up or down you can use Math.ceil() or Math.floor(). Another helpful math method is Math.trunc(). This removes the decimal part of a number, returning only the integer portion. You can also use Math.sqrt() and Math.cbrt() for squareroot/cuberoot. Math.abs() will give you the absolute value of a number. Math.pow() takes two numbers and raise the first to the power of the second. Math.round combines ceil/floor.
-
How Does isNaN Work?
Nan stands for Not a Number. Its a special value that represents an unrepresentable or undefined numerical result. NaN is a property of the global object, and its also a considered type in JavaScript. NaN is typically the result of operations that should return a number but can't produce a meaningful numerical value. Such as, 0/0. One odd property about NaN is that it's not equal to anything.. including itself. This unique behavior makes it challenging to check if a value is NaN using comparison operators. To address this, JavaScript provides the isNaN() function. isNaN() first attempts to convert the parameter to a number. If it can't be converted it returns true. Due to this in ES6 introduced Number.isNaN() which does not convert the parameter to a number before testing. It only returns true if the value is exactly NaN.
-
How Do the parseFloat() and parseInt() Methods Work?
parseFloat() and parseInt() are methods used to convert strings to numbers. parseFloat() parses a string argument and returns a floating point number. It's designed to extract a number from the beginning of a string, even if the string contains non numeric characters. Float numbers are numbers with decimal points, heres how parseFloat works: it starts parsing from the beginning of the string and continues until it ecncounters a char that can' be a floating point number. parseFloat starts parsing from the beginning of a string until it encounters a character that can't be part of a floating point. If it can't find a valid number it returns NaN. parseInt on the other hand parses a string and returns an integer. It starts from the beginning of a string, but it stops on the first non digit character. parseInt() stops parsing at the first non-digit it encounters. Both methods ignore whitespace, they handle plus and minus at the beginning of the string. They also have some limitations. They do not handle all number formats, such as scientific notation.
-
What is the toFixed() Method, and How Does It Work?
The .toFixed() method is buitl in JavaScript function that formats a number using fixed point notation. It's particularly useful when you need to control the decimal places in a number like when using currency values or precise measurements. It's important to know that .toFixed() returns a string not a number. The .toFixed() method rounds to the nearest value that can be represented wiht the specified number of decimal places. If you call .toFixed() without arguments it will default to 0 decimal places. This can be particularly useful when working with financial calculations or displaying prices.
-
How Do Comparisons Work with Null and Undefined Data Types?
In JavaScript, null and undefined are two distinct data types that represent the absence of a value, but they behave differently in comparisons. Undefined when a variable is declared but it is not assigned a value. It's the default value of uninitialized variables and function parameters that aren't provided an argument. The null type on the other hand is an assignment value that represents a deliberate non-value. When comparing null and undefinedusing the == operator, JavaScript performs type coercion. This means it tries to convert the operands to the same type before making a comparison. In this case, null and undefined are considered equal. However, strict equality will not say they are equal. null and undefined are only equal to each other when using the equality operator. undefined always converts to NaN which amkes all numeric comparisons false. It's recommended to use the strict equality operator ===.
-
What Are Switch Statements and How Do They Differ from If/Else Chains?
switch statements and if/else if/else chains are both control flow structures that allow us to execute different code blocks based on conditions. A switch statement evaluates an expression and matches its value against a series of case clauses. When a match is found, the code block associated with that case is executed. The break statement at the end of each case is crucial. Without it, the program will continue executing subsequent cases known as fall through. If you are comparing many values for a single variable, switch statements can be more readable and concise. if/else if statements are more flexible. They can evaluate complex conditions and different variables in each clause. Switch statements use strict comparison === operators.
-
What Is the Purpose of Functions, and How Do They Work?
Functions are reusable pieces of code that perform a specific task or calculate a value. Think of functions as a machine that takes some input, does some operations on it, and then produces an output. We declare a function with function name() { code here }. A function call is when we use the function like functionName();. In order to use variables within a function we use the parameters within the parenthesis.A function will always return a value, by default it will return undefined. If you need your function to return a value, use the return statement. Functions can use a default value for a parameter,
function greetings(name = "Guest") {console.log("Hello, " + name + "!");}in this example if there is no value for name it will use Guest. -
What Are Arrow Functions, and How Do They Work?
You can also write functions using an arrow function expression.
const greetings = (name) => { console.log("Hello, " + name + "!");};In this example we are assigning a variable a function. This doesn't use the function keyword and adds => between the parameter and function body. If your arrow function has no parameters then you must use parentheses like [const greetings = () =>] You can remove the braces if youconst greetings = name => console.log("Hello, " + name + "!");. These type of one line functions only work with arrow functions. When using a one liner you cannot use return like if you want to return width * height.const calculateArea = (width, height) => width * height; -
What Is Scope in Programming, and How Does Global, Local, and Block Scope Work?
Scope refers to visibility and accessiblity of variables in diff parts of your code. It determines where variables can be accessed. In JS scope is crucial for good code. There are 3 types of scope global, local and block scopes. Global scope is the outermost scope in the JS program. These are accessible everywhere in your code. While these can be convenient, they should be used sparingly as they can make naming conflicts and harder to maintain code. Local scope refers to variables only accessible within a function. Local scope will result in a variable that will only be usable in a function, outside of that it will return an error. Block scope is created by let and const keywords in ES6. A block is any code section within curly braces {}. If statements, for, while use these. Block var are only useable within the block access outside of the block throws an error.
-
What Are the Key Characteristics of JavaScript Arrays?
An array in JavaScript is an ordered collection of values, each identified by a numeric index. The values in a JS array can be different data types, nums, strings, booleans, objects, other arrays. You create an array with [] and separate values with commas. One of the key characteristics of arrays are they are zero indexed. Arrays have a property of length that returns the number of items. They are also dynamic so their size can be changed after creation. You can add or remove elements from an array using push(), pop(), shift(), unshift(), and splice().
-
How Do You Access and Update Elements in an Array?
Arrays start with 0, and its imoprtant to note if you try to access an index that doesn't exist it returns undefined. You can update by assigning a new value to an index. You can also assign values to index that don't exist yet. Be careful not to create undefined indices in between the numbers created.
-
How Do You Add and Remove Elements from the Beginning and End of an Array?
Arrays in JS are dynamic, there are 4 main methods for adding to an array push, pop, shift, and unshift. The push() method is used to add one or more elements to the end of an array. The push() value will return the new length. You can add values to an array declared with const. You cannot assign new values to an array with just = operator. The next method is with pop() this removes the last element from an array and returns that element. The unshift() method adds one or more elements to the beginning of an array and returns its new length. The shift() method removes the first element of an array and returns that element.
-
What Is the Difference Between One-Dimensional and Two-Dimensional Arrays?
Arrays are fundamental structures to store collections of elements. Understanding the difference between one dimensional and 2 dimensional arrays is crucial for organizing and manipulating data. In a one dimensional array elements are accessed using a single index. In 2 dimensional arrays its more like a grid multiple rows and columns. It is essentially an array of arrays. To access an element you need 2 indices one for row and one for column. 1-d arrays are simpler and sufficient for most tasks, 2-d becomes important with complex structured.
-
What is Array Destructuring, and How Does It Work?
Array destructuring is a feature in JS allows you to extract values from arrays or objects and assign them to variables in a concise and readable way. It provides convenient syntax for unpacking array elements.
let fruits = ["apple", "banana", "orange"]; let [first, second, third] = fruits; console.log(first); // "apple" console.log(second); // "banana" console.log(third); // "orange"This an example of array destructuring. You can also skip elements by having an empty set of commas. You can also use default values in destructuring. Lastly, you can use rest syntax to collect the remaining elements into a new array. The ...rest must be the last element in the destructuring pattern. -
How Can You Use String and Array Methods to Reverse a String?
Reversing a string is a commmon programming task that can be accomplished in JS using string and array methods. This involves 3 main steps: splitting the string into an array of characters, reversing, joining the character back into a string. These steps using the split(), reverse(), and join() methods. The first step is to convert the array into individual characters, we do this using the split() method. This divides a string into an array of substrings and specifies where each split should happen based on a separator. If no separator is provided, the method returns an array containing the original string as a single element. Examples of separators an empty string "", single space " ", A dash "0". If you have a string and use varname.split(""); you can split a string into an array of characters. Once we have an array of characters, you can use reverse() to reverse the order. The final step is to put the array back into a string using join().
-
How Do You Get the Index for an Element in an Array Using the indexOf() Method?
In JavaScript the indexOf() method ius useful for finding the first index of a specific element within an array. If the element cannot be found it will return -1.
let index = colors.indexOf("green", 3);the fromIndex is optional, if it is not specified it will start the search from the beginning. -
How Do You Add and Remove Elements from the Middle of an Array?
The splice() method is a powerful tool for modifying arrays. It allows you to add or remove elements from any position in the array. The return value for splice will be an array of items removed from the array. Its important to realize this modifies the original array. The syntax is
array.splice(startIndex, itemsToRemove, item1, item2)the startIndex is where it starts, itemsToRemove is optional if omitted it will remove all elements. The items are added to the array. You can create a copy of the original array using the ... operator.let copy = [...original];you can use the indexOf() to find an element. You can then use indextToRemove to remove it. splice() mayt not be efficient for large arrays because it causes all elements to shift. -
How Can You Check if an Array Contains a Certain Value?
In JS, the includes() method is simple and efficient way to check if an array contains a value. This method returns a boolean value based on that. The includes method is great when you need to verify the presence of an element without its position. The includes method can take a second parameter to tell it where to start the search. Includes is a straightforward way to verify something.
-
What Is a Shallow Copy of an Array, and What Are Some Ways to Create These Copies?
A shallow copy of an array is a new array that has the same items as the original. Also when you change something in one you change it in the other too. There are several ways to do this concat(), slice() and spread. concat() creates a new array by merging two or more arrays. When creating a shallow copy with concat a strict equality check will throw false. You can also use a slice method without arguments. The spread operator ... provides another concise method to make shallow copies.
-
What Is an Object in JavaScript, and How Can You Access Properties from an Object?
In JS, an object is a fundamental data structure that allows you to store data. It's a container for information.
const person = {name: "Alice",age: 30, city: "New York"};in this example there is an object with 3 different properties. There are two main ways to access object properties, dot notation and bracket notation. Dot notation looks likeobjectName.propertyName. Bracket notation allows you to access a property inside square brackets like person["name"]. Bracket notation allows you to use property names that aren't valid identifiers. -
How Can You Remove Properties from an Object?
There are several ways to remove properties from an object. The delete operator being the most common. You can use something like
delete person.job;to delete the job property from person. Another way is by destructuring assignment with parameters, this won't actually change the object but make a new object with the desired properties. You can also collect the remaining properties into a new object after the ... like remainingProperties. -
How to Check If an Object Has a Property?
In JS there are several ways to check if an object has a property. The common ways are hasOwnProperty(), the in operator and checking against undefined. You could use
person.hasOwnProperty("name");to check if person has the name property and it will return true/false. You can also use the in property like"name" in personwhich will also return a true/false. Lastly, you can check it against undefined likecar.brand !== undefined;which will Also return a true false value. This can give false negatives if a property has explicitly been given the value undefined. -
How Do You Work with Accessing Properties from Nested Objects and Arrays in Objects?
When working with JS you'll often encounter complex data structures that involve nested objects and arrays within objects. Accessing properties from nested objects involve using dot notation or bracket, you'll need to chain the accessors to drill down into the structure. You may have to chain them like this code
person.contact.phone.work;in order to access the work property. Bracket notation would look like thisperson['contact']['phone']['work'] -
What is the Difference Between Primitive and Non-Primitive Data Types?
In JavaScript, Primitive data types are the simplest form of data. They include numbers, strings, booleans, null, undefined and symbols. These represent single values and are not objects. Primitive values are immutable which means when created their value cannot be changed. Non primitive values are more complex in JS these are objects, arrays, and functions. These hold multiple values as properties or elements. When you create a non primitive variable its a reference to the location of the memory itself. Which is why when there is a copy its still the same object in memory.
-
What is the Difference Between Functions and Object Methods?
In JS, functions and objects are both ways to encapsulate reusable code but have key differences. Functions are reusable blocks of code for a task, an object is functions associated with an object.
const person = { name: "Bob", age: 30, sayHello: function() { return "Hello, my name is " + this.name; }};The this keyword allows the SayHello method to access the properties. Functions are called by name, methods are called by using dot notation on the object. -
What Is the Object() Constructor, and When Should You Use it?
In JS, a constructor is a special type of function used to create and initialize objects. It is invoked with the new keyword and can initialize properties and methods. The Object() constructor would be called using new Object(). The constructor method can also be used without the new keyword. Object(num) will create an object wrapper for the num making num into an object.
-
What Is JSON, and How Do You Access Values Using Bracket and Dot Notation?
JSON stands for JavaScript Object Notation. It is a lightweight, text-based format that is commonly used to exchange data between a server and web app. It is machine parseable and human readable. It is language independent so you can use it in python or a C# application.
{"name": "Alice","age": 30,"isStudent": false,"list of courses": ["Mathematics", "Physics", "Computer Science"}.JSON key values are store info and each pair is separated by commas. Each key must be wrapped in "" or it will result in an error. You can access JSON objects with dot or bracket notation.import data from "./example.json" with { type: "json" };This example is using an import statement to bring the object file to be accessed. -
How Do JSON.parse() and JSON.stringify() Work?
JSON.stringify() is used to convert a JS object into a JSON string.
console.log(JSON.stringify(developerObj, ["firstName", "country"]));In this example we express which properties we want to be stringified which is name/country. There is also a space parameter which is optional. This allows you to control the spacing for the stringified result. You will also use the JSON.parsE() method. This converts a JSON string back into a JS Object. This is useful when you want to retrieve JSON data from a web server or from a localStorage. -
What Is The Optional Chaining and Object Destructuring?
The optional chaining operator ?. is a useful tool in JS that lets you safely access object properties or call methods. Uncaught TypeError can occur if you try to access a property that does not exist.
console.log(user?.profile?.phone?.number);. By using the optional chain operator before? attributes we are telling JS to continue and will return undefined instead of an error. -
What is Object Destructuring, and How Does It Work?
Object destructuring is a powerful feature in JS that allows you to extract values from objects and assign them to variables. It's part of the ES6 specification and has become an essential tool. At its core destructuring is about separating objects into variables. Object destructuring also allows you to set default values.
-
How Do Loops and Iterations Work in JavaScript?
Loops in programming are used to repeat a block of code multiple times. In JavaScript, there are several types of loops that you can use. The first will be the for loop.
for (initialization; condition; increment or decrement) { // code block to be executed}. The initialization statement is executed before the loop starts, it is typically used to initialize a counter variable. A counter variable is designed to keep track of the amount the loop has been ran. The conditional statement is evaluated before the iteration of the loop. The last part is the increment/decrement statement, this is execute after each iteration.for (let i = 0; i < 5; i++) {console.log(i);}In the example, i is the counter, initialized at 0, the condition is i < 5, and then incremented. Be careful not to make a condition that is always true, creating an infinite loop. -
How Does the For.. of Loop Work, and When Should You Use It?
A for...of loops is when you need to loop over values from an iterable.
for (variable of iterable) {}this is the basic syntax. If you have an array of numbers the variable would be the current number of the array.const numbers = [1, 2, 3, 4, 5];for (const num of numbers) {console.log(num);}. For iteration 1 it will be 1, and so on.If you need to change the value of the variable it is important to use int over const despite being an array. For of loops are when you need to loop over values. -
What Is the For...in Loop, and When Should You Use It?
a for...in loop is best used when you need to loop over the properties of an object.
const fruit = {name: 'apple',color: 'red',price: 0.99};for (const prop in fruit) {console.log(fruit[prop]);}In this example apple, red, 0.99 will be logged to the console. If there are nested properties it will display the property name for the nested, unless you nest another for... in loop within the first. Use isObject() to avoid arrays and null. -
What is a While Loop, and How Does It Differ from the Do...while Loop?
A while loop will loop until the condition is true. Condition is checked to make sure it is not false, which halts the loop. While loops are important when you do not know how many times to loop.
let counter = 0;while(counter < 5) {console.log(counter);counter++;}A do while loop is similar but it will execute the code at least once before checking. an example of a do while looplet counter = 0;do {console.log(counter);counter++;} while (counter < 5);. You will probably use while loops more often. -
What Are the Break and Continue Statements Used for in Loops?
A break statement is used to exit a loop early. A continue loop is used to skip the current iteration of a loop and move to the next one.
for (let i = 0; i < 10; i++) {if (i === 5) {break;}console.log(i);}In this example the loop starts and 0 and goes to 10, but due to the break check it will stop when it hits 5 resulting in 0 through 4.for (let i = 0; i < 10; i++) { if (i === 5) { continue; }console.log(i);}In this example the continue will result in skipping the value of 5. Resulting in 0-9 without 5. You can also use break and continue statements to control nested loops using the loopname and break or continue. When you use const, you must declare the variable or you will get an error. You should try to use const as a default, and let only when you need a variable that needs to change. -
What Is a String Object, and How Does It Differ from String Primitive?
In JS there are string objects and string primitives. A string object is created using the string constructor function like this
const greetingObject = new String("Hello, World!"); console.log(typeof greetingObject); // "object"If you do a typeOf test you will get back that a type object is a string. When you use length on a string primitive JS wraps the string primitive in a string object. This is why you can use methods like repeat(), concat() and slice(). String primitives are more memory efficient and faster than objects. -
What Is the toString() Method, and How Does It Work?
toString() is a feature that converts a value to its string representation. You can use this method for numbers, booleans, arrays, and objects. The method accepts an optional radix which represents the base.
console.log(num.toString(2));returns "1010" because of base 2, where an empty radix would be "10". You can also convert arrays and objects to strings. Arrays convert each element to a string and joins them with commas. With objects, it returns a default string which is [object Object]. To get a stringified version you need to use JSON.stringify() . -
What Is the Number Constructor, and How Does It Work for Type Coercion?
Number() constructor is used to create a number object. It contains methods like the isNaN and toFixed.
const myNum = new Num("34"); console.log(typeof myNum); // "object"Most of the time, the Number() will convert a string to a number. This is helpful when you get inputs from a user but need to make a number to calculate. If you number an empty string you will get 0. If it has random characters the result will be NaN. Booleans will be 1 for true, and 0 for false. null returns 0, undefined NaN. Empty array returns 0, 1 number array returns the number, multiple numbers gives NaN. Array with strings also NaN. Objects is always NaN. -
What Are Some Common Practices for Naming Variables and Functions?
Naming variables is important to clean readable code. Use camelcase, and boolean start with prefixes like is, has, can. Functions should clearly indicate what it does. For functions that return booleans, you can use is, has, can. If the function retrieves data start with the word get. Functions that set data start with set. For event handler functions the prefix handle or suffix handler. An event handler is an event after a button click. It is common to use i, j, k for iterator variables in loops. For arrays use plural nouns.
-
How Do You Get the Length for an Array, and How Can You Create an Empty Array of Fixed Length?
Length returns the number of elements in an array. It is possible to have an array with empty slots which will be reported by length. To create an empty array of fixed length use the Array().
const emptyArray = new Array(5);creates a new array with 5 length and all undefined values. You can also use Array.from() with a length argument. By default it creates undefined values, but you can use fill() to set it to 0. -
What Are Linters and Formatters, and How Can They Help You with Code Consistency?
A linter is a static code analysis tool that flags bugs. The term lint comes from a unix utility that examines C. ESLint is popular for JavaScript. Formatters automatically format code to adhere to a style guide. Formatters ensure consistent code style. A popular JS one is Prettier. Using linters and formatters can improve code quality and consistency.
-
What Is Memory Management, and How Does It Work in JavaScript?
Memory management is the proces of controlling memory allocation. When you run programs, it needs memory to store information. In some languages developers have to manually manage memory. JS uses automatic memory management, this process is called garbage collection. First allocation happens when you create variables, objects or functions to store them. The engine has ways to figure out when it isn't needed, then it is freed up. Sometimes you can accidentally keep things and prevent the garbage collection. Avoid global variables, and be careful what your functions are closing over.
-
What Are Closures, and How Do They Work?
Closures is a function that has access to variables in its outer scope even after return.
function outerFunction(x) { let y = 10; function innerFunction(){ console.log(x + y); } return innerFunction; } let closure = outerFunction(5); console.log(closure()); // 15In this we call outer function with x, the inner function uses x and y and returns it. Later when we call closure() it has access to outerfunction even though its done executing. Closures are useful for creating private variables and functions. Closures capture variables by reference not by value. -
What Is the var Keyword, and Why Is It No Longer Suggested to Use It?
The var keyword is the original way to declare a variable. let and const were introduced on 2015. When you declare a variable with var it becoems function scoped or globally scoped. var allows you to declare the same variable multiple times without throwing errors. The most significant issue with var is the lack of block scoping variables declared inside a block are still accessible outside of the block.
-
What is Hoisting?
Hoisting is a JS default behavior of moving declarations to the top of their scopes during the compilation phase before execution. JS runs in two phases, the compilation phase and the execution phase. Compilation - JS engine goes through code and sets up memory for variables and functions. If you use the var keyword, JS hoists the declaration to the top of its scope. This does not include a value though so if you call the variable before its given a value it will be undefined. Functions can be called before the declaration because the entire thing is hoisted to the top of its scope. let and const are hoisted but they cannot be accessed referred to as a temporal dead zone. It is recommended to avoid hoisting and declare variables at the top of their scope.
-
What Is a Module in JavaScript, and How Can You Import and Export Modules in Your Program?
In JavaScript a module is a self contained unit of code that has related functions/classes/variables. To create a module you write your JS code in a different file. Variables/functions/classes you want to make available need to be exported. You will need to first create a .js file that will have the function with export in front. Then in your websites source link you will need to add type="module" attribute to the script link. Then at the beginning of the file you will need to import the functions/variables you want.
-
What is the arguments Objects?
You create functions with parameters and call functions with arguments. If you call a function with more arguments than 2, JS will not throw an error. Functions that accept a variable number of arguments are called variadic functions. Since the arguments object is array like you can access an argument at a specific index. Even though arguments acts like an array, it does not utilize array methods like includes or push. While variadic functions are possible, you will normally use rest parameter syntax.
-
What are Reset Parameters and How Do They Differ from the arguments Object?
Arguments is an array like structure passed into a function. Modern JS uses the rest parameter like with logArgs(1,2,3) you should use a parameter like (...args). This will cause the paramter to be placed within an Array object. You can name this rest parameter whatever you like but make sure it is the last parameter listed. You may only have one rest parameter. You cannot use trailing commas after a rest parameter. Lastly, you cannot have a default value. A big difference between a rest parameter and the arguments object is the rest parameter is a real array and can use array methods like push.
-
What Is a Callback Function, and How Does It Work with teh forEach Method?
A callback function is passed as an argument to another function, so that the outer function can invoke it at a specific point. This is essential for understanding many including the forEach method. forEach allows you to iterate after each element in an array.
numbers.forEach(function(number) {console.log(number * 2);})in this example we use the forEach method with a callback function. forEach can take 3 arguments, the current element(callback function), index of current element, and array called upon. -
What Are Higher-Order Functions?
Higher order function is a function that takes one or more functions as arguments or returns a function. A common use is to abstract away complex operations. Higher order function can return functions, this is useful for creating more general ones. Many built in methods for JS are higher order function such as map(), filter(), and reduce(). Higher order functions allow you to describe what you want to accomplish(declarative) instead of step by step (imperative).
-
What Is the Map Method, and How Does It Work?
map is afunction that operates on arrays. This does not alter the original array and creates a copy, map accepts a callback function that will be called on every single element of an array. Callbacks acccept 3 arguments as stated earlier. A key difference between map and forEach is that map returns a new array.
-
What Is the Filter Method, and How Does It Work?
filter is used to create a new array with elements that pass a test. The callback function for filter accepts 3 arguments, the current element, the index, and the array. If no elements pass the test, it returns an empty array. You can use it to remove null and undefined from an array.
-
What Is the Reduce Method, and How Does It Work?
The reduce method is a function that allows you to process an array and condense it into a single value. This value can be a number,string,object, or another array. It applies a function to each element in an array, passing the result of each calculation on to the next. It takes two parameters an accumulator and the current value. If you do not provide an accumulator reduce will start from the second element.
-
What Is Method Chaining, and How Does It Work?
Method chaining is a technique where you call several methods one after another. You can use it on many different values strings/arrays/objects.
const result = " Hello, World! " .trim() .toLowerCase() .replace("world", "JavaScript");In this example .trim,.toLowerCase(),.replace are chained together. It's often good practice to break long chains into multiple steps. -
How Does the Sort Method Work?
The sort method is used to arrange the elements of an array and returns a reference to the sorted array. No copy is made. The sort method takes a function parameter to decide on how to sort. The sort method converts the elements to strings, then compares the sequences of their UTF-16 unit values. In order to bypass this, you can use a function like a - b to do the sorting.
-
How Do the every() and some() Methods Work?
The every() and some() methods will allow you to check all elements for a condition. The every() method returns true if every element returns true. The some() method returns true if at least one element passes the test. These methods are very good at making your code cleaner and more expressive.
-
What Is an API, and What Are Web APIs?
API stands for Application Programming Interface. APIs establish rules that allow applications to communicate and exchange data. APIs allow developers to create more complex functionality. Web APIs are often divided into two categories, browser APIs and third-party APIs. Browser APIs expose data from the browser, examples include : DOM API, Storage API. Browser APIs are built into browsers. You can also use third party APIs that are not defaulted into teh browser. An example would be the Google Maps API, weather APIs, social media APIs, payment APis, etc.
-
What Is the DOM, and How Do You Access Elements?
DOM - Document Object Model, its a programming interface that lets you interact with HTML documents. The HTML document is represented as a tree of nodes. The document is the root of the hierarchy, it has one child the HTML element. The HTML element has two children: head/body. The head contains the meta data, the body contains the visible content. You can use getElementByID() to get an HTML element with a specific id.
const container = document.getElementById("container");In this example you are grabbing a div element with the set id of container and assigning it to a JS variable container. You can use a querySelector() to get a CSS selector.const highlightEl = document.querySelector(".highlight");In this example you are setting a JS constant for an element's class selector. -
How Do DOM Nodes Exist Relative to Each Other in the DOM Tree?
DOM nodes have direct and indirect relationships with one another. The root of the document is the html element, all other nodes are descendants of this node. Below the root node, there are parent nodes that contain other elements. A child is an element contained within another element. the body element may be the parnet of a paragraph element which is a child. Sibling nodes are elements that share the same parent, list elements are often siblings of each other. Indirect relationships also exist across levels. An element is considered a descendant if it can be reached going downwards from its ancestor.
-
What Is the querySelectorAll() Method, and When Should You Use It?
You can use the querySelectorAll in order to get all elements that match a CSS selector. The document object and pass it a string with the CSS selector as an argument. If the string isn't valid a SyntaxError will be thrown. querySelectorAll returns a Nodelist object that match the CSS selector. You can use it to select all elements, a class, id, all elements with an attribute, you can even use a complicated css selector like "ul.ingredients li".
-
How Do You Create New Nodes Using innerHTML and createElement()?
innerHTML is a property of Element objects that you can use to set their HTML markup. You can select an element like a div and then add elements within that container.
container.innerHTML = "In this example we take a selector assigned to a container variable and add an unordered list. innerHTML can be very helpful, but it does have some security risks. You should not use innerHTML if the user can enter data into it, in these cases use textContent instead. You can also use the createElement() to create a new element.- Cheese
- Tomato
const img = document.createElement("img");createElement creates an HTML element if the document is an HTML document. Once you create the element you can attach it using the appendChild() method and some others.container.appendChild(img);is an example of appendchild of an img to a div named container selected earlier. -
What Is the Difference Between innerText, textContent, and innerHTML?
innerText, textContent, innerHTML are used to change the content of HTML elements. innerText represents the visible content of an html element
container.innerText = "JavaScript is awesome!";in this you are replacing the text and adding a line break. This can create problems by triggering reflow which calculates positions of certain elements and can be intensive. textContent returns the plain text of an element, including text within its descendants. The main difference between innerText and textContent is that textContent reveals all content hidden or not.container.textContent = "New content";if you replace the value of textContent it will remove all children and replace them with a single text node. -
How Do You Add and Remove Nodes from the DOM with appendChild() and removeChild()?
When you need to add or remove nodes from the DOM you can use appendChild() and removeChild(). appendChild adds a note to the end of list of children of a parent. To remove a node from the DOM you can use removeChild() method
parentNode.removeChild(childNode); -
How Do the Navigator, Window, and Document Work?
You will come across Navigator, Window and Document interfaces. An interface is a collection of methods and properties that define an object. Navigator interface provides information about the browser environment. Things like the user agent string, platform, and version of browser.
console.log(navigator.userAgent);in this you will get information about the users browser which can be useful if you want to have content based on browser. The Window interface is a browser window that contains the DOM document. It provides methods and properties for interacting with the browser window such as resizing, opening new, and navigating to URLs.console.log(window.innerWidth);this will display the inner width of the browser window to console. Most of the time you don't need to access Window since it exists in the global scope of your JS. The Document interface is where the DOM document is displayed.console.log(document.children);this will display an HTMLCollection object that has all the children of the document. -
How Do You Add Attributes with setAttribute()?
setAttribute is used to add attributes to HTML elements.
para.setAttribute("class", "my-class");When using set attribute you first name the attribute, then the value. outerHTML is a way to get a display of the HTML elements and the code within. -
What Is the Event Object?
The Event object is a payload that triggers when a user interacts with your page in some way. The Event object has a number of properties that are helpful. All Events have a type property, this reveals the type of event like "keydown" or "click". These are some values you may pass to addEventListener(). Event objects will also always have a target property. The target is usually to some HTMLElement. Events also have methods, a commonly used one is preventDefault(). Which can be used to prevent default behavior like form submit POST. The stopPropagation() prevents an even from propogating parent elements.
-
How Does the addEventListener Method Work?
The addEventListener() is used to listen for events, it takes two arguments: the event you want to listen for and a function that occurs on the event. The element monitors for events and monitors for them such as "click".
element.addEventListener("click", handleClick);In this example you have a function created outside called handleClick to run when the element is clicked. The EventListener automatically calls the method handleEvent(). There are many events to listen for including mouseover, mouseout, keydown, keyup, submit. -
How Does the removeEventListener Method Work?
The removeEventListener() method is used to remove an event listener previously added. This takes two arguments the event you want to remove, and the listener function. There is an optional third argument of options or useCapture. The options argument specifies the options for the listener such as passive or once. The useCapture specifies whether the event be captured in the propagation phase. removeEventListener is often used when closing a modal in a web app or when logging out of an application.
-
What Are Inline Event Handlers, and Why Is It Best Practice to Use addEventListener Instead?
It is not recommended but inline event handlers are attributes of html elements that are used to execute code on the event.
this is an example of an inline event. You can also define a function in a script element and then call it from the inline click. You can only attach one inline event handler to an element. -
How Do You Manipulate Styles Using Element.style and Element.classList?
There will be times when you need to manipulate HTML inside your .js file. Element.style is a read only property that represents the inline style of an element you can use it to get or set styles.
paraEl.style.color = "red";example where paraEl was retrieved earlier. You can also manipulate styles using the classList property. It can be used to add, remove, or toggle classes on an element.paraEl.classList.add("highlight");in this we have added the class of highlight to the p element. If you need to remove a class from an element you can use classList.remove(). You can use classList.toggle() method to toggle class to an element. -
What Is the DOMContentLoaded Event, and How Does It Work?
The DOMContentLoaded event is fired when everything has been loaded and parsed. These events will not wait for styles/iomages etc to be loaded. This differs from the load event which waits for everything to be loaded.
document.addEventListener("DOMContentLoaded", function () { console.log("DOM is loaded.");});This example displays a cl when the event has been met. -
How Do the setTimeout and setInterval Methods Work?
To have things happen at a delay or repeat you can use setTimeOut() or setInterval() which accept a function and a delay as parameters. setTimeOut() lets you delay an action.
setTimeout(function () {console.log("This runs after 3 seconds");}, 3000);in this example the function will run after 3 seconds, since the delay is in milliseconds.setTimeout(() => {console.log("This runs after 3 seconds"); }, 3000);You can also use arrow functions like this example. You can also use clearInterval() to stop the interval from repeating. -
What Is the requestAnimationFrame() API, and How Can It Be Used to Set Up an Animation Loop?
requestAnimationFrame() is a method that alows you to schedule the next step of your animation before the next screen repaint. The next screen repaint is when the browser refreshes the visual display typically around 60 times or 60 fps. To use requestAnimationFrame() you just call it and pass a callback function to it.
-
What Is the Web Animations API, and How Does It Relate to CSS Animation Properties?
The Web Animations API allow you to create and control animations within JS. At the core of the WAAPI is the Animation constructor which has a significant method of animate(). This allows you to create animation by specifying keyframes and options like duration, direction, easing, and iterations.
const animation = square.animate([{ transform: "translateX(0px)" }, { transform: "translateX(100px)" }], { duration: 2000, // makes animation lasts 2 seconds iterations: Infinity, // loops indefinitely direction: "alternate", // moves back and forth easing: "ease-in-out" // smooth easing});. Instance Methods: play(), pause(), reverse(), finish(), cancel() Properties: playbackRate, currentTime, startTime, effect, timeline, playState, finished, onfinish, oncancel WAAPI extends the capabiliteis of CSS animations by providing dynamic control over them inside JavaScript. CSS animation is ideal for simple declarative animations, but if your animation needs to respond to user interaction clicks/scroll or you want the user to be able to pause/reverse/change speed WAAPI is better. -
What Is the Canvas API, and How Does It Work?
The Canvas API is a tool that lets you manipulate graphics right inside JS. The canvas element in HTML allows you to draw using instance methods and properties. The Canvas API provides everything you need to create amazing visuals, including shapes, text, animations, and even games. It has interfaces like HTMLCanvasElement, CanvasRenderingContext2D, CanvasGradient, CanvasPattern, TextMetrics. First you need to create a canvas element in html like
<canvas id="my-canvas"> </canvas>. You can give width and height to your canvas as html attributes or within the HTMLCanvasElement interface. IF you use the getContext() method of the HTMLCanvasElement you can get the drawing elements for 2d by using '2d'.const ctx = canvas.getContext('2d');if you CL the variable created you will get -
How Do You Open and Close Dialog Elements Using JavaScript?
Dialogs let you display important information or actions to users. You can do this with both modal and non modal dialogs. A modal dialog is a type of dialog that forces the user to interact with it before they can access the rest of the application or webpage. It blocks interaction with other content until the user completes an action. A non modal allows the user to continue interacting with parts of the page or application when the dialog is open. You will learn about showModal() and close() methods. When you want to make sure the user focuses on the materials use the showModal() method.
-
What Is the Change Event, and How Does It Work?
The change event is a special event fired when the user modifies the value of input elements. Including: checkbox tick/untick, radio button ticked, making a selection in a picker or dropdown, when input loses focus after user changed value, when the value is confirmed.
selectMenu.addEventListener("change", (event) => {console.log(`You selected: ${event.target.value}`);});in this example, evertyime the user selects an option the selected value with be logged. The change event generates an Event object, but it does not generate custom implementation. This is different than the input event which generates a dedicated object. input events also trigger when the user types into a field. -
How Do Event Bubbling, and Event Delegation Work?
Event bubbling or propagation refers to how an event bubbles up to parent objects when triggered. If you have a span inside of a paragraph, when the span is clicked this also goes to the p element it is nested in. You could even have a response from both elements for an event. If you add a stopPropagation() to the span element, then the paragraph element would no longer receive the event data. You can also delegate from a parent to the children elements where the elements being clicked are apart of the parent.
-
How Do You Make Dynamic and Interactive Content Accessible?
You learned how semantic markup and ARIA attributes make content accessible. Since pages update dynamically through JavaScript, its important to make sure these changes are also in the HTML. It is important to update teh associated ARIA attributes when changing elements with JavaScript including aria-expanded and aria-controls.
-
What Is the aria-expanded Attribute, and How Does It Work?
The aria-expanded attribute is used to indicate if something is expanded or collapsed. It's used with menus it's set to true when exapnded, false when collapsed. The aria-expanded attribute is applied to the interactive element like a button that controls the expansion. If the menu is expanded by default aria-expanded should be set to true. aria-owns can be used with aria-control to establish a programmatic control between the trigger and element.
button.addEventListener('click', () => { const expanded = button.getAttribute('aria-expanded') === 'true'; button.setAttribute('aria-expanded', String(!expanded)); menu.hidden = expanded; });In this example the list for expansion immediately follows the interaction making it easier for screen readers to navigate the controls. You can use aria owns when you aren't able to place the code immediately after but it has drawbacks. It creates verbosity since the screen reader reads out all the contents when expanded. Ideally the expanded content should be placed after the control element and the aria-owns should be a worst-case scenario. -
What Is the aria-live Attribute, and How Does It Work?
The aria-live attribute creates a region which you can use to notify screen readers of dymamic content. Common uses of live regions include messages after actions are tqaken, content that updates periodically(ticker, countdown) or general status messages. Screen readers can only focus on one place at a time which means users won't notice changes on a different part of the page. Live regions notify the user of changes in real time. 3 values for the attribute: assertive - update is important, highest priority. This means any change in the live region will interrupt the user and can be disruptive so it should only be used for time sensitive materials or critical conditions. The next option is polite: this means the update is not urgent this will wait for the screen reader makes the current announcement or when the user finishes typing. This one is most frequently used. The lowest priority is off which means that the update will not be announced unless the content is an element that currently is keyboard focused. This is not commonly used. aria-live is not required if the updated information is within an element with ARIA roles alert, log, marquee, status, or timer.
-
What Are Some Common ARIA States Used on Custom Control Elements?
Semantic form control elements like input, select, textarea, button, fielset have built in states that are conveyed to assistive technologies. You could use disabled attribute to disable a button or the checked attribute to indicate that a checkbox is checked. If you are using a custom control you need to use ARIA attributes to convey states to assistive technologies. The first ARIA attribute is aria-selected this is used to indicate if an element is selected. aria-disabled is used to indicate an element is disabled only to screen readers. aria-disabled does not actually disable the element, it is up to you the developer to make the element behave and look disabled. aria-haspop this is used to indicate interactive element will trigger a popup when activated. You can use aria-popup when the popup has one of the roles: menu, listbox, tree, grid, dialog. The aria-haspopup must be one of these roles or true which default to menu. The aria-haspopup is used to indicate a File will open when popup menus are activated. You will need to use JS to show and hide the popup menu and to implement proper keyboard shortcuts. ARIA menu refers to a specific type of menu, a list of actions the user can invoke, similar to a menu in a desktop app. aria-required is used to indicate a field needs to be filled for a form to be submitted. If you use the form element required attribute you do not need to use aria required, but if you use a custom form control. aria-required can be used on native form inputs and someitmes preferred over native required. aria-checked is used to indicate checked state commonly used on custom checkboxes. Native checkboxes have a built in checked state, but custom ones will need this attribute. You will need to set aria checked to true when selected, false when unchecked.
-
What Is the aria-controls Attribute, and How Does It Work?
The aria-controls is used to create a programmatic relationship between an element that controls the presence of another and the element controlled.
is an example of how aria-controls can be used on a button. In most tabbed interfaces the first tab panel is visible by default, so the first one will have aria-selected set to true. The aria-controls attribute is used to associate the button with the section that it controls.aria-labelledby is used to point to corresponding tab to give an accessible name. You will need to use JS to update which button is currently visible and the arias-selected set to true.
What Are Some Examples of Common JavaScript Errors?
There are four types of errors, SyntaxError, ReferenceError, TypeError,RangeError. SyntaxError - incorrectly written code forgetting , or (). ReferenceError - different types either a variable that is used but not defined, or variable that is accessed before definition. TypeError - performing an operation on not the right type. Like using an object when you need a function. RangeError - using a variable outside of what JavaScript can handle, a negative index etc.
How Does the Throw Statement Work?
throw in JS is used to throw a user defined exception. Unexpected event happens and disrupts the flow. throw expression; the expression is the object or value representing the exception. Examples are error, typeError, rangeError. function validateNumber (input) { if (type of input !== "number" { throw new TypeError("Expect a number but received " + typeof input)} return input * x;}
How Does try...catch...finally Work?
The try...catch...finally block can help you to manage errors. The try block is used to wrap code that might throw an error. The catch block captures and handles errors that occur in the try block. The finally block runs after try and catch regardless of if there was an error or not. try {console.log("Starting to process input...");const result = processInput(9); console.log("Processed result:", result); } catch (error) { console.error("Error occurred:", error.message); } . We call the function in the try block, and this will be caught in the catch block. The error will be passed with information about that error. We use console.error to log error messages. Then the finally code block will happen regardless.
How Does the Debugger Statement Work?
The debugger statement is a tool that lets you pause code at a specific line to investigate. JS executes code from top to bottom. When it hits a debugger statement, it pauses execution at that line. This gives you the chance to inspect variables and check functions. This only happens if the browser tools are open. Otherwise, the debugger statement is ignored. The browser will pause the code the page will not reload unless manually triggered. Place a debugger; statement at the line you want to pause at.
What Are Some Examples of Using Advanced JavaScript Debugging Techniques?
Debugging should go beyond console.log() statements. First you can use breakpoints. These let you pause your code at a line of choice. You can do this in the developer tools in the sources tab, and click on the line you want to put the breakpoint at. You can also right click on a line and add a conditional breakpoint. Watch expressions allow you to monitor values even if they are out of scope. To add one go to sources tab of dev tools, look for watch and press + to add it. Profiling helps identify performance bottlenecks. Go to performance tab, click record and perform the actions you want to profile. Inspecting network requests can help debug issues such as parameter errors, address errors or server errorrs. You can find this in the network table of the dev tools. console.table() provides a table in the console. It takes one mandatory argument (array/object) and an option argument to specify properties or columns. console.dir() lets you display an interactive list of properties of an object.
What Are Regular Expressions, and What Are Some Common Methods?
Regular expressions(regex) are a feature of many programming languages. It is a special syntax to create a pattern to be used against a string, extract text, etc. const regex = /freeCodeCamp/; in JavaScript you define regex between forward slashes. The test() method is present on RegExp objects. If you use regex.text("e"); it will return false even though freeCodeCamp has an 'e'. It will return true if all the text is included within. If you use the match() method on the above cove it will display the text and also the groups property which shows any captured groups(undefined here). It will display the index which is where the string is (in this case 0). Finally, it will display the input it was displayed on. Strings have the replace() method which can take a regular expression to match and the string to replace it with.
What Are Some Common Regular Expression Modifiers Used for Searching?
Modifiers or flags modify the behavior of a regex. For example const regex = /freeCodeCamp/i; will ignore the case. There are many other flags including the g flag or global modifier which allows your regex to match a pattern more than once. const regex = /freeCodeCamp/gi; in this case we are using both lower case and global. Which can lead to unexpected results when chaining together logs since it uses the lastIndex to track previous matches. The $ sign anchor(before last slash) says to match the end of the string. The ^(after first slash) says to match the start of a string. These do not work if the string starts to enter new lines, unless you use the m flag at the end of the regex this is for multi-line modifier. The d flag is for indices which expands what you get in the match object. There is also the u flag which is the unicode modifier to allow matching special unicode characters. the v flag expands the unicode matching. The y flag is for sticky which will return null if there is not a match at lastIndex. The s flag which is a single line modifier. The single line allows a . to be used to match linebreaks making a string a single line of text. i and g flags are the most commonly used.
How Can You Match and Replace All Occurrences in a String?
If you have multiple occurrences to match, match() and replace() will only replace the first one. You can replace both using the g flag like this const regex = /freecodecamp/g; const replaced = str.replace(regex, "freeCodeCamp");
Although, you can also use the methods matchAll() and replaceAll(). MatchAll() returns an object called an iterator. The iterator has a next() method which can get the next value. You can extract all matches by converting to an array with the iterator using Array.from() .
What Are Character Classes, and What Are Some Common Examples?
The wildcard is represented by a period (.) and matches any single character except line breaks. To use the wildcard to match line breaks you would need the s flag. You can use character classes to narrow down searches, instead of searching for /0|1|2 for numerical values(0-9) you could also use the \d character class to find 0-9. If you want any letter you can use \w. A word character is any letter a-z or number 0-9 or _. The \s will match any white space. You can negate using uppercase const regex = /\D/; for example would match any character that is not 0-9. If you want your own characters you can use the square brackets /[abcdf]/ would allow you to find just those characters. If you have a range you can use a hyphen /[a-g]/ which all regex is case sensitive by default. If you want uppercase you should include them like /[a-zA-z]/. If you want a hyphen you have to put it at the beginning like /[-a-z]/.
What Are Lookahead and Lookbehind Assertions, and How Do They Work?
The lookahead will match a pattern followed by a pattern. First you will start with the pattern to match, then (?=) before the second slash. const regex = /free(?=code)/i for example will only match free if it is followed by code. For free that is not followed by code: /free(?!code)/i. Lookbehind matches preceding the pattern, /(?<=free)code/i would look for code with free before it. Regex.prototype.test only confirms if a string matches. Lookaheads and lookbehinds are useful for matching text without impacting the returned value.
What Are Regex Quantifiers, and How Do They Work?
If you want to match a 4 digit identification code you may use something like const regex = /^\d\d\d\d$/;. However you can use a quantifier to accomplish the same thing like /^\d{4}$/ to allow four or more digits you can use a comma /^\d{4,}$/ . If you want a range you can use /^\d{4,6}$/ which would give 4-6 digits. Special shorthand for a single optional character is ?. The match previous character zero or more times is the asterisk *. The + symbol means use the quantifier as a min with no max.
What Are Capturing Groups and Backreferences, and How Do They Work?
A capturing group allows you to capture a matched string. To capture code : /free(code)camp/i. You can use match to capture the element desired. You can also use this with replace in order to replace the code with a string. If you add a + like (co+de) you can get more os or an undetermined number, but in order to do this you must also add a backreference. const regex = /free(co+de)camp/i; console.log("freecoooooooodecamp".replace(regex, "paid$1world")); In this code we add the backreference where the capture is and 1 is because the capture is in the first group. To get both copies to be the same you need to reference the first capture with the second like this /free(co+de)camp.*free\1camp/i;. If you wish to define a capture group you can do it as follows with a ? and <> const regex = /free(?co+de)camp.*free\1camp/i;.
What Are Some Ways to Validate Forms Using JavaScript?
In HTML you can restrict values that a user can submit, but if you want to get more complex you need JavaScript. textarea and input elements expose constraint validation API. This allows you to set validation like minimum length and pattern matching. If you set the required type to email you can restrict data to require an @. However, users can still bypass this very easily by using something like @email.com We can use the pattern attribute to specify the email address must end in a company email address. This would look like: . If you try to submit something different it will display a message saying "Please match the requested format." You can use the checkValidity() method input.addEventListener("input", (e) => { console.log (e.target.checkValidity())\}) This returns a boolean based on the HTML validation. However, the message will still be "Please match the requested format." Using the setCustomValidity method if (!e.target.checkValidity()) { e.target.setCustomValidity( "You must use a company email address that ends in @sampleCompany.com" );
You can use a console.log(e.target.validity); to see the validity property. Some other useful properties are valueMissing and patternMismatch.
What Is the Purpose of the preventDefault() Method?
preventDefault() prevents default behavior like click toggle of a checkbox. We need to hook into the keydown event like this const input = document.querySelector("input");input.addEventListener("keydown", (e) => {}) By default this will show the value of the key pressed such as e, if you change the code to include { e.preventDefault(); output.innerText = `You pressed the ${e.key} key`;} within the code block you can set your own event handling. You can also use the preventDefault() method to stop a page reload on form submission.
How Does the Submit Event Work With Forms?
The first way to submit a form is when the user clicks a button with type submit. The second is when the user presses the Enter key on any editable input field in the form. The third is through a JavaScript requestSubmit() or submit() methods. The first attribute to look at is the action attribute. This should contain the URL or path for the domain. This determines where the data is sent. If there is no action attribute it will send to the current page. To set the action attribute use the form element like this