functions.notes
Document Details
Uploaded by Jaycelab
Tags
Full Transcript
// Functions Intro - Functions are the essential building blocks of Javascript and prevents redundancy in code by using reusable code blocks. - Functions encapsulates multiple statements, expressions, and logics into a single unit. - Similar to mini programs inside a much larger program - Function D...
// Functions Intro - Functions are the essential building blocks of Javascript and prevents redundancy in code by using reusable code blocks. - Functions encapsulates multiple statements, expressions, and logics into a single unit. - Similar to mini programs inside a much larger program - Function Declaration: Executing the function using the keyword function followed by the function name and the code block inside curly braces. - Syntax: function functionName(parameters) { code block } - Data that is passed into the function is called arguments and accepts all data types including primitive and non-primitive data types, as well as other functions known as callback functions. - Code block is denoted by curly braces and contains the logic of the function. This can include variables, loops, conditional statements, and other functions. - Function declaration in Javascript are hoisted to the global scope, which means that you can use the function before it is declared. - Code inside a function is functional scope and is only accessible within the function - Return keyword returns the operand on the right & terminates the function (optional) - Functions are classified as objects in Javascript and can be made to run in context of other functions or objects - Functions as Objects: Concept can be pictures as a car engine which is used in one car and then used in another car. In both cases, the engine may produce different results based on the car it is used in due to the cars design, weight, and other factors. However, the engine remains the same. - Conceptual definition - Functions are first class objects in JavaScript meaning that functions are similar to objects and can have internal properties and methods. Methods are properties on the object that feature functions which can be passed as arguments to other functions, returned from other functions, and assigned to variables. - Functions can be reused without exposing their internals and act like building blocks to an application as it composes and reuses multiple functions together - *In summary, functions are reusable code blocks that encapsulate multiple statements, expressions, and logics into a single unit while removing redundancy in code.* //Function Declaration - Declaring a function declaration after using the console.log command will still execute the function as the function declaration is hoisted to the global scope. - Function hoisting is a feature where function declarations are moved to the top of their containing scope during the compile phase. This means that you can use the function before it is declared. // Function Expression - Function expressions are similar to function declarations but are assigned to a variable. - A function without a name is called an anonymous function. The variable that it is assigned to is known as an identifier. - The major difference between function expressions and function declarations is that function expressions are not hoisted to the top of the global scope. This means that you cannot use the function before it is declared whereas function declarations can be used before, they are declared or after the return statement. - Using nullish coalescing operator to check if a parameter is given a value or not. If the parameter is not given a value, the function will return a default value as specified. a. We can also assign the Number method to only accept a number as a parameter and return a default value if the parameter is not a number. - Unlike function declarations, a function expression isn't hoisted to the top of its lexical environment and is only available for use after it has been declared in code. // This Keyword - The this keyword refers to the object that the function is a property of. - In a web browser, the 'this' keyword points to the global window object outside a function. E.g. console.log(this) will return the window object. - Inside a function, the 'this' keyword may point to the global scope if 'use strict' is not used. If 'use strict' is used, the 'this' keyword will return undefined. - If the 'this' keyword is used in an object, it points to the object that the function is a property of and allows us to access the object's properties, methods, and values. - Object shorthand syntax allows us to create a function inside an object without using the function keyword. - Functions inside an object using the 'this' keyword can often be labeled as methods because it offers a way to build in features and behaviors into an object. This also applies when adding a function later on to an object using the dot notation. - Properties accessing the 'this' keyword in a function returns undefined because the property is not found in the function itself. Instead, using the 'this' keyword is pointing to the object reference and not the function itself. - The 'this' keyword in a function provides access to the context within which the function is executed. This let's a function access data from the context. The benefit - A reusable function can be made to execute in the context of multiple objects where it can access data from that object using the 'this' keyword. - Function declaration or expression creates a this context based on the location of the function call. If the function is called in the global scope, the this context will be the global object. If the function is called in an object, the this context will be the object. - // Function Call method - To gain access to an object within a function using the 'this' keyword, we can append an invocation using the built in call method. This allows us to bind the 'this' context to the object we want to access. - The call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). This allows borrowing methods from other objects, executing them within a different context, overriding the default value, and passing arguments. // Function Bind method - We can also run the bind method to bind the 'this' context to the object we want to access. The bind method creates a new function that, when called, has its 'this' keyword set to the provided value. - The difference between call and bind is that call invokes the function immediately and bind returns (or bounds) a new function that can be invoked later for reusability //Arrow Functions - Arrow functions are anonymous functions that can be assigned to constants and variables to make them equivalent to function expressions. - The "Fat Arrow" =\> is generally pointed to a code block that follows the arrow and is used to define the function. - Arrow functions can be written both declaratively and as expressions. - Arrow functions let you return an expression without using the return keyword or curly braces. A code block is also not necessary if the function is only returning a single expression or one liner - Wrapping an object first with a pair of parentheses returns the object as a whole. This is because the parentheses are used to group expressions and operators. - Useful tip - If an object property is named the same. E.g. user: user, you can use the shorthand syntax to only write the property name once. E.g. user - Inline functions are the arrow functions that have only one expression and thus, usually eliminate the need of curly braces and the return keyword. - Arrow function does not create a context of its own and instead inherits the context of the parent function. This means that the 'this' keyword in an arrow function will always refer to the parent function's context. - Declaring this keyword inside an arrow function, within an object, will throw an error or NaN because the arrow function does not have its own context and instead inherits the context of the parent function, which happens to be window. This does not create a contextual bind to this keyword since a new this context is not created. - What makes arrow functions different is that they do not create their own 'this' context and access the 'this' context of their parent function. //Constructor Functions - Constructor functions are used to create multiple instances of an object with the same properties and methods. - Constructor functions are similar to regular functions but are named with a capital letter to distinguish them from regular functions and allows them to be used with the new and this keywords. - This.property exposes the property to the object and allows the property to be accessed by the object. - To instantiate a new object, we use the new keyword followed by the constructor function and assign it to a variable with values defined as set during creation time. - Constructor functions will never be used as regular function by simply invoking (or calling) it. Instead, it will be used to create new objects with the new keyword. - Common constructor function is the Date object which is used to create a new date object with the current date and time. We also access the member method getDay() to return the day of the week. - Can be assigned using both declaration and expression syntax. - **proto** is a property that is used to access the prototype of an object. It is a reference to the object's prototype object from which it inherits properties and methods. - To return an object literal expression requires parentheses around expression to avoid syntax error. This is because the curly braces are interpreted as a code block and not an object literal. - Assignment operators can also be applied to expressions with 'this' methods - Constructor functions are the basis of object-oriented programming in JavaScript and are used to create multiple instances of an object with the same properties and methods. It is first defined with a template out of which objects are instantiate and spawned - A constructor function can be used for generating Objects programmatically by invoking functions that accept values of a pre-configured set of properties, as parameters. One of the key things to keep in mind is that constructor function names should begin with an upper-case character. - These functions provide an easy way to generate template objects by simply ingesting a set of parameters. In such a situation, you can pre-define the template object by way of properties on the 'this' context of the constructor function. //Default Parameters Values - When using a nullish coalescing operator , setting a 0 will still default to 0 even when passing an argument as Null. Null is set explicitly, which eliminates the need of an alterative of it. This is where initializing parameters to a default value comes to play. - Parameters defined earlier to default parameters can be available for default parameters. For eg, for default parameter z, we make use of x and y. function add(x, y, z=x+y) - Function parameters default to undefined if no value is assigned to them. - Default parameters are used to assign a default value to a parameter if no argument is passed to the function. This is useful when you want to avoid undefined values in your code. If a function is invoked without passing all arguments that are necessary for computation, you are bound to get incorrect results or even errors. The traditional way to solve this problem is to implement a series of checks in the function's body and provide alternate values if arguments are missing, in which case they're undefined. - Now of course, you don't need to do all that. Default parameters, as a feature has been designed to address missing arguments by providing a default value which will be automatically substituted if the said argument is missing value or is provided with undefined or null as values.