JavaScript

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

mathematical assignment operators

+= -= *= /= ++ --

setters

Along with getter methods, we can also create setter methods which reassign values of existing properties within an object. const person = { _age: 37, set age(newAge){ if (typeof newAge === 'number'){ this._age = newAge; } else { console.log('You must assign a number to age'); } } }; person.age = 40; console.log(person._age); // Logs: 40 Setter methods like age do not need to be called with a set of parentheses. Syntactically, it looks like we're reassigning the value of a property. However, even with a setter method, it is still possible to directly reassign properties. For example, in the example above, we can still set ._age directly: person._age = 'forty-five' console.log(person._age); // Prints forty-five

instances

An instance is an object that contains the property names and methods of a class, but with unique property values. Let's look at our Dog class example. class Dog { constructor(name) { this.name = name; this.behavior = 0; } } const halley = new Dog('Halley'); // Create new Dog instance console.log(halley.name); // Log the name value saved to halley // Output: 'Halley'

.pop()

Another array method, .pop(), removes the last item of an array. .pop() does not take any arguments, it simply removes the last element. .pop() returns the value of the last element. .pop() is a method that mutates the initial array. When you need to mutate an array by removing the last element, use .pop().

.forEach()

Aptly named, .forEach() will execute the same code for each element of an array. .forEach() takes an argument of callback function. Remember, a callback function is a function passed as an argument into another function. .forEach() loops through the array and executes the callback function for each element. During each execution, the current element is passed as an argument to the callback function. The return value for .forEach() will always be undefined. Another way to pass a callback for .forEach() is to use arrow function syntax. We can also define a function beforehand to be used as the callback function.

arrays

Arrays are JavaScript's way of making lists. Arrays can store any data types (including strings, numbers, and booleans). Like lists, arrays are ordered, meaning each item has a numbered position. We can have an array that holds all the same data types or an array that holds different data types.

inheritance

When multiple classes share properties or methods, they become candidates for inheritance — a tool developers use to decrease the amount of code they need to write. With inheritance, you can create a parent class (also known as a superclass) with properties and methods that multiple child classes (also known as subclasses) share. The child classes inherit the properties and methods from their parent class.

indexing

cities[0] will access the element at index 0 in the array cities. You can also access individual characters in a string using bracket notation and the index.

for...in

for...in will execute a given block of code for each property in an object. for (let crewMember in spaceship.crew) { console.log(`${crewMember}: ${spaceship.crew[crewMember].name}`) }; for (let variableName in outerObject.innerObject) { console.log(`${variableName}: ${outerObject.innerObject[variableName].propertyName}`) };

Built-In Objects

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects

Array Methods

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

Iterator Array Methods

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Iteration_methods

Built-In Object Methods

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#Methods

String Methods

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype

template literal

A template literal is wrapped by backticks ` (this key is usually located on the top of your keyboard, left of the 1 key). Inside the template literal, you'll see a placeholder, ${XX}. The value of XX is inserted into the template literal.

property value shorthand

But we can use a destructuring technique, called property value shorthand, to save ourselves some keystrokes. For example: const monsterFactory = (name, age) => { return { name, age } };

+

When a + operator is used on two strings, it appends the right string to the left string.

return

When a return statement is used in a function body, the execution of the function is stopped and the code that follows it will not be executed. The return keyword is powerful because it allows functions to produce an output. We can then save the output to a variable for later use.

block scope

When a variable is defined inside a block, it is only accessible to the code within the curly braces {}. We say that variable has block scope because it is only accessible to the lines of code within that block.

nested array

When an array contains another array it is known as a nested array. If we wanted to access the elements within the nested array we can chain, or add on, more bracket notation with index values. nestedArr[1][0]

privacy

When discussing privacy in objects, we define it as the idea that only certain properties should be mutable or able to change in value. Certain languages have privacy built-in for objects, but JavaScript does not have this feature. Rather, JavaScript developers follow naming conventions that signal to other developers how to interact with a property. One common convention is to place an underscore _ before the name of a property to mean that the property should not be altered.

//

A single line comment will comment out a single line and is denoted with two forward slashes // preceding it. You can also use a single line comment to comment after a line of code.

for loop

A for loop contains three expressions separated by ; inside the parentheses: 1. An initialization starts the loop and can also be used to declare the iterator variable. 2. A stopping condition is the condition that the iterator variable is evaluated against— if the condition evaluates to true the code block will run, and if it evaluates to false the code will stop. 3. An iteration statement is used to update the iterator variable on each loop. The for loop syntax looks like this: for (let counter = 0; counter < 4; counter++) { console.log(counter); }

function declaration

A function declaration binds a function to a name, or an identifier. A function declaration consists of: The function keyword. The name of the function, or its identifier, followed by parentheses. A function body, or the block of statements required to perform a specific task, enclosed in the function's curly brackets, { }.

higher-order function

A higher-order function is a function that either accepts functions as parameters, returns a function, or both

.map()

When .map() is called on an array, it takes an argument of a callback function and returns a new array

/*

A multi-line comment will comment out multiple lines and is denoted with /* to begin the comment, and */ to end the comment. You can also use this syntax to comment something out in the middle of a line of code.

arrow function syntax

A shorter way to write functions by using the special "fat arrow" () => notation. Arrow functions remove the need to type out the keyword function every time you need to create a function. Instead, you first include the parameters inside the ( ) and then add an arrow => that points to the function body surrounded in { }.

const

A const variable cannot be reassigned because it is constant. If you try to reassign a const variable, you'll get a TypeError. Constant variables must be assigned a value when declared. If you try to declare a const variable without a value, you'll get a SyntaxError.

do...while statement

A do...while statement says to do a task once and then keep doing it until a specified condition is no longer met. The syntax for a do...while statement looks like this: let countString = ''; let i = 0; do { countString = countString + i; i++; } while (i < 5); console.log(countString); Note that the while and do...while loop are different! Unlike the while loop, do...while will run at least once whether or not the condition evaluates to true.

factory function

A factory function is a function that returns an object and can be reused to make multiple object instances. Factory functions can also have parameters allowing us to customize the object that gets returned. const monsterFactory = (name, age, energySource, catchPhrase) => { return { name: name, age: age, energySource: energySource, scare() { console.log(catchPhrase); } } }; To make an object that represents a specific monster like a ghost, we can call monsterFactory with the necessary arguments and assign the return value to a variable: const ghost = monsterFactory('Ghouly', 251, 'ectoplasm', 'BOO!'); ghost.scare(); // 'BOO!'

comparison operators

Less than: < Greater than: > Less than or equal to: <= Greater than or equal to: >= Is equal to: === Is NOT equal to: !==

.findIndex()

Calling .findIndex() on an array will return the index of the first element that evaluates to true in the callback function If there isn't a single element in the array that satisfies the condition in the callback, then .findIndex() will return -1

classes

Classes are a tool that developers use to quickly produce similar objects. class Dog { constructor(name) { this._name = name; this._behavior = 0; } get name() { return this._name; } get behavior() { return this._behavior; } incrementBehavior() { this._behavior ++; } } Class method and getter syntax is the same as it is for objects except you can not include commas between methods.

default parameters

Default parameters allow parameters to have a predetermined value in case there is no argument passed into the function or if the argument is undefined when called. By using a default parameter, we account for situations when an argument isn't passed into a function that is expecting an argument.

Number.isInteger()

Determine whether the passed value is an integer.

.startsWith()

Determines whether a string begins with the characters of another string.

length

Every string instance has a property called length that stores the number of characters in that string. You can retrieve property information by appending the string with a period and the property name.

.indexOf()

Finds the index of a particular element in an array.

concise body

Functions that take only a single parameter do not need that parameter to be enclosed in parentheses. However, if a function takes zero or multiple parameters, parentheses are required. A function body composed of a single-line block does not need curly braces. Without the curly braces, whatever that line evaluates will be automatically returned. The contents of the block should immediately follow the arrow => and the return keyword can be removed. This is referred to as implicit return.

getters

Getters are methods that get and return the internal properties of an object. const person = { _firstName: 'John', _lastName: 'Doe', get fullName() { if (this._firstName && this._lastName){ return `${this._firstName} ${this._lastName}`; } else { return 'Missing a first name or a last name.'; } } } // To call the getter method: person.fullName; // 'John Doe' In the last line we call fullName on person. In general, getter methods do not need to be called with a set of parentheses. Syntactically, it looks like we're accessing a property. Now that we've gone over syntax, let's discuss some notable advantages of using getter methods: - Getters can perform an action on the data when getting a property. - Getters can return different values using conditionals. - In a getter, we can access the properties of the calling object using this. - The functionality of our code is easier for other developers to understand.

constructor

JavaScript calls the constructor() method every time it creates a new instance of a class. class Dog { constructor(name) { this.name = name; this.behavior = 0; } } - Dog is the name of our class. By convention, we capitalize and CamelCase class names. - JavaScript will invoke the constructor() method every time we create a new instance of our Dog class. - This constructor() method accepts one argument, name. - Inside of the constructor() method, we use the this keyword. In the context of a class, this refers to an instance of that class. In the Dog class, we use this to set the value of the Dog instance's name property to the name argument. - Under this.name, we create a property called behavior, which will keep track of the number of times a dog misbehaves. The behavior property is always initialized to zero.

Math

If you wanted to perform more complex mathematical operations than arithmetic, JavaScript has the built-in Math object. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math

||

In a boolean condition, JavaScript assigns the truthy value to a variable if you use the || operator in your assignment. let defaultName = username || 'Stranger';

function expression

In a function expression, the function name is usually omitted. A function with no name is called an anonymous function. A function expression is often stored in a variable in order to refer to it. To declare a function expression: Declare a variable to make the variable's name be the name, or identifier, of your function. Since the release of ES6, it is common practice to use const as the keyword to declare the variable. Assign as that variable's value an anonymous function created by using the function keyword followed by a set of parentheses with possible parameters. Then a set of curly braces that contain the function body.

camel casing

In camel casing you group words into one, the first word is lowercase, then every word that follows will have its first letter uppercased.

destructured assignment

In destructured assignment we create a variable with the name of an object's key that is wrapped in curly braces { } and assign to it the object. Take a look at the example below: const { residence } = vampire; console.log(residence); // Prints 'Transylvania'

global scope

In global scope, variables are declared outside of blocks. These variables are called global variables. Because global variables are not bound inside a block, they can be accessed by any code in the program, including code in blocks.

.join()

Joins all elements of an array into a string. arr.join(separator) Separator specifies a string to separate each pair of adjacent elements of the array.

.filter()

Like .map(), .filter() returns a new array. However, .filter() returns an array of elements after filtering out certain elements from the original array. The callback function for the .filter() method should return true or false depending on the element that is passed to it. The elements that cause the callback function to return true are added to the new array.

Math.floor()

Math.floor() takes a decimal number, and rounds down to the nearest whole number.

subclass

Now that we have these shared properties and methods in the parent Animal class, we can extend them to the subclass, Cat. class Cat extends Animal { constructor(name, usesLitter) { super(name); this._usesLitter = usesLitter; } } In the example above, we create a new class named Cat that extends the Animal class. - The super keyword calls the constructor of the parent class. In this case, super(name) passes the name argument of the Cat class to the constructor of the Animal class. When the Animal constructor runs, it sets this._name = name; for new Cat instances. - Notice, we call super on the first line of our constructor(), then set the usesLitter property on the second line. In a constructor(), you must always call the super method before you can use the this keyword — if you do not, JavaScript will throw a reference error. To avoid reference errors, it is best practice to call super on the first line of subclass constructors.

objects

Objects can be assigned to variables just like any JavaScript type. We use curly braces, {}, to designate an object literal: let spaceship = {}; // spaceship is an empty object We fill an object with unordered data. This data is organized into key-value pairs. A key is like a variable name that points to a location in memory that holds a value. A key's value can be of any data type in the language including functions or other objects. We make a key-value pair by writing the key's name, or identifier, followed by a colon and then the value. We separate each key-value pair in an object literal with a comma (,). Keys are strings, but when we have a key that does not have any special characters in it, JavaScript allows us to omit the quotation marks

methods

Objects, including instances of data types, can have methods which perform actions. Methods are called by appending the object or instance with a period, the method name, and parentheses.

properties

Objects, including instances of data types, can have properties, stored information. The properties are denoted with a . after the name of the object.

console.log()

One action, or method, that is built into the console object is the .log() method. When we write console.log() what we put inside the parentheses will get printed, or logged, to the console.

.push()

One method, .push() allows us to add items to the end of an array. We access the push method by using dot notation. Then we call it like a function. That's because .push() is a function and one that JavaScript allows us to use right on an array. .push() can take a single argument or multiple arguments separated by commas. Notice that .push() changes, or mutates, itemTracker. You might also see .push() referred to as a destructive array method since it changes the initial array.

.length

One of an array's built-in properties is length and it returns the number of items in the array. We access the .length property just like we do with strings. objectives.length

parameters and arguments

Parameters allow functions to accept input(s) and perform a task using the input(s). We use parameters as placeholders for information that will be passed to the function when it is called. When calling a function that has parameters, we specify the values in the parentheses that follow the function name. The values that are passed to the function when it is called are called arguments. Arguments can be passed to the function as values or variables.

Math.ceil()

Returns the smallest integer greater than or equal to a number.

scope pollution

Scope pollution is when we have too many global variables that exist in the global namespace, or when we reuse variables across different scopes. Scope pollution makes it difficult to keep track of our different variables and sets us up for potential accidents.

.reduce()

The .reduce() method returns a single value after iterating through the elements of an array, thereby reducing the array. Take a look at the example below: const numbers = [1, 2, 4, 10]; const summedNums = numbers.reduce((accumulator, currentValue) => { return accumulator + currentValue }) console.log(summedNums) // Output: 17 Now let's go over the use of .reduce() from the example above: - The callback function has two parameters, accumulator and currentValue. The value of accumulator starts off as the value of the first element in the array and the currentValue starts as the second element. - As .reduce() iterates through the array, the return value of the callback function becomes the accumulator value for the next iteration, currentValue takes on the value of the current element in the looping process. The .reduce() method can also take an optional second parameter to set an initial value for accumulator (remember, the first argument is the callback function!). For instance: const numbers = [1, 2, 4, 10]; const summedNums = numbers.reduce((accumulator, currentValue) => { return accumulator + currentValue }, 100) // <- Second argument for .reduce() console.log(summedNums); // Output: 117

.unshift()

The .unshift() method adds an element to the beginning of an array.

Object.assign()

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object. const target = { a: 1, b: 2 }; const source = { b: 4, c: 5 }; const returnedTarget = Object.assign(target, source); console.log(target); // expected output: Object { a: 1, b: 4, c: 5 } console.log(returnedTarget); // expected output: Object { a: 1, b: 4, c: 5 }

Object.entries()

The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for...in loop const object1 = { a: 'somestring', b: 42 }; for (let [key, value] of Object.entries(object1)) { console.log(`${key}: ${value}`); } // expected output: // "a: somestring" // "b: 42" // order is not guaranteed

Object.keys()

The Object.keys() method returns an array of a given object's own property names, in the same order as we get with a normal loop. const object1 = { a: 'somestring', b: 42, c: false }; console.log(Object.keys(object1)); // expected output: Array ["a", "b", "c"]

break

The break keyword allows programs to "break" out of the loop from within the loop's block. Let's check out the syntax of a break keyword: for (let i = 0; i < 99; i++) { if (i > 2 ) { break; } console.log('Banana.'); } console.log('Orange you glad I broke out the loop!');

iterators

The built-in JavaScript array methods that help us iterate are called iteration methods, at times referred to as iterators. Iterators are methods called on arrays to manipulate elements and return values.

ternary operators

The condition is provided before the ?. Two expressions follow the ? and are separated by a colon :. If the condition evaluates to true, the first expression executes. If the condition evaluates to false, the second expression executes. Like if...else statements, ternary operators can be used for conditions which evaluate to true or false.

console

The console keyword refers to an object, a collection of data and actions, that we can use in our code.

--

The decrement operator will decrease the value of the variable by 1.

if

The if keyword followed by a set of parentheses () which is followed by a code block, or block statement, indicated by a set of curly braces {}. Inside the parentheses (), a condition is provided that evaluates to true or false. If the condition evaluates to true, the code inside the curly braces {} runs, or executes. If the condition evaluates to false, the block won't execute.

.includes()

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

++

The increment operator will increase the value of the variable by 1.

let

The let keyword signals that the variable can be reassigned a different value.

changing elements

The line, seasons[3] = 'Autumn'; tells our program to change the item at index 3 of the seasons array to be 'Autumn' instead of what is already there.

falsy

The list of falsy values includes: 0 Empty strings like "" or '' null which represent when there is no value at all undefined which represent when a declared variable lacks a value NaN, or Not a Number

%

The remainder operator, sometimes called modulo, returns the number that remains after the right-hand number divides into the left-hand number as many times as it evenly can.

.slice()

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified. array.splice(start, deleteCount, item)

switch

The switch keyword initiates the statement and is followed by ( ... ), which contains the value that each case will compare. Inside the block, { ... }, there are multiple cases. The case keyword checks if the expression matches the specified value that comes after it. The break keyword tells the computer to exit the block and not execute any more code or check any other cases inside the code block. Note: Without the break keyword at the end of each case, the program would execute the code for all matching cases and the default code as well. This behavior is different from if/else conditional statements which execute only one block of code. At the end of each switch statement, there is a default statement. If none of the cases are true, then the code in the default statement will run. switch(expression) { case x: // code block break; case y: // code block break; default: // code block }

this

The this keyword references the calling object which provides access to the calling object's properties const goat = { dietType: 'herbivore', makeSound() { console.log('baaa'); }, diet() { console.log(this.dietType); } }; goat.diet(); // Output: herbivore Arrow functions inherently bind, or tie, an already defined this value to the function itself that is NOT the calling object. The key takeaway is to avoid using arrow functions when using this in a method

typeof

The typeofoperator checks the value to its right and returns, or passes back, a string of the data type.

passed by reference

This means when we pass a variable assigned to an object into a function as an argument, the computer interprets the parameter name as pointing to the space in memory holding that object. As a result, functions which change object properties actually mutate the object permanently (even when the object is assigned to a const variable). However, when we try the same thing using a function designed to reassign the object passed into it, the reassignment doesn't stick.

Math.random()

This method returns a random number between 0 and 1.

.toUpperCase()

This method returns a string in all capital letters.

function call

To call a function in your code, you type the function name followed by parentheses. This function call executes the function body, or all of the statements between the curly braces in the function declaration.

bracket notation

To use bracket notation to access an object's property, we pass in the property name (key) as a string. We *must* use bracket notation when accessing keys that have numbers, spaces, or special characters in them. Without bracket notation in these situations, our code would throw an error. With bracket notation you can also use a variable inside the brackets to select the keys of an object. This can be especially helpful when working with functions

.trim()

Trims whitespace from the beginning and end of the string. Part of the ECMAScript 5 standard.

.shift()

Use the .shift() method to remove the first item.

else

Uses the else keyword following the code block of an if statement. Has a code block that is wrapped by a set of curly braces {}. The code inside the else statement code block will execute when the if statement's condition evaluates to false.

local variables

Variables that are declared with block scope are known as local variables because they are only available to the code that is part of the same block.

callback function

We call the functions that get passed in as parameters and invoked callback functions because they get called during the execution of the higher-order function With callbacks, we pass in the function itself by typing the function name without the parentheses (that would evaluate to the result of calling the function): const timeFuncRuntime = funcParameter => { let t1 = Date.now(); funcParameter(); let t2 = Date.now(); return t2 - t1; } const addOneToOne = () => 1 + 1; timeFuncRuntime(addOneToOne);

helper functions

We can also use the return value of a function inside another function. These functions being called within another function are often referred to as helper functions. Since each function is carrying out a specific task, it makes our code easier to read and debug if necessary. Writing helper functions can help take large and difficult tasks and break them into smaller and more manageable tasks.

property assignment

We can use either dot notation, ., or bracket notation, [], and the assignment operator, = to add new key-value pairs to an object or change an existing property. - If the property already exists on the object, whatever value it held before will be replaced with the newly assigned value. - If there was no property with that name, a new property will be added to the object. It's important to know that although we can't reassign an object declared with const, we can still mutate it, meaning we can add new properties and change the properties that are there. const spaceship = {type: 'shuttle'}; spaceship = {type: 'alien'}; // TypeError: Assignment to constant variable. spaceship.type = 'alien'; // Changes the value of the type property spaceship.speed = 'Mach 5'; // Creates a new key of 'speed' with a value of 'Mach 5'

method

When the data stored on an object is a function we call that a method. A property is what an object has, while a method is what an object does. We can include methods in our object literals by creating ordinary, comma-separated key-value pairs. The key serves as our method's name, while the value is an anonymous function expression. const alienShip = { invade: function () { console.log('Hello! We have come to dominate your planet. Instead of Earth, it shall be called New Xaculon.') } }; With the new method syntax introduced in ES6 we can omit the colon and the function keyword. const alienShip = { invade () { console.log('Hello! We have come to dominate your planet. Instead of Earth, it shall be called New Xaculon.') } };

dot notation

With property dot notation, we write the object's name, followed by the dot operator and then the property name (key): let spaceship = { homePlanet: 'Earth', color: 'silver' }; spaceship.homePlanet; // Returns 'Earth', spaceship.color; // Returns 'silver',

delete

You can delete a property from an object with the delete operator. const spaceship = { 'Fuel Type': 'Turbo Fuel', homePlanet: 'Earth', mission: 'Explore the universe' }; delete spaceship.mission; // Removes the mission property

while loop

let counterTwo = 1; while (counterTwo < 4) { console.log(counterTwo); counterTwo++; } Let's break down what's happening with our while loop syntax: - The counterTwo variable is declared before the loop. We can access it inside our while loop since it's in the global scope. - We start our loop with the keyword while followed by our stopping condition, or test condition. This will be evaluated before each round of the loop. While the condition evaluates to true, the block will continue to run. Once it evaluates to false the loop will stop. - Next, we have our loop's code block which prints counterTwo to the console and increments counterTwo. In situations when we want a loop to execute an undetermined number of times, while loops are the best choice.

logical operators

the and operator (&&) the or operator (||) the not operator, otherwise known as the bang operator (!)

var

var, short for variable, is a JavaScript keyword that creates, or declares, a new variable.


Ensembles d'études connexes

Chapter 16: Drug Therapy to Decrease Pain, Fever, and Inflammation Supplement

View Set

02.07 Review and Practice Exam for Geometry

View Set

Organizational Behavior Ch 1,2,3,4,5,6

View Set

UCONN Anthropology 1000 Final Exam

View Set