curriculum/challenges/english/blocks/review-javascript/6723d3cfdd0717d3f1bf27e3.md
Review the concepts below to prepare for the upcoming prep exam.
While HTML and CSS provide website structure, JavaScript brings interactivity to websites by enabling complex functionality, such as handling user input, animating elements, and even building full web applications.
Data types help the program understand the kind of data it's working with, whether it's a number, text, or something else.
"I like coding" and 'JavaScript is fun' are examples of strings.true or false. You can use a boolean to represent a condition, such as isLoggedIn = true.undefined value is a variable that has been declared but not assigned a value. A null value is an empty value, or a variable that has intentionally been assigned a value of null.Here, the pet object has three properties or keys: name, age, and type. The values are Fluffy, 3, and dog, respectively.
let pet = {
name: "Fluffy",
age: 3,
type: "dog"
};
In this example below, two symbols are created with the same description, but they are not equal.
:::interactive_editor
const crypticKey1= Symbol("saltNpepper");
const crypticKey2= Symbol("saltNpepper");
console.log(crypticKey1 === crypticKey2); // false
:::
Number data type, you can use the BigInt data type to represent integers of arbitrary length.By adding an n to the end of the number, you can create a BigInt.
const veryBigNumber = 1234567890123456789012345678901234567890n;
let keyword.let cityName;
=.cityName = "New York";
let can be reassigned a new value.:::interactive_editor
let cityName = "New York";
cityName = "Los Angeles";
console.log(cityName); // Los Angeles
:::
let, you can also use const to declare a variable. However, a const variable cannot be reassigned a new value.const cityName = "New York";
cityName = "Los Angeles"; // TypeError: Assignment to constant variable.
const find uses in declaring constants, that are not allowed to change throughout the code, such as PI or MAX_SIZE.cityName, isLoggedIn, and veryBigNumber._, or $._ and $.age and Age are different variables.let correctWay = 'This is a string';
let alsoCorrect = "This is also a string";
let firstName = "John";
firstName = "Jane"; // Reassigning the string to a new value
+ operator is one of the simplest and most frequently used methods to concatenate strings.:::interactive_editor
let studentName = "Asad";
let studentAge = 25;
let studentInfo = studentName + " is " + studentAge + " years old.";
console.log(studentInfo); // Asad is 25 years old.
:::
+= operator. This is helpful when you want to build upon a string by adding more text to it over time.:::interactive_editor
let message = "Welcome to programming, ";
message += "Asad!";
console.log(message); // Welcome to programming, Asad!
:::
concat() method. This method joins two or more strings together.:::interactive_editor
let firstName = "John";
let lastName = "Doe";
let fullName = firstName.concat(" ", lastName);
console.log(fullName); // John Doe
:::
console.log()console.log() method is used to log messages to the console. It's a helpful tool for debugging and testing your code.:::interactive_editor
console.log("Hello, World!");
// Output: Hello, World!
:::
let message = "Hello, World!"; // first statement ends here
let number = 42; // second statement starts here
//.// This is a single-line comment and will be ignored by the JavaScript engine
/* to start the comment and */ to end the comment./*
This is a multi-line comment.
It can span multiple lines.
*/
let error = 404; // JavaScript treats error as a number
error = "Not Found"; // JavaScript now treats error as a string
int error = 404; // value must always be an integer
error = "Not Found"; // This would cause an error in C#
typeof Operatortypeof operator is used to check the data type of a variable. It returns a string indicating the type of the variable.:::interactive_editor
let age = 25;
console.log(typeof age); // "number"
let isLoggedIn = true;
console.log(typeof isLoggedIn); // "boolean"
:::
null. The typeof operator returns "object" for null values.:::interactive_editor
let user = null;
console.log(typeof user); // "object"
:::
:::interactive_editor
const developer = "Jessica";
console.log(developer[0]); // J
:::
\n (Newline Character): You can create a newline in a string by using the \n newline character.:::interactive_editor
const poem = "Roses are red,\nViolets are blue,\nJavaScript is fun,\nAnd so are you.";
console.log(poem);
:::
\) in front of the quotes.:::interactive_editor
const statement = "She said, \"Hello!\"";
console.log(statement); // She said, "Hello!"
:::
:::interactive_editor
const name = "Jessica";
const greeting = `Hello, ${name}!`;
console.log(greeting); // "Hello, Jessica!"
:::
charCodeAt() Method and the fromCharCode() MethodcharCodeAt() Method: This method is called on a string and returns the ASCII code of the character at a specified index.:::interactive_editor
const letter = "A";
console.log(letter.charCodeAt(0)); // 65
:::
fromCharCode() Method: This method converts an ASCII code into its corresponding character.:::interactive_editor
const char = String.fromCharCode(65);
console.log(char); // A
:::
indexOf Method: This method is used to search for a substring within a string. If the substring is found, indexOf returns the index (or position) of the first occurrence of that substring. If the substring is not found, indexOf returns -1, which indicates that the search was unsuccessful.:::interactive_editor
const text = "The quick brown fox jumps over the lazy dog.";
console.log(text.indexOf("fox")); // 16
console.log(text.indexOf("cat")); // -1
:::
includes() Method: This method is used to check if a string contains a specific substring. If the substring is found within the string, the method returns true. Otherwise, it returns false.:::interactive_editor
const text = "The quick brown fox jumps over the lazy dog.";
console.log(text.includes("fox")); // true
console.log(text.includes("cat")); // false
:::
slice() Method: This method returns a new array containing a shallow copy of a portion of the original array, specified by start and end indices. The new array contains references to the same elements as the original array (not duplicates). This means that if the elements are primitives (like numbers or strings), the values are copied; but if the elements are objects or arrays, the references are copied, not the objects themselves.:::interactive_editor
const text = "freeCodeCamp";
console.log(text.slice(0, 4)); // "free"
console.log(text.slice(4, 8)); // "Code"
console.log(text.slice(8, 12)); // "Camp"
:::
toUpperCase() Method: This method converts all the characters to uppercase letters and returns a new string with all uppercase characters.:::interactive_editor
const text = "Hello, world!";
console.log(text.toUpperCase()); // "HELLO, WORLD!"
:::
toLowerCase() Method: This method converts all characters in a string to lowercase.:::interactive_editor
const text = "HELLO, WORLD!"
console.log(text.toLowerCase()); // "hello, world!"
:::
replace() Method: This method allows you to find a specified value (like a word or character) in a string and replace it with another value. The method returns a new string with the replacement and leaves the original unchanged because JavaScript strings are immutable.:::interactive_editor
const text = "I like cats";
console.log(text.replace("cats", "dogs")); // "I like dogs"
:::
repeat() Method: This method is used to repeat a string a specified number of times.:::interactive_editor
const text = "Hello";
console.log(text.repeat(3)); // "HelloHelloHello"
:::
trim() Method: This method is used to remove whitespaces from both the beginning and the end of a string.:::interactive_editor
const text = " Hello, world! ";
console.log(text.trim()); // "Hello, world!"
:::
trimStart() Method: This method removes whitespaces from the beginning (or "start") of the string.:::interactive_editor
const text = " Hello, world! ";
console.log(text.trimStart()); // "Hello, world! "
:::
trimEnd() Method: This method removes whitespaces from the end of the string.:::interactive_editor
const text = " Hello, world! ";
console.log(text.trimEnd()); // " Hello, world!"
:::
prompt() Method: This method of the window is used to get information from a user through the form of a dialog box. This method takes two arguments. The first argument is the message which will appear inside the dialog box, typically prompting the user to enter information. The second one is a default value which is optional and will fill the input field initially.const answer = window.prompt("What's your favorite animal?"); // This will change depending on what the user answers
Number type includes integers, floating-point numbers, Infinity and NaN. Floating-point numbers are numbers with a decimal point. Positive Infinity is a number greater than any other number while -Infinity is a number smaller than any other number. NaN (Not a Number) represents an invalid numeric value like the string "Jessica".+) is used to calculate the sum of two or more numbers.-) is used to calculate the difference between two numbers.*) is used to calculate the product of two or more numbers./) is used to calculate the quotient between two numbersInfinity.%) returns the remainder of a division.**) raises one number to the power of another.+ operator with a number and a string, JavaScript will coerce the number into a string and concatenate the two values. When you use the -, * or / operators with a string and number, JavaScript will coerce the string into a number and the result will be a number. For null and undefined, JavaScript treats null as 0 and undefined as NaN in mathematical operations.:::interactive_editor
const result = 5 + '10';
console.log(result); // "510"
console.log(typeof result); // string
const subtractionResult = '10' - 5;
console.log(subtractionResult); // 5
console.log(typeof subtractionResult); // number
const multiplicationResult = '10' * 2;
console.log(multiplicationResult); // 20
console.log(typeof multiplicationResult); // number
const divisionResult = '20' / 2;
console.log(divisionResult); // 10
console.log(typeof divisionResult); // number
const result1 = null + 5;
console.log(result1); // 5
console.log(typeof result1); // number
const result2 = undefined + 5;
console.log(result2); // NaN
console.log(typeof result2); // number
:::
:::interactive_editor
const result = (2 + 3) * 4;
console.log(result); // 20
const result2 = 10 - 2 + 3;
console.log(result2); // 11
const result3 = 2 ** 3 ** 2;
console.log(result3); // 512
:::
++num increases the value of the variable first, then returns a new value. The postfix notation num++ returns the current value of the variable first, then increases it.:::interactive_editor
let x = 5;
console.log(++x); // 6
console.log(x); // 6
let y = 5;
console.log(y++); // 5
console.log(y); // 6
:::
:::interactive_editor
let num = 5;
console.log(--num); // 4
console.log(num--); // 4
console.log(num); // 3
:::
+=) Operator: This operator performs addition on the values and assigns the result to the variable.-=) Operator: This operator performs subtraction on the values and assigns the result to the variable.*=) Operator: This operator performs multiplication on the values and assigns the result to the variable./=) Operator: This operator performs division on the values and assigns the result to the variable.%=) Operator: This operator divides a variable by the specified number and assigns the remainder to the variable.**=) Operator: This operator raises a variable to the power of the specified number and reassigns the result to the variable.true or false.==) Operator: This operator uses type coercion before checking if the values are equal.:::interactive_editor
console.log(5 == '5'); // true
:::
===) Operator: This operator does not perform type coercion and checks if both the types and values are equal.:::interactive_editor
console.log(5 === '5'); // false
:::
!=) Operator: This operator uses type coercion before checking if the values are not equal.!==) Operator: This operator does not perform type coercion and checks if both the types and values are not equal.>) Operator: This operator checks if the value on the left is greater than the one on the right.>=) or Equal Operator: This operator checks if the value on the left is greater than or equal to the one on the right.<) Operator: This operator checks if the value on the left is less than the one on the right.<=) or Equal Operator: This operator checks if the value on the left is less than or equal to the one on the right.:::interactive_editor
const str = '42';
const num = +str;
console.log(num); // 42
console.log(typeof num); // number
:::
-) Operator: This operator negates the operand.:::interactive_editor
const num = 4;
console.log(-num); // -4
:::
!) Operator: This operator flips the boolean value of its operand. So, if the operand is true, it becomes false, and if it's false, it becomes true. &) Operator: This operator returns a 1 in each bit position for which the corresponding bits of both operands are 1.&=) Operator: This operator performs a bitwise AND operation with the specified number and reassigns the result to the variable.|) Operator: This operator returns a 1 in each bit position for which the corresponding bits of either or both operands are 1.|=) Operator: This operator performs a bitwise OR operation with the specified number and reassigns the result to the variable.^) Operator: This operator returns a 1 in each bit position for which the corresponding bits of either, but not both, operands are 1.~) Operator: This operator inverts the binary representation of a number.<<) Operator: This operator shifts all bits to the left by a specified number of positions.>>) Operator: This operator shifts all bits to the right.if/else if/else: An if statement takes a condition and runs a block of code if that condition is truthy. If the condition is false, then it moves to the else if block. If none of those conditions are true, then it will execute the else clause. Truthy values are any values that result in true when evaluated in a Boolean context like an if statement. Falsy values are values that evaluate to false in a Boolean context.:::interactive_editor
const score = 87;
if (score >= 90) {
console.log('You got an A');
} else if (score >= 80) {
console.log('You got a B'); // You got a B
} else if (score >= 70) {
console.log('You got a C');
} else {
console.log('You failed! You need to study more!');
}
:::
if else statements.:::interactive_editor
const temperature = 30;
const weather = temperature > 25 ? 'sunny' : 'cool';
console.log(`It's a ${weather} day!`); // It's a sunny day!
:::
&&) Operator: This operator checks if both operands are truthy. If the first value is truthy, then it will return the second value. If the first value is falsy, then it will return the first value.:::interactive_editor
const result = true && 'hello';
console.log(result); // hello
:::
||) Operator: This operator checks if at least one of the operands is truthy. If the first value is truthy, then it is returned. If the first value is falsy, then the second value is returned.??) Operator: This operator will return a value only if the first one is null or undefined.:::interactive_editor
const userSettings = {
theme: null,
volume: 0,
notifications: false,
};
let theme = userSettings.theme ?? 'light';
console.log(theme); // light
:::
Math ObjectMath.random() Method: This method generates a random floating-point number between 0 (inclusive) and 1 (exclusive). This means the possible output can be 0, but it will never actually reach 1.Math.max() Method: This method takes a set of numbers and returns the maximum value.Math.min() Method: This method takes a set of numbers and returns the minimum value.Math.ceil() Method: This method rounds a value up to the nearest whole integer.Math.floor() Method: This method rounds a value down to the nearest whole integer.Math.round() Method: This method rounds a value to the nearest whole integer.:::interactive_editor
console.log(Math.round(2.3)); // 2
console.log(Math.round(4.5)); // 5
console.log(Math.round(4.8)); // 5
:::
Math.trunc() Method: This method removes the decimal part of a number, returning only the integer portion, without rounding.Math.sqrt() Method: This method will return the square root of a number.Math.cbrt() Method: This method will return the cube root of a number.Math.abs() Method: This method will return the absolute value of a number.Math.pow() Method: This method takes two numbers and raises the first to the power of the second.isNaN(): NaN stands for "Not-a-Number". It's a special value that represents an unrepresentable or undefined numerical result. The isNaN() function property is used to determine whether a value is NaN or not. Number.isNaN() provides a more reliable way to check for NaN values, especially in cases where type coercion might lead to unexpected results with the global isNaN() function.:::interactive_editor
console.log(isNaN(NaN)); // true
console.log(isNaN(undefined)); // true
console.log(isNaN({})); // true
console.log(isNaN(true)); // false
console.log(isNaN(null)); // false
console.log(isNaN(37)); // false
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN(Number.NaN)); // true
console.log(Number.isNaN(0 / 0)); // true
console.log(Number.isNaN("NaN")); // false
console.log(Number.isNaN(undefined)); // false
:::
parseFloat() Method: This method 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 later on.parseInt() Method: This method parses a string argument and returns an integer. parseInt() stops parsing at the first non-digit it encounters. For floating-point numbers, it returns only the integer part. If it can't find a valid integer at the start of the string, it returns NaN.toFixed() Method: This method is called on a number and takes one optional argument, which is the number of digits to appear after the decimal point. It returns a string representation of the number with the specified number of decimal places.null and undefined Data Typesundefined: A variable is undefined when it has been declared but hasn't been assigned a value. It's the default value of uninitialized variables and function parameters that weren't provided an argument. undefined converts to NaN in numeric contexts, which makes all numeric comparisons with undefined return false.:::interactive_editor
console.log(undefined < 0); // false (NaN < 0 is false)
console.log(undefined >= 0); // false (NaN >= 0 is false)
:::
null: The null type represents the intentional absence of a value. null converts to 0 in numeric contexts, which may result in unexpected behavior in numeric comparisons::::interactive_editor
console.log(null < 0); // false (0 < 0 is false)
console.log(null >= 0); // true (0 >= 0 is true)
:::
==), null and undefined only equal each other and themselves::::interactive_editor
console.log(null == undefined); // true
console.log(null == 0); // false
console.log(undefined == NaN); // false
:::
===), which checks both value and type without performing type coercion, null and undefined are not equal::::interactive_editor
console.log(null === undefined); // false
:::
switch Statementsswitch 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.:::interactive_editor
const dayOfWeek = 3;
switch (dayOfWeek) {
case 1:
console.log("It's Monday! Time to start the week strong.");
break;
case 2:
console.log("It's Tuesday! Keep the momentum going.");
break;
case 3:
console.log("It's Wednesday! We're halfway there.");
break;
case 4:
console.log("It's Thursday! Almost the weekend.");
break;
case 5:
console.log("It's Friday! The weekend is near.");
break;
case 6:
console.log("It's Saturday! Enjoy your weekend.");
break;
case 7:
console.log("It's Sunday! Rest and recharge.");
break;
default:
console.log("Invalid day! Please enter a number between 1 and 7.");
}
:::
function keyword followed by a name, a list of parameters, and a block of code that performs the task.undefined.return keyword is used to specify the value to be returned from the function and ends the function execution.=> syntax between the parameters and the function body.function keyword.return keyword.{} such as in if statements, or loops.let and const provides even finer control over variable accessibility, helping to prevent errors and make your code more predictable.const developers = ["Jessica", "Naomi", "Tom"];
undefined.:::interactive_editor
const developers = ["Jessica", "Naomi", "Tom"];
console.log(developers[0]) // "Jessica"
console.log(developers[1]) // "Naomi"
console.log(developers[10]) // undefined
:::
length Property: This property is used to return the number of items in an array.:::interactive_editor
const developers = ["Jessica", "Naomi", "Tom"];
console.log(developers.length) // 3
:::
=) to assign a new value to the element at a specific index.:::interactive_editor
const fruits = ['apple', 'banana', 'cherry'];
fruits[1] = 'blueberry';
console.log(fruits); // ['apple', 'blueberry', 'cherry']
:::
:::interactive_editor
const chessboard = [
['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R'],
['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'],
['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r']
];
console.log(chessboard[0][3]); // "Q"
:::
:::interactive_editor
const fruits = ["apple", "banana", "orange"];
const [first, second, third] = fruits;
console.log(first); // "apple"
console.log(second); // "banana"
console.log(third); // "orange"
:::
:::interactive_editor
const fruits = ["apple", "banana", "orange", "mango", "kiwi"];
const [first, second, ...rest] = fruits;
console.log(first); // "apple"
console.log(second); // "banana"
console.log(rest); // ["orange", "mango", "kiwi"]
:::
push() Method: This method is used to add elements to the end of the array and will return the new length.:::interactive_editor
const desserts = ["cake", "cookies", "pie"];
desserts.push("ice cream");
console.log(desserts); // ["cake", "cookies", "pie", "ice cream"];
:::
pop() Method: This method is used to remove the last element from an array and will return that removed element. If the array is empty, then the return value will be undefined.:::interactive_editor
const desserts = ["cake", "cookies", "pie"];
desserts.pop();
console.log(desserts); // ["cake", "cookies"];
:::
shift() Method: This method is used to remove the first element from an array and return that removed element. If the array is empty, then the return value will be undefined.:::interactive_editor
const desserts = ["cake", "cookies", "pie"];
desserts.shift();
console.log(desserts); // ["cookies", "pie"];
:::
unshift() Method: This method is used to add elements to the beginning of the array and will return the new length.:::interactive_editor
const desserts = ["cake", "cookies", "pie"];
desserts.unshift("ice cream");
console.log(desserts); // ["ice cream", "cake", "cookies", "pie"];
:::
indexOf() Method: This method is useful for finding the first index of a specific element within an array. If the element cannot be found, then it will return -1.:::interactive_editor
const fruits = ["apple", "banana", "orange", "banana"];
const index = fruits.indexOf("banana");
console.log(index); // 1
console.log(fruits.indexOf("not found")); // -1
:::
splice() Method: This method is used to add or remove elements from any position in an array. The return value for the splice() method will be an array of the items removed from the array. If nothing is removed, then an empty array will be returned. This method will mutate the original array, modifying it in place rather than creating a new array. The first argument specifies the index at which to begin modifying the array. The second argument is the number of elements you wish to remove. The following arguments are the elements you wish to add.:::interactive_editor
const colors = ["red", "green", "blue"];
colors.splice(1, 0, "yellow", "purple");
console.log(colors); // ["red", "yellow", "purple", "green", "blue"]
:::
includes() Method: This method is used to check if an array contains a specific value. This method returns true if the array contains the specified element, and false otherwise.:::interactive_editor
const programmingLanguages = ["JavaScript", "Python", "C++"];
console.log(programmingLanguages.includes("Python")); // true
console.log(programmingLanguages.includes("Perl")); // false
:::
concat() Method: This method creates a new array by merging two or more arrays.:::interactive_editor
const programmingLanguages = ["JavaScript", "Python", "C++"];
const newList = programmingLanguages.concat("Perl");
console.log(newList); // ["JavaScript", "Python", "C++", "Perl"]
:::
slice() Method: This method returns a shallow copy of a portion of the array, starting from a specified index or the entire array. A shallow copy will copy the reference to the array instead of duplicating it.:::interactive_editor
const programmingLanguages = ["JavaScript", "Python", "C++"];
const newList = programmingLanguages.slice(1);
console.log(newList); // ["Python", "C++"]
:::
:::interactive_editor
const originalArray = [1, 2, 3];
const shallowCopiedArray = [...originalArray];
shallowCopiedArray.push(4);
console.log(originalArray); // [1, 2, 3]
console.log(shallowCopiedArray); // [1, 2, 3, 4]
:::
split() Method: This method divides a string into an array of substrings and specifies where each split should happen based on a given separator. If no separator is provided, the method returns an array containing the original string as a single element.:::interactive_editor
const str = "hello";
const charArray = str.split("");
console.log(charArray); // ["h", "e", "l", "l", "o"]
:::
reverse() Method: This method reverses an array in place.:::interactive_editor
const desserts = ["cake", "cookies", "pie"];
console.log(desserts.reverse()); // ["pie", "cookies", "cake"]
:::
join() Method: This method concatenates all the elements of an array into a single string, with each element separated by a specified separator. If no separator is provided, or an empty string ("") is used, the elements will be joined without any separator.:::interactive_editor
const reversedArray = ["o", "l", "l", "e", "h"];
const reversedString = reversedArray.join("");
console.log(reversedString); // "olleh"
:::
:::interactive_editor
const person = {
name: "Alice",
age: 30,
city: "New York"
};
console.log(person.name); // Alice
console.log(person["name"]); // Alice
:::
To set a property of an existing object you can use either dot notation or bracket notation together with the assignment operator.
:::interactive_editor
const person = {
name: "Alice",
age: 30
};
person.job = "Engineer"
person["hobby"] = "Knitting"
console.log(person); // {name: 'Alice', age: 30, job: 'Engineer', hobby: 'Knitting'}
:::
delete Operator: This operator is used to remove a property from an object.:::interactive_editor
const person = {
name: "Alice",
age: 30,
job: "Engineer"
};
delete person.job;
console.log(person.job); // undefined
:::
hasOwnProperty() Method: This method returns a boolean indicating whether the object has the specified property as its own property.:::interactive_editor
const person = {
name: "Alice",
age: 30
};
console.log(person.hasOwnProperty("name")); // true
console.log(person.hasOwnProperty("job")); // false
:::
Object.hasOwn() Method: This is the modern, recommended way to check if an object has a property as its own (not inherited). The syntax is Object.hasOwn(object, propertyName). It returns true if the property exists on the object and false if it does not — regardless of what value the property holds. This makes it safer than checking if (obj.prop) when values can be 0, false, null, or undefined.:::interactive_editor
const person = {
name: "Alice",
age: 30
};
console.log(Object.hasOwn(person, "name")); // true
console.log(Object.hasOwn(person, "job")); // false
:::
Using Object.hasOwn() inside an if statement before accessing a value prevents bugs:
:::interactive_editor
const cart = {
item: "Headphones",
quantity: 1,
discount: 0
};
// Safe: Object.hasOwn() checks existence, not value
if (Object.hasOwn(cart, "discount")) {
console.log("Discount value:", cart.discount); // Discount value: 0
}
// Unsafe: if() misses the property because 0 is falsy
if (cart.discount) {
console.log("This will NOT print even though discount exists");
}
:::
in Operator: This operator will return true if the property exists in the object.:::interactive_editor
const person = {
name: "Bob",
age: 25
};
console.log("name" in person); // true
:::
:::interactive_editor
const person = {
name: "Alice",
age: 30,
contact: {
email: "[email protected]",
phone: {
home: "123-456-7890",
work: "098-765-4321"
}
}
};
console.log(person.contact.phone.work); // "098-765-4321"
:::
null, undefined, and symbols. These types are called "primitive" because they represent single values and are not objects. Primitive values are immutable, which means once they are created, their value cannot be changed.this keyword inside the method refers to the object itself, enabling access to its properties.:::interactive_editor
const person = {
name: "Bob",
age: 30,
sayHello: function() {
return "Hello, my name is " + this.name;
}
};
console.log(person.sayHello()); // "Hello, my name is Bob"
:::
new keyword and can initialize properties and methods on the newly created object. The Object() constructor creates a new empty object.new Object()
?.):::interactive_editor
const user = {
name: "John",
profile: {
email: "[email protected]",
address: {
street: "123 Main St",
city: "Somewhere"
}
}
};
console.log(user.profile?.address?.street); // "123 Main St"
console.log(user.profile?.phone?.number); // undefined
:::
:::interactive_editor
const person = { name: "Alice", age: 30, city: "New York" };
const { name, age } = person;
console.log(name); // Alice
console.log(age); // 30
:::
{
"name": "Alice",
"age": 30,
"isStudent": false,
"list of courses": ["Mathematics", "Physics", "Computer Science"]
}
JSON.stringify(): This method is used to convert a JavaScript object into a JSON string. This is useful when you want to store or transmit data in a format that can be easily shared or transferred between systems.:::interactive_editor
const user = {
name: "John",
age: 30,
isAdmin: true
};
const jsonString = JSON.stringify(user);
console.log(jsonString); // '{"name":"John","age":30,"isAdmin":true}'
:::
JSON.parse(): This method converts a JSON string back into a JavaScript object. This is useful when you retrieve JSON data from a web server or localStorage and you need to manipulate the data in your application.:::interactive_editor
const jsonString = '{"name":"John","age":30,"isAdmin":true}';
const userObject = JSON.parse(jsonString);
// result: { name: 'John', age: 30, isAdmin: true }
console.log(userObject);
:::
for Loop: This type of loop is used to repeat a block of code a certain number of times. This loop is broken up into three parts: the initialization statement, the condition, and the increment/decrement statement. The initialization statement is executed before the loop starts. It is typically used to initialize a counter variable. The condition is evaluated before each iteration of the loop. An iteration is a single pass through the loop. If the condition is true, the code block inside the loop is executed. If the condition is false, the loop stops and you move on to the next block of code. The increment/decrement statement is executed after each iteration of the loop. It is typically used to increment or decrement the counter variable.:::interactive_editor
for (let i = 0; i < 5; i++) {
console.log(i);
}
:::
for...of Loop: This type of loop is used when you need to loop over values from an iterable. Examples of iterables are arrays and strings.:::interactive_editor
const numbers = [1, 2, 3, 4, 5];
for (const num of numbers) {
console.log(num);
}
:::
for...in Loop: This type of loop is best used when you need to loop over the properties of an object. This loop will iterate over all enumerable properties of an object, including inherited properties and non-numeric properties.:::interactive_editor
const fruit = {
name: 'apple',
color: 'red',
price: 0.99
};
for (const prop in fruit) {
console.log(fruit[prop]);
}
:::
while Loop: This type of loop will run a block of code as long as the condition is true.:::interactive_editor
let i = 5;
while (i > 0) {
console.log(i);
i--;
}
:::
do...while Loop: This type of loop will execute the block of code at least once before checking the condition.let userInput;
do {
userInput = prompt("Please enter a number between 1 and 10");
} while (Number(userInput) < 1 || Number(userInput) > 10);
alert("You entered a valid number!");
break and continue Statementsbreak statement is used to exit a loop early, while a continue statement is used to skip the current iteration of a loop and move to the next one.:::interactive_editor
// Example of break statement
for (let i = 0; i < 10; i++) {
if (i === 5) {
break;
}
console.log(i);
}
// Output: 0, 1, 2, 3, and 4
// Example of continue statement
for (let i = 0; i < 10; i++) {
if (i === 5) {
continue;
}
console.log(i);
}
// Output: 0, 1, 2, 3, 4, 6, 7, 8, and 9
:::
toString() MethodString constructor function, which wraps the primitive value in an object.:::interactive_editor
const greetingObject = new String("Hello, world!");
console.log(typeof greetingObject); // "object"
:::
toString() Method: This method converts a value to its string representation. It is a method you can use for numbers, booleans, arrays, and objects.:::interactive_editor
const num = 10;
console.log(num.toString()); // "10"
const arr = [1, 2, 3];
console.log(arr.toString()); // "1,2,3"
:::
This method accepts an optional radix which is a number from 2 to 36. This radix represents the base, such as base 2 for binary or base 8 for octal. If the radix is not specified, it defaults to base 10, which is decimal.
:::interactive_editor
const num = 10;
console.log(num.toString(2)); // "1010"(binary)
:::
Number constructor is used to create a number object. The number object contains a few helpful properties and methods like the isNaN and toFixed method. Most of the time, you will be using the Number constructor to convert other data types to the number data type.:::interactive_editor
const myNum = new Number("34");
console.log(typeof myNum); // "object"
const num = Number('100');
console.log(num); // 100
console.log(typeof num); // number
:::
camelCasing: By convention, JavaScript developers will use camel casing for naming variables and functions. Camel casing is where the first word is all lowercase and the following words start with a capital letter. Ex. isLoading.
Naming Booleans: For boolean variables, it's a common practice to use prefixes such as "is", "has", or "can".
let isLoading = true;
let hasPermission = false;
let canEdit = true;
function getUserData() { /* ... */ }
function isValidEmail(email) { /* ... */ }
function getProductDetails(productId) { /* ... */ }
function setUserPreferences(preferences) { /* ... */ }
function handleClick() { /* ... */ }
i, j, or k.for (let i = 0; i < array.length; i++) { /* ... */ }
undefined. These types of arrays are known as sparse arrays.:::interactive_editor
const sparseArray = [1, , , 4];
console.log(sparseArray.length); // 4
:::
:::interactive_editor
function outerFunction(x) {
let y = 10;
function innerFunction() {
console.log(x + y);
}
return innerFunction;
}
let closure = outerFunction(5);
closure(); // 15
:::
var Keyword and Hoistingvar was the original way to declare variables before 2015. But there were some issues that came with var in terms of scope, redeclaration and more. So that is why modern JavaScript programming uses let and const instead.var: If you try to redeclare a variable using let, then you would get a SyntaxError. But with var, you are allowed to redeclare a variable.// Uncaught SyntaxError: Identifier 'num' has already been declared
let num = 19;
let num = 18;
var myNum = 5;
var myNum = 10; // This is allowed and doesn't throw an error
console.log(myNum) // 10
var and Scope: Variables declared with var inside a block (like an if statement or a for loop) are still accessible outside that block.:::interactive_editor
if (true) {
var num = 5;
}
console.log(num); // 5
:::
var keyword, JavaScript hoists the declaration to the top of its scope.:::interactive_editor
console.log(num); // undefined
var num = 5;
console.log(num); // 5
:::
When you declare a function using the function declaration syntax, both the function name and the function body are hoisted. This means you can call a function before you've declared it in your code.
:::interactive_editor
sayHello(); // "Hello, World!"
function sayHello() {
console.log("Hello, World!");
}
:::
Variable declarations made with let or const are hoisted, but they are not initialized, and you can't access them before the actual declaration in your code. This behavior is often referred to as the "temporal dead zone".
:::interactive_editor
console.log(num); // Throws a ReferenceError
let num = 10;
:::
export keyword. There are two types of export: named export and default export.import keyword. The types can be named import, default import, and namespace import.// Within a file called math.js, we export the following functions:
// Named export
export function add(num1, num2) {
return num1 + num2;
}
// Default export
export default function subtract(num1, num2) {
return num1 - num2;
}
// Within another file, we can import the functions from math.js.
// Named import - This line imports the add function.
// The name of the function must exactly match the one exported from math.js.
import { add } from './math.js';
// Default import - This line imports the subtract function.
// The name of the function can be anything.
import subtractFunc from './math.js';
// Namespace import - This line imports everything from the file.
import * as Math from './math.js';
console.log(add(5, 3)); // 8
console.log(subtractFunc(5, 3)); // 2
console.log(Math.add(5, 3)); // 8
console.log(Math.subtract(5, 3)); // 2
forEach MethodforEach() Method: This method is used to iterate over each element in an array and perform an operation on each element. The callback function in forEach can take up to three arguments: the current element, the index of the current element, and the array that forEach was called upon.:::interactive_editor
const numbers = [1, 2, 3, 4, 5];
// Result: 2 4 6 8 10
numbers.forEach((number) => {
console.log(number * 2);
});
:::
:::interactive_editor
function operateOnArray(arr, operation) {
const result = [];
for (let i = 0; i < arr.length; i++) {
result.push(operation(arr[i]));
}
return result;
}
function double(x) {
return x * 2;
}
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = operateOnArray(numbers, double);
console.log(doubledNumbers); // [2, 4, 6, 8, 10]
:::
map() Method: This method is used to create a new array by applying a given function to each element of the original array. The callback function can accept up to three arguments: the current element, the index of the current element, and the array that map was called upon.:::interactive_editor
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map((num) => num * 2);
console.log(numbers); // [1, 2, 3, 4, 5]
console.log(doubled); // [2, 4, 6, 8, 10]
:::
filter() Method: This method is used to create a new array with elements that pass a specified test, making it useful for selectively extracting items based on criteria. Just like the map method, the callback function for the filter method accepts the same three arguments: the current element being processed, the index, and the array.:::interactive_editor
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenNumbers = numbers.filter((num) => num % 2 === 0);
console.log(evenNumbers); // [2, 4, 6, 8, 10]
:::
reduce() Method: This method is used to process an array and condense it into a single value. This single value can be a number, a string, an object, or even another array. The reduce() method works by applying a function to each element in the array, in order, passing the result of each calculation on to the next. This function is often called the reducer function. The reducer function takes two main parameters: an accumulator and the current value. The accumulator is where you store the running result of your operations, and the current value is the array element being processed.:::interactive_editor
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce(
(accumulator, currentValue) => accumulator + currentValue,
0
);
console.log(sum); // 15
:::
:::interactive_editor
const result = " Hello, World! "
.trim()
.toLowerCase()
.replace("world", "JavaScript");
console.log(result); // "hello, JavaScript!"
:::
sort Methodsort method is used to sort the elements of an array and return a reference to the sorted array. No copy is made in this case because the elements are sorted in place.:::interactive_editor
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
console.log(fruits); // ["Apple", "Banana", "Mango", "Orange"]
:::
If you need to sort numbers, then you will need to pass in a compare function. The sort method converts the elements to strings and then compares their sequences of UTF-16 code units values. UTF-16 code units are the numeric values that represent the characters in the string. Examples of UTF-16 code units are the numbers 65, 66, and 67 which represent the characters "A", "B", and "C" respectively. So the number 200 appears before the number 3 in an array, because the string "200" comes before the string "3" when comparing their UTF-16 code units.
:::interactive_editor
const numbers = [414, 200, 5, 10, 3];
numbers.sort((a, b) => a - b);
console.log(numbers); // [3, 5, 10, 200, 414]
:::
The parameters a and b are the two elements being compared. The compare function should return a negative value if a should come before b, a positive value if a should come after b, and zero if a and b are equal.
every and some Methodsevery() Method: This method tests whether all elements in an array pass a test implemented by a provided function. The every() method returns true if the provided function returns true for all elements in the array. If any element fails the test, the method immediately returns false and stops checking the remaining elements.:::interactive_editor
const numbers = [2, 4, 6, 8, 10];
const hasAllEvenNumbers = numbers.every((num) => num % 2 === 0);
console.log(hasAllEvenNumbers); // true
:::
some() Method: This method checks if at least one element passes the test. The some() method returns true as soon as it finds an element that passes the test. If no elements pass the test, it returns false.:::interactive_editor
const numbers = [1, 3, 5, 7, 8, 9];
const hasSomeEvenNumbers = numbers.some((num) => num % 2 === 0);
console.log(hasSomeEvenNumbers); // true
:::
html element. It's the top-level container for all the content of an HTML document. All other nodes are descendants of this root node. Then, below the root node, we find other nodes in the hierarchy. A parent node is an element that contains other elements. A child node is an element that is contained within another element.navigator Interface: This provides information about the browser environment, such as the user agent string, the platform, and the version of the browser. A user agent string is a text string that identifies the browser and operating system being used.window Interface: This represents the browser window that contains the DOM document. It provides methods and properties for interacting with the browser window, such as resizing the window, opening new windows, and navigating to different URLs.querySelector(), querySelectorAll() and getElementById() MethodsgetElementById() Method: This method is used to get an object that represents the HTML element with the specified id. Remember that ids must be unique in every HTML document, so this method will only return one Element object.:::interactive_editor
<div id="container"></div>
<script src="./index.js"></script>
const container = document.getElementById("container");
console.log(container)
:::
querySelector() Method: This method is used to get the first element in the HTML document that matches the CSS selector passed as an argument.:::interactive_editor
<section class="section"></section>
<script src="./index.js"></script>
const section = document.querySelector(".section");
console.log(section)
:::
querySelectorAll() Method: You can use this method to get a list of all the DOM elements that match a specific CSS selector.:::interactive_editor
<ul class="ingredients">
<li>Sugar</li>
<li>Milk</li>
<li>Eggs</li>
</ul>
<script src="./index.js"></script>
const ingredients = document.querySelectorAll('ul.ingredients li');
console.log(ingredients)
:::
innerText(), innerHTML(), createElement() and textContent() MethodsinnerHTML Property: This is a property of the Element that is used to set or update parts of the HTML markup.:::interactive_editor
<div id="container">
<!-- Add new elements here -->
</div>
<script src="./index.js"></script>
const container = document.getElementById("container");
container.innerHTML = '<ul><li>Cheese</li><li>Tomato</li></ul>';
:::
createElement Method: This is used to create an HTML element.const img = document.createElement("img");
innerText: This represents the visible text content of the HTML element and its descendants.:::interactive_editor
<div id="container">
<p>Hello, World!</p>
<p>I'm learning JavaScript</p>
</div>
<script src="./index.js"></script>
const container = document.getElementById("container");
console.log(container.innerText);
:::
textContent: This returns the plain text content of an element, including all the text within its descendants.:::interactive_editor
<div id="container">
<p>Hello, World!</p>
<p>I'm learning JavaScript</p>
</div>
<script src="./index.js"></script>
const container = document.getElementById("container");
console.log(container.textContent);
:::
appendChild() and removeChild() MethodsappendChild() Method: This method is used to add a node to the end of the list of children of a specified parent node.:::interactive_editor
<ul id="desserts">
<li>Cake</li>
<li>Pie</li>
</ul>
<script src="./index.js"></script>
const dessertsList = document.getElementById("desserts");
const listItem = document.createElement("li");
listItem.textContent = "Cookies";
dessertsList.appendChild(listItem);
:::
removeChild() Method: This method is used to remove a node from the DOM.:::interactive_editor
<section id="example-section">
<h2>Example sub heading</h2>
<p>first paragraph</p>
<p>second paragraph</p>
</section>
<script src="./index.js"></script>
const sectionEl = document.getElementById("example-section");
const lastParagraph = document.querySelector("#example-section p:last-of-type");
sectionEl.removeChild(lastParagraph);
:::
setAttribute() Method:::interactive_editor
<p id="para">I am a paragraph</p>
<script src="./index.js"></script>
const para = document.getElementById("para");
para.setAttribute("class", "my-class");
:::
Event object is a payload that triggers when a user interacts with your web page in some way. These interactions can be anything from clicking on a button or focusing an input to shaking their mobile device. All Event objects will have the type property. This property reveals the type of event that triggered the payload, such as keydown or click. These values will correspond to the same values you might pass to addEventListener(), where you can capture and utilize the Event object.addEventListener() and removeEventListener() MethodsaddEventListener Method: This method is used to listen for events. It takes two arguments: the event you want to listen for and a function that will be called when the event occurs. Some common examples of events would be click events, input events, and change events.:::interactive_editor
<button id="btn">Click Me</button>
<script src="./index.js"></script>
const btn = document.getElementById("btn");
btn.addEventListener("click", () => alert("You clicked the button"));
:::
removeEventListener() Method: This method is used to remove an event listener that was previously added to an element using the addEventListener() method. This is useful when you want to stop listening for a particular event on an element.:::interactive_editor
<body>
<p id="para">Hover over me to disable the button's click event</p>
<button id="btn">Toggle Background Color</button>
</body>
<script src="./index.js"></script>
const bodyEl = document.querySelector("body");
const para = document.getElementById("para");
const btn = document.getElementById("btn");
let isBgColorGrey = true;
function toggleBgColor() {
bodyEl.style.backgroundColor = isBgColorGrey ? "blue" : "grey";
isBgColorGrey = !isBgColorGrey;
}
btn.addEventListener("click", toggleBgColor);
para.addEventListener("mouseover", () => {
btn.removeEventListener("click", toggleBgColor);
});
:::
addEventListener method instead.:::interactive_editor
<button onclick="alert('Hello World!')">Show alert</button>
:::
DOMContentLoaded event is fired when everything in the HTML document has been loaded and parsed. If you have external stylesheets, or images, the DOMContentLoaded event will not wait for those to be loaded. It will only wait for the HTML to be loaded.style and classListElement.style Property: This property is a read-only property that represents the inline style of an element. You can use this property to get or set the style of an element.:::interactive_editor
<p id="para">This paragraph will turn red.</p>
<script src="./index.js"></script>
const paraEl = document.getElementById("para");
paraEl.style.color = "red";
:::
Element.classList Property: This property is a read-only property that can be used to add, remove, or toggle classes on an element.:::interactive_editor
<link rel="stylesheet" href="./styles.css"/>
<p id="para" class="blue-background">This paragraph will have classes added and removed.</p>
<div id="menu" class="menu">Menu Content</div>
<button id="toggle-btn">Toggle Menu</button>
<script src="./index.js"></script>
.highlight {
background-color: yellow;
}
.blue-background {
background-color: lightblue;
}
.menu {
display: none;
padding: 10px;
background-color: #f0f0f0;
}
.menu.show {
display: block;
}
// Example adding a class
const paraEl = document.getElementById("para");
paraEl.classList.add("highlight");
// Example removing a class
paraEl.classList.remove("blue-background");
// Example toggling a class
const menu = document.getElementById("menu");
const toggleBtn = document.getElementById("toggle-btn");
toggleBtn.addEventListener("click", () => menu.classList.toggle("show"));
:::
setTimeout() and setInterval() MethodssetTimeout() Method: This method lets you delay an action for a specified time.:::interactive_editor
setTimeout(() => {
console.log('This runs after 3 seconds');
}, 3000);
:::
setInterval() Method: This method keeps running a piece of code repeatedly at a set interval. Since setInterval() keeps executing the provided function at the specified interval, you might want to stop it. For this, you have to use the clearInterval() method.:::interactive_editor
setInterval(() => {
console.log('This runs every 2 seconds');
}, 2000);
// Example using clearInterval
const intervalID = setInterval(() => {
console.log('This will stop after 5 seconds');
}, 1000);
setTimeout(() => {
clearInterval(intervalID);
}, 5000);
:::
requestAnimationFrame() Methodfunction animate() {
// Update the animation...
// for example, move an element, change a style, and more.
update();
// Request the next frame
requestAnimationFrame(animate);
}
:::interactive_editor
<link rel="stylesheet" href="./styles.css"/>
<div id="square"></div>
<script src="./index.js"></script>
#square {
width: 100px;
height: 100px;
background: red;
}
const square = document.querySelector('#square');
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
}
);
:::
canvas element in HTML. This element acts as a drawing surface you can manipulate with the instance methods and properties of the interfaces in the Canvas API. This API has interfaces like HTMLCanvasElement, CanvasRenderingContext2D, CanvasGradient, CanvasPattern, and TextMetrics which contain methods and properties you can use to create graphics in your JavaScript file.:::interactive_editor
<canvas id="my-canvas" width="400" height="400"></canvas>
<script src="./index.js"></script>
const canvas = document.getElementById('my-canvas');
// Access the drawing context of the canvas.
// "2d" allows you to draw in two dimensions
const ctx = canvas.getContext('2d');
// Set the background color
ctx.fillStyle = 'crimson';
// Draw a rectangle
ctx.fillRect(1, 1, 150, 100);
:::
showModal() Method: This method is used to open a modal.:::interactive_editor
<dialog id="my-modal">
<p>This is a modal dialog.</p>
</dialog>
<button id="open-modal">Open Modal Dialog</button>
<script src="./index.js"></script>
const dialog = document.getElementById('my-modal');
const openButton = document.getElementById('open-modal');
openButton.addEventListener('click', () => {
dialog.showModal();
});
:::
close() Method: This method is used to close the modal.:::interactive_editor
<dialog id="my-modal">
<p>This is a modal dialog.</p>
<button id="close-modal">Close Modal</button>
</dialog>
<button id="open-modal">Open Modal Dialog</button>
<script src="./index.js"></script>
const dialog = document.getElementById('my-modal');
const openButton = document.getElementById('open-modal');
const closeButton = document.getElementById('close-modal');
openButton.addEventListener('click', () => {
dialog.show();
});
closeButton.addEventListener('click', () => {
dialog.close();
});
:::
:::interactive_editor
<label>
Choose a programming language:
<select class="language" name="language">
<option value="">---Select One---</option>
<option value="JavaScript">JavaScript</option>
<option value="Python">Python</option>
<option value="C++">C++</option>
</select>
</label>
<p class="result"></p>
<script src="./index.js"></script>
const selectEl = document.querySelector(".language");
const result = document.querySelector(".result");
selectEl.addEventListener("change", (e) => {
result.textContent = `You enjoy programming in ${e.target.value}.`;
});
:::
aria-expanded attribute: Used to convey the state of a toggle (or disclosure) feature to screen reader users.aria-haspopup attribute: This state is used to indicate that an interactive element will trigger a pop-up element when activated. You can only use the aria-haspopup attribute when the pop-up has one of the following roles: menu, listbox, tree, grid, or dialog. The value of aria-haspopup must be either one of these roles or true, which is the same as menu.aria-checked attribute: This attribute is used to indicate whether an element is in the checked state. It is most commonly used when creating custom checkboxes, radio buttons, switches, and listboxes.aria-disabled attribute: This state is used to indicate that an element is disabled only to people using assistive technologies, such as screen readers.aria-selected attribute: This state is used to indicate that an element is selected. You can use this state on custom controls like a tabbed interface, a listbox, or a grid.aria-controls attribute: Used to associate an element with another element that it controls. This helps people using assistive technologies understand the relationship between the elements.hidden attribute: Hides inactive panels from both visual and assistive technology users.aria-live attribute: Makes part of a webpage a live region, meaning any updates inside that area will be announced by a screen reader so users don't miss important changes.polite value: Most live regions use this value. This value means that the update is not urgent, so the screen reader can wait until it finishes any current announcement or the user completes their current action before announcing the update.Here is an example of a live region that is dynamically updated by JavaScript:
:::interactive_editor
<div aria-live="polite" id="status"></div>
<button id="updateStatus">Update Status</button>
<script>
const statusEl = document.getElementById("status");
const btn = document.getElementById("updateStatus");
btn.addEventListener("click", () => {
statusEl.textContent = "Your file has been successfully uploaded.";
});
</script>
:::
contenteditable attribute: Turns the element into a live editor, allowing users to update its content as if it were a text field. When there is no visible label or heading for a contenteditable region, add an accessible name using the aria-label attribute to help screen reader users understand the purpose of the editable area.:::interactive_editor
<div
contenteditable="true"
aria-label="Note editor"
id="editor"
style="border: 1px solid #ccc; padding: 8px;"
>
Editable content goes here
</div>
<p id="status" aria-live="polite"></p>
<script>
const editor = document.getElementById("editor");
const status = document.getElementById("status");
editor.addEventListener("input", () => {
status.textContent = "Content updated";
});
</script>
:::
focus and blur Eventsblur event: Fires when an element loses focus.:::interactive_editor
<input
id="nameInput"
type="text"
placeholder="Type here and click outside"
aria-label="Name input"
/>
<p id="status" aria-live="polite"></p>
<script>
const input = document.getElementById("nameInput");
const status = document.getElementById("status");
input.addEventListener("blur", () => {
status.textContent = "Input lost focus";
});
</script>
:::
focus event: Fires when an element receives focus.:::interactive_editor
<input
id="emailInput"
type="email"
placeholder="Click or tab into this field"
aria-label="Email input"
/>
<p id="status" aria-live="polite"></p>
<script>
const input = document.getElementById("emailInput");
const status = document.getElementById("status");
input.addEventListener("focus", () => {
status.textContent = "Input received focus";
});
</script>
:::
const arr = ["Beau", "Quincy" "Tom"]
let or const, before it has been defined.:::interactive_editor
console.log(num);
const num = 50;
:::
const developerObj = {
name: "Jessica",
country: "USA",
isEmployed: true
};
developerObj.map()
const arr = [];
arr.length = -1;
throw Statementthrow statement in JavaScript is used to throw a user-defined exception. An exception in programming, is when an unexpected event happens and disrupts the normal flow of the program.:::interactive_editor
function validateNumber(input) {
if (typeof input !== "number") {
throw new TypeError("Expected a number, but received " + typeof input);
}
return input * 2;
}
:::
try...catch...finallytry block is used to wrap code that might throw an error. It acts as a safe space to try something that could fail. The catch block captures and handles errors that occur in the try block. You can use the error object inside catch to inspect what went wrong. The finally block runs after the try and catch blocks, regardless of whether an error occurred. It's commonly used for cleanup tasks, such as closing files or releasing resources.:::interactive_editor
function processInput(input) {
if (typeof input !== "string") {
throw new TypeError("Input must be a string.");
}
return input.toUpperCase();
}
try {
console.log("Starting to process input...");
const result1 = processInput("hello");
console.log("Processed result:", result1); // HELLO
const result2 = processInput(9); // throws TypeError
console.log("Processed result:", result2); // not executed
} catch (error) {
console.error("Error occurred:", error.message);
}
:::
debugger Statement: This statement lets you pause your code at a specific line to investigate what's going on in the program.:::interactive_editor
let firstNumber = 5;
let secondNumber = 10;
debugger; // Code execution pauses here
let sum = firstNumber + secondNumber;
console.log(sum);
:::
console.dir(): This method is used to display an interactive list of the properties of a specified JavaScript object. It outputs a hierarchical listing that can be expanded to see all nested properties.console.dir(document);
console.table(): This method displays tabular data as a table in the console. It takes one mandatory argument, which must be an array or an object, and one optional argument to specify which properties (columns) to display.const regex = /freeCodeCamp/;
test() Method: This method accepts a string, which is the string to test for matches against the regular expression. This method will return a boolean if the string matches the regex.:::interactive_editor
const regex = /freeCodeCamp/;
const test = regex.test("e");
console.log(test); // false
:::
match() Method: This method accepts a regular expression, although you can also pass a string which will be constructed into a regular expression. The match method returns the match array for the string.const regex = /freeCodeCamp/;
const match = "freeCodeCamp".match(regex);
console.log(match); // ['freeCodeCamp', index: 0, input: 'freeCodeCamp', groups: undefined]
replace() Method: This method accepts two arguments: the regular expression to match (or a string), and the string to replace the match with (or a function to run against each match).:::interactive_editor
const regex = /Jessica/;
const str = "Jessica is rly kewl";
const replaced = str.replace(regex, "freeCodeCamp");
console.log(replaced); // "freeCodeCamp is rly kewl"
:::
replaceAll Method: This method is used to replace all occurrences of a specified pattern with a new string. This method will throw an error if you give it a regular expression without the global modifier.:::interactive_editor
const text = "I hate JavaScript! I hate programming!";
const newText = text.replaceAll("hate", "love");
console.log(newText); // "I love JavaScript! I love programming!"
:::
matchAll Method: This method is used to retrieve all matches of a given regular expression in a string, including capturing groups, and returns them as an iterator. An iterator is an object that allows you to go through (or "iterate over") a collection of items.:::interactive_editor
const str = "JavaScript, Python, JavaScript, Swift, JavaScript";
const regex = /JavaScript/g;
const iterator = str.matchAll(regex);
for (let match of iterator) {
console.log(match[0]); // "JavaScript" for each match
}
:::
i Flag: This flag makes a regex ignore case.:::interactive_editor
const regex = /freeCodeCamp/i;
console.log(regex.test("freecodecamp")); // true
console.log(regex.test("FREECODECAMP")); // true
:::
g Flag: This flag, or global modifier, allows your regular expression to match a pattern more than once.:::interactive_editor
const regex = /freeCodeCamp/gi;
console.log(regex.test("freeCodeCamp")); // true
console.log(regex.test("freeCodeCamp is great")); // false
:::
^ anchor, at the beginning of the regular expression, says "match the start of the string". The $ anchor, at the end of the regular expression, says "match the end of the string".:::interactive_editor
const start = /^freeCodeCamp/i;
const end = /freeCodeCamp$/i;
console.log(start.test("freecodecamp")); // true
console.log(end.test("freecodecamp")); // true
:::
m Flag: Anchors look for the beginning and end of the entire string. But you can make a regex handle multiple lines with the m flag, or the multi-line modifier.flag, or the multi-line modifier.:::interactive_editor
const start = /^freecodecamp/im;
const end = /freecodecamp$/im;
const str = `I love
freecodecamp
it's my favorite
`;
console.log(start.test(str)); // true
console.log(end.test(str)); // true
:::
d Flag: This flag expands the information you get in a match object.const regex = /freecodecamp/di;
const string = "we love freecodecamp isn't freecodecamp great?";
console.log(string.match(regex));
And the result is:
// [
// 'freecodecamp',
// index: 8,
// input: "we love freecodecamp isn't freecodecamp great?",
// groups: undefined,
// indices: [
// 0: [8, 20],
// groups: undefined
// ]
// ]
u Flag: This expands the functionality of a regular expression to allow it to match special unicode characters. The u flag gives you access to special classes like the Extended_Pictographic to match most emoji. There is also a v flag, which further expands the functionality of the unicode matching.y Flag: The sticky modifier behaves very similarly to the global modifier, but with a few exceptions. The biggest one is that a global regular expression will start from lastIndex and search the entire remainder of the string for another match, but a sticky regular expression will return null and reset the lastIndex to 0 if there is not immediately a match at the previous lastIndex.s Flag: The single-line modifier allows a wildcard character, represented by a . in regex, to match linebreaks - effectively treating the string as a single line of text..: Character classes are a special syntax you can use to match sets or subsets of characters. The first character class you should learn is the wild card class. The wild card is represented by a period, or dot, and matches ANY single character EXCEPT line breaks. To allow the wildcard class to match line breaks, remember that you would need to use the s flag.const regex = /a./;
\d: This will match all digits (0-9) in a string.const regex = /\d/;
\w: This is used to match any word character (a-z0-9_) in a string. A word character is defined as any letter, from a to z, or a number from 0 to 9, or the underscore character.const regex = /\w/;
\s: The white-space class \s, represented by a backslash followed by an s. This character class will match any white space, including new lines, spaces, tabs, and special unicode space characters.const regex = /\D/;
const regex = /[abcdf]/;
?= to define that pattern as a positive lookahead.const regex = /free(?=code)/i;
const regex = /free(?!code)/i;
const regex = /(?<=free)code/i;
const regex = /(?<!free)code/i;
const regex = /^\d{4}$/;
* : Matches 0 or more occurrences of the preceding element.+: Matches 1 or more occurrences of the preceding element.?: Matches 0 or 1 occurrence of the preceding element.{n}: Matches exactly n occurrences of the preceding element.{n,}: Matches n or more occurrences of the preceding element.{n,m}: Matches between n and m occurrences of the preceding element.const regex = /free(code)camp/i;
$1 refers to the first captured group.:::interactive_editor
const regex = /free(co+de)camp/i;
console.log("freecoooooooodecamp".replace(regex, "paid$1world"));
:::
textarea and input elements, expose a constraint validation API. This API allows you to assert that the user's provided value for that element passes any HTML-level validation you have written, such as minimum length or pattern matching.checkValidity() method: This method returns true if the element matches all HTML validation (based on its attributes), and false if it fails.:::interactive_editor
<form>
<label>
Email:
<input
id="email"
type="email"
required
pattern=".+\.com$"
placeholder="[email protected]"
/>
</label>
</form>
<script>
const input = document.getElementById("email");
input.addEventListener("input", (e) => {
if (!e.target.checkValidity()) {
e.target.setCustomValidity("You must use a .com email.");
} else {
e.target.setCustomValidity("");
}
});
</script>
:::
reportValidity() Method: This method tells the browser that the input is invalid.:::interactive_editor
<form>
<label>
Email:
<input
id="email2"
type="email"
required
pattern=".+\.com$"
placeholder="[email protected]"
/>
</label>
</form>
<script>
const input = document.getElementById("email2");
input.addEventListener("input", (e) => {
if (!e.target.checkValidity()) {
e.target.reportValidity();
}
});
</script>
:::
validity Property: This property is used to get or set the validity state of form controls (like <input>, <select>, etc.) and provides information about whether the user input meets the constraints defined for that element (e.g., required fields, pattern constraints, maximum length, etc.).:::interactive_editor
<input
id="age"
type="number"
min="18"
placeholder="Enter age (18+)"
/>
<script>
const input = document.getElementById("age");
input.addEventListener("input", (e) => {
console.log(e.target.validity);
});
</script>
:::
patternMismatch Property: This will be true if the value doesn't match the specified regular expression pattern.preventDefault() MethodpreventDefault() method on these Event objects stops that behavior from happening.:::interactive_editor
<form id="form">
<input type="text" placeholder="Try to submit" />
<button type="submit">Submit</button>
</form>
<p id="status"></p>
<script>
const form = document.getElementById("form");
const status = document.getElementById("status");
form.addEventListener("submit", (event) => {
event.preventDefault();
status.textContent = "Form submission prevented.";
});
</script>
:::
type attribute set to 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 call to the requestSubmit() or submit() methods of the form element.action Attribute: The action attribute should contain either a URL or a relative path for the current domain. This value determines where the form attempts to send data - if you do not set an action attribute, the form will send data to the current page's URL.<form action="https://freecodecamp.org">
<input
type="number"
id="input"
placeholder="Enter a number"
name="number"
/>
<button type="submit">Submit</button>
</form>
method Attribute: This attribute accepts a standard HTTP method, such as GET or POST, and uses that method when making the request to the action URL. When a method is not set, the form will default to a GET request. The data in the form will be URL encoded as name=value pairs and appended to the action URL as query parameters.<form action="/data" method="POST">
<input
type="number"
id="input"
placeholder="Enter a number"
name="number"
/>
<button type="submit">Submit</button>
</form>
enctype Attribute: The form element accepts an enctype attribute, which represents the encoding type to use for the data. This attribute only accepts three values: application/x-www-form-urlencoded (which is the default, sending the data as a URL-encoded form body), text/plain (which sends the data in plaintext form, in name=value pairs separated by new lines), or multipart/form-data, which is specifically for handling forms with a file upload.date() Object and Common Methodsdate() object is used to create, manipulate, and format dates and times in JavaScript. In the following example, the new keyword is used to create a new instance of the Date object, and the Date object is then assigned to the variable now. If you were to log the value of now to the console, you would see the current date and time based on the system clock of the computer running the code.:::interactive_editor
const now = new Date();
console.log(now); // prints the current date and time
:::
Date.now() Method: This method is used to get the current date and time. Date.now() returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This is known as the Unix epoch time. Unix epoch time is a common way to represent dates and times in computer systems because it is an integer that can be easily stored and manipulated. UTC stands for Universal Time Coordinated, which is the primary time standard by which the world regulates clocks and time.getDate() Method: This method is used to get a day of the month based on the current date. getDate() will return an integer value between 1 and 31, depending on the day of the month. If the date is invalid, it will return NaN (Not a Number).:::interactive_editor
const now = new Date("2014-10-15");
const date = now.getDate();
console.log(date); // 15
:::
getMonth() Method: This method is used to get the month. The month is zero-based, so January is 0, February is 1, and so on. In this example, the output is 2, which corresponds to March. If the month is invalid, it will return NaN.:::interactive_editor
const now = new Date("2014-03-15");
const month = now.getMonth();
console.log(month); // 2
:::
getFullYear() Method: This method is used to get the full year. If the year is invalid, it will return NaN.:::interactive_editor
const now = new Date("2014-10-15");
const year = now.getFullYear();
console.log(year); // 2014
:::
toISOString() Method: This method is used to format the date in an extended ISO (ISO 8601) format. ISO 8601 is an international standard for representing dates and times. The format is YYYY-MM-DDTHH:mm:ss.sssZ.:::interactive_editor
const date = new Date("2014-10-15");
console.log(date.toISOString()); // "2014-10-15T00:00:00.000Z"
:::
toLocaleDateString() Method: This method is used to format the date based on the user's locale.:::interactive_editor
const date = new Date("2014-10-15");
console.log(date.toLocaleDateString("en-US")); // "10/15/2014"
:::
The toLocaleDateString() method accepts two optional parameters: locales and options.
The locales parameter is a string representing the locale to use. For example, you can pass in "en-US" for English (United States) or "fr-FR" for French (France). If you don't pass in a locales parameter, the default locale is used. The second optional parameter is the options parameter. This parameter is an object that allows you to specify the format of the date string.
:::interactive_editor
const date = new Date("2014-10-15");
const options = {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
};
console.log(date.toLocaleDateString("en-GB", options)); // "Wednesday, 15 October 2014"
:::
Audio Constructor and Common MethodsAudio constructor, like other constructors, is a special function called with the new keyword. It returns an HTMLAudioElement, which you can then use to play audio for the user, or append to the DOM for the user to control themselves. When you call the constructor, you can optionally pass a URL as the (only) argument. This URL should point to the source of the audio file you want to play. Or, if you need to change the source dynamically, you can assign the URL to the src property of the returned audio element.play() Method: This method is used with the audio or video elements to begin playback for the media.:::interactive_editor
<audio id="audio" controls>
<source src="https://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
</audio>
<button id="playBtn">Play Audio</button>
<script>
const audio = document.getElementById("audio");
const playBtn = document.getElementById("playBtn");
playBtn.addEventListener("click", () => {
audio.play();
});
</script>
:::
- **`pause()` Method**: This method is used with the `audio` or `video` elements to pause playback for the media.
:::interactive_editor
```html
<audio id="myAudio" controls>
<source src="https://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
</audio>
<button id="pauseBtn">Pause Audio</button>
<script>
document.addEventListener("DOMContentLoaded", () => {
const audio = document.getElementById("myAudio");
const pauseBtn = document.getElementById("pauseBtn");
pauseBtn.addEventListener("click", () => {
audio.pause();
});
});
</script>
:::
addTextTrack() Method: This method allows you to specify a text track to associate with the media element - which is especially helpful for adding subtitles to a video.fastSeek() Method: This method allows you to move the playback position to a specific time within the media.source Element: This is used to specify a file type and source - and can include multiple different types by using multiple source elements. When you do this, the browser will determine the best format to use for the user's current environment.audio/mpeg.audio/mp4 OR video/mp4, depending on whether it's a video file or audio-only.codecs= and the codec.HTMLMediaElement API is used to control the behavior of audio and video elements on your page. It extends the base HTMLElement interface, so you have access to the base properties as well as these helpful methods. Examples of these methods include play(), fastSeek(), and pause().MediaStream object. You could do this with the constructor, but it would not be tied to the user's hardware. Instead, the mediaDevices property of the global navigator object has a getUserMedia() method for you to use.window.navigator.mediaDevices.getUserMedia({
audio: true,
video: {
width: {
min: 1280,
ideal: 1920,
max: 3840
},
height: {
min: 720,
ideal: 1080,
max: 2160
}
}
});
getDisplayMedia() method of the mediaDevices object and consuming the returned media stream.HTMLMediaElement directly).srcObject property.AudioBuffer (representing a Buffer specifically containing audio data) or the AudioContext.Set is a built-in option for managing data collection.Set using the Set() constructor::::interactive_editor
const set = new Set([1, 2, 3, 4, 5]);
console.log(set); // Set { 1, 2, 3, 4, 5 }
:::
Sets can be manipulated using these methods:
add(): Adds a new element to the Set.delete(): Removes an element from the Set.has(): Checks if an element exists in the Set.clear(): Removes all elements from the Set.WeakSet is a collection of objects that allows you to store weakly held objects.WeakSet does not support primitives like numbers or strings.WeakSet only stores objects, and the references to those objects are "weak," meaning that if the object is not being used anywhere else in your code, it is removed automatically to free up memory.Map is a built-in object that holds key-value pairs just like an object.Map provides better performance over the standard object when it comes to frequent addition and removals of key-value pairs.Map using the Map() constructor::::interactive_editor
const map = new Map([
['flower', 'rose'],
['fruit', 'apple'],
['vegetable', 'carrot']
]);
console.log(map); // Map(3) { 'flower' => 'rose', 'fruit' => 'apple', 'vegetable' => 'carrot' }
:::
Maps can be manipulated using these methods:
set(): Adds a new key-value pair to the Map.get(): Retrieves the value of a key from the Map.delete(): Removes a key-value pair from the Map.has(): Checks if a key exists in the Map.clear(): Removes all key-value pairs from the Map.WeakMap is a collection of key-value pairs just like Map, but with weak references to the keys. The keys must be an object and the values can be anything you like.GET Method: This is used to fetch data from a server.POST Method: This is used to submit data to a server which creates a new resource.PUT Method: This is used to update a resource by replacing it entirely.PATCH Method: This is used to partially update a resource.DELETE Method: This is used to remove records from a database.localStorage and sessionStorage PropertieslocalStorage and sessionStorage properties.localStorage Property: localStorage is the part of the Web Storage API that allows data to persist even after the browser window is closed or the page is refreshed. This data remains available until it is explicitly removed by the application or the user.localStorage.setItem() Method: This method is used to store a key-value pair in localStorage.localStorage.setItem('username', 'Jessica');
localStorage.getItem() Method: This method is used to retrieve the value of a given key from localStorage.localStorage.setItem('username', 'codingRules');
let username = localStorage.getItem('username');
console.log(username); // codingRules
localStorage.removeItem() Method: This method is used to remove a specific item from localStorage using its key.localStorage.removeItem('username');
localStorage.clear() Method: This method is used to clear all of the stored data in localStorage.localStorage.clear();
sessionStorage Property: Stores data that lasts only for the current session and is cleared when the browser tab or window is closed.sessionStorage.setItem() Method: This method is used to store a key-value pair in sessionStorage.sessionStorage.setItem('cart', '3 items');
sessionStorage.getItem() Method: This method is used to retrieve the value of a given key from sessionStorage.sessionStorage.setItem('cart', '3 items');
let cart = sessionStorage.getItem('cart');
console.log(cart); // '3 items'
sessionStorage.removeItem() Method: This method is used to remove a specific item from sessionStorage using its key.sessionStorage.removeItem('cart');
sessionStorage.clear() Method: This method is used to clear all data stored in sessionStorage.sessionStorage.clear();
document.cookie:document.cookie = "organization=freeCodeCamp; expires=Fri, 31 Dec 2021 23:59:59 GMT; path=/";
To delete a cookie, you can set its expiration date to a time in the past.
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
this keyword is used here to refer to the current instance of the class. Below the constructor, you can have what are called methods. Methods are functions defined inside a class that perform actions or operations on the class's data or state. They are used to define behaviors that instances of the class can perform.:::interactive_editor
class Dog {
constructor(name) {
this.name = name;
}
bark() {
console.log(`${this.name} says woof!`);
}
}
const dog = new Dog("Gino");
console.log(dog.name); // Gino
:::
To create a new instance of the class, you will use the new keyword followed by the class name:
const dog = new Dog("Gino");
You can also create classes as class expressions. This is where the class is anonymous and assigned to a variable.
:::interactive_editor
const Dog = class {
constructor(name) {
this.name = name;
}
bark() {
console.log(`${this.name} says woof!`);
}
};
const dog = new Dog("Gino");
console.log(dog.name); // Gino
dog.bark(); // Gino says woof!
:::
extends keyword to implement inheritance. This keyword indicates that a class is the child class of another class.:::interactive_editor
class Vehicle {
constructor(brand, year) {
this.brand = brand;
this.year = year;
}
}
class Car extends Vehicle {
honk() {
console.log("Honk! Honk!");
}
}
const myCar = new Car("freeCodeCamp Motors", 2019);
console.log(myCar.brand); // freeCodeCamp Motors
console.log(myCar.year); // 2019
myCar.honk(); // Honk! Honk!
:::
The super keyword is used to access the parent class's methods, constructors, and fields.
:::interactive_editor
class Vehicle {
constructor(brand, year) {
this.brand = brand;
this.year = year;
}
}
class Car extends Vehicle {
constructor(brand, year, numDoors) {
super(brand, year);
this.numDoors = numDoors;
}
}
const myCar = new Car("freeCodeCamp Motors", 2019, 4);
console.log(myCar.brand); // freeCodeCamp Motors
console.log(myCar.year); // 2019
console.log(myCar.numDoors); // 4
:::
:::interactive_editor
class Movie {
constructor(title, rating) {
this.title = title;
this.rating = rating;
}
static compareMovies(movieA, movieB) {
if (movieA.rating > movieB.rating) {
console.log(`${movieA.title} has a higher rating.`);
} else if (movieA.rating < movieB.rating) {
console.log(`${movieB.title} has a higher rating.`);
} else {
console.log("These movies have the same rating.");
}
}
}
let movieA = new Movie("Movie A", 80);
let movieB = new Movie("Movie B", 45);
Movie.compareMovies(movieA, movieB); // Movie A has a higher rating.
:::
Static methods are also helpful for implementing "factory" methods. A factory method is a method that you define in addition to the constructor to create objects based on specific criteria.
class Pizza {
constructor(type, price) {
this.type = type;
this.price = price;
}
static createMargherita() {
return new this("Margherita", 6.99);
}
}
let myPizza = Pizza.createMargherita();
console.log(myPizza); // Pizza { type: "Margherita", price: 6.99 }
console.log(myPizza.type); // Margherita
:::interactive_editor
class Car {
// Static property
static numberOfWheels = 4;
constructor(make, model) {
this.make = make;
this.model = model;
}
// Instance method
getCarInfo() {
return `${this.make} ${this.model}`;
}
// Static method
static getNumberOfWheels() {
return Car.numberOfWheels;
}
}
// Accessing static property directly from the class
console.log(Car.numberOfWheels); // 4
:::
Here is an example of a recursive function that calculates the factorial of a number:
function findFactorial(n) {
if (n === 0) {
return 1;
}
return n * findFactorial(n - 1);
}
In the above example, the findFactorial function is called recursively until n reaches 0. When n is 0, the base case is reached and the function returns 1. The function then returns the product of n and the result of the recursive call to findFactorial(n - 1).
Here is an example of a regular function vs a curried function:
:::interactive_editor
// Regular function
function average(a, b, c) {
return (a + b + c) / 3;
}
console.log(average(2, 3, 4)); // 3
// Curried function
function curriedAverage(a) {
return function(b) {
return function(c) {
return (a + b + c) / 3;
};
};
}
console.log(curriedAverage(2)(3)(4)); // 3
:::
const curriedAverage = a => b => c => (a + b + c) / 3;
fetch() method that you can use to make these requests.The Fetch API supports various HTTP methods to interact with the server. The most common methods are:
GET method to retrieve data.fetch('https://api.example.com/data')
To use the fetched data, it must be converted to JSON format using the .json() method:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
In this code, the response coming from the Fetch API is a promise and the .then handler is converting the response to a JSON format.
POST method is used to create new resources on the server.fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: 'John Doe',
email: '[email protected]'
})
})
In this example, we're sending a POST request to create a new user. We have specified the method as POST, set the appropriate headers, and included a body with the data we want to send. The body needs to be a string, so we use JSON.stringify() to convert our object to a JSON string.
PUT method is used to update existing resources on the server.fetch('https://api.example.com/users/45', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: 'John Smith',
email: '[email protected]'
})
})
In this example, we are updating the ID 45 that is specified at the end of the URL. We have used the PUT method on the code and also specified the data as the body which will be used to update the identified data.
DELETE method is used to delete resources on the server.fetch('https://api.example.com/users/45', {
method: 'DELETE'
})
In this example, we're sending a DELETE request to remove a user with the ID 45.
async operation is completed.const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data received successfully');
}, 2000);
});
.then() method is used in a Promise to specify what should happen when the Promise is fulfilled, while .catch() is used to handle any errors that occur..then() and .catch() with a Promise:promise
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
In the above example, the .then() method is used to log the data received from the Promise, while the .catch() method is used to log any errors that occur.
.then() can return a new Promise, allowing you to perform a sequence of asynchronous operations one after the other.fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
console.log(data);
return fetch('https://api.example.com/other-data');
})
.then(response => response.json())
.then(otherData => {
console.log(otherData);
})
.catch(error => {
console.error(error);
});
In the above example, we first fetch data from one URL, then fetch data from another URL based on the first response, and finally log the second data received.
The catch method would handle any errors that occur during the process. This means you don't need to add error handling to each step, which can greatly simplify your code.
async/await to handle promisesAsync/await makes writing & reading asynchronous code easier which is built on top of Promises.
async keyword is used to define an asynchronous function. An async function returns a Promise, which resolves with the value returned by the async function.await keyword is used inside an async function to pause the execution of the function until the Promise is resolved. It can only be used inside an async function.async/await::::interactive_editor
async function delayedGreeting(name) {
console.log("A Messenger entered the chat...");
await new Promise(resolve => setTimeout(resolve, 2000));
console.log(`Hello, ${name}!`);
}
delayedGreeting("Alice");
console.log("First Printed Message!");
:::
In the above example, the delayedGreeting function is an async function that pauses for 2 seconds before printing the greeting message. The await keyword is used to pause the function execution until the Promise is resolved.
async/await is error handling via try/catch blocks. Here's an example:async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
fetchData();
In the above example, the try block contains the code that might throw an error, and the catch block handles the error if it occurs. This makes error handling more straightforward and readable.
async attributeasync attribute tells the browser to download the script file asynchronously while continuing to parse the HTML document.async for independent scripts where the order of execution doesn't matterdefer attributeThe defer attribute also downloads the script asynchronously, but it defers the execution of the script until after the HTML document has been fully parsed.
The defer scripts maintain the order of execution as they appear in the HTML document.
It's important to note that both async and defer attributes are ignored for inline scripts and only work for external script files.
When both async and defer attributes are present, the async attribute takes precedence.
The Geolocation API provides a way for websites to request the user's location.
The example below demonstrates the API's getCurrentPosition() method which is used to get the user's current location.
navigator.geolocation.getCurrentPosition(
(position) => {
console.log("Latitude: " + position.coords.latitude);
console.log("Longitude: " + position.coords.longitude);
},
(error) => {
console.log("Error: " + error.message);
}
);
In this code, we're calling getCurrentPosition and passing it a function which will be called when the position is successfully obtained.
The position object contains a variety of information, but here we have selected latitude and longitude only.
If there is an issue with getting the position, then the error will be logged to the console. It is important to respect the user's privacy and only request their location when necessary.
Review the JavaScript topics and concepts.