Intro to Fns:
Fundamental building blocks of the language.
Most essential concepts.
Fn - piece of code which can be used again and again.
{Invoking, Running, Calling} a Fn all mean the same.
Fn - can take data as arguments, return data as result after computation.
Fn call is replaced by the result returned from it after execution.
Fns are perfect for implementing DRY principle
Arguments are passed, parameters are placeholder which receives values passed to fn.
Fn declaration vs expression:
Fn declaration begins with fn keyword.
Fn expression are anonymous fn, stored inside a variable. Then that variable which stores the fn act as a fn.
The anonymous fn defn is an expression, and the expression produces a value. Fn are just values.
Fn are not a String, Number type. Its a value, hence can be stored in a variable.
Fn declaration can be called even before they are defined in the code i.e they are hoised. This doesn't work with Fn expression.
Fn expression forces the user to define fns first, then use them later. Everything is stored inside variables.
Both have their place in JS, hence needs to be mastered properly.
Fn expression = essentially a fn value stored in a variable
Arrow Fn came with ES6
Implicit return for one-liner, for multiple lines explicit return is needed.
Arrow fns don't get 'this' keyword of their own
Learning is not an a linear process, knowledge builds up in an incremental way gradually. You cannot learn everything about a thing in one go.
## Default parameters const bookings = []; const createBooking = function(flightNum, numPassengers=1, price= 100 * numPassengers){ // It will work for parameters defined before in the list like numPassengers is defined before its used in expression of next argument else it won't work. // Arguments cannot be skipped also with this method. If you want to skip an argument, then manually pass undefined value for it which is equivalent to skipping an argument /* Setting default values pre-ES6 days. numPassengers = numPassengers || 1; price = price || 199;*/ // Using enhanced object literal, where if same property name & value is there, just write them once as shown below. const booking = { flightNum, numPassengers, price, }; console.log(booking); bookings.push(booking); } createBooking('AI123'); /* { flightNum: 'AI123', numPassengers: 1, price: 100 } */ createBooking('IN523',7); /* { flightNum: 'IN523', numPassengers: 7, price: 700 } */ createBooking('SJ523',5); /* { flightNum: 'SJ523', numPassengers: 5, price: 500 } */ createBooking('AA523',undefined, 100000); /* { flightNum: 'AA523', numPassengers: 1, price: 100000 } */
Calling one fn from inside another fn:
Very common technique to suport DRY principle.
Supports maintainability
return immediately exits the fn
return = to output a value from the fn, terminate the execution
Three ways of writing fn, but all work in a similar way i.e Input, Computation, Output
Parameters = placeholders to receive i/p values, Like local variables of a fn.
How passing arguments works i.e Value vs Reference Types
Primitives are passed by value to fn. Original value remains intact.
Objects are passed by reference to fn. Original value is changed.
JS doesn not have pass value by reference.
Interaction of different fns with same object can create trouble sometimes
Fns are first-class in JS, hence we can write HO fns.
Fns are treated as values, just another 'type' of object.
Since objects are values, fns are values too. Hence, can also be stored in variables, attached as object properties etc.
Also, fns can be passed to other fns also. Ex. event listeners-handlers.
Return from fns.
Fns are objects, and objects have their own methods-properties in JS. Hence, fn can have methods as well as properties which can be called on them. Ex call, apply, bind etc.
Higher Order Fn : Fn that receives another fn as an argument, that returns a new fn or both. Only possible because fns are first class in JS
Fn that is passed in callback fn, which will be called by HOF.
Fns that return another fn, i.e in Closures.
First class fns and HOF are different concepts.
Callback Fns Adv:
Allow us to create abstractions. Makes easier to look at larger problem.
Modularize the code into more smaller chunks to be resused.
// Example for CB & HOF: // CB1 const oneWord = function(str){ return str.replace(/ /g,'').toLowerCase(); }; // CB2 const upperFirstWord = function(str){ const [first, ...others] = str.split(' '); return [first.toUpperCase(), ...others].join(' '); }; // HOF const transformer = function(str, fn){ console.log(`Original string: ${str}`); console.log(`Transformed string: ${fn(str)}`); console.log(`Transformed by: ${fn.name}`); }; transformer('JS is best', upperFirstWord); transformer('JS is best', oneWord); // JS uses callbacks all the time. const hi5 = function(){ console.log("Hi"); }; document.body.addEventListener('click', hi5); // forEach will be exectued for each value in the array. ['Alpha','Beta','Gamma','Delta','Eeta'].forEach(hi5);
Fns returning another fn.
// A fn returning another fn. const greet = function(greeting){ return function(name){ console.log(`${greeting} ${name}`); } } const userGreet = greet('Hey'); userGreet("Alice"); userGreet("Lola"); // Another way to call greet('Hello')("Lynda"); // Closures are widely used in Fnal programming paradigm. // Same work using Arrow Fns. Below is one arrow fn returning another arrow fn. const greetArr = greeting => name => console.log(`${greeting} ${name}`); greetArr('Hola')('Roger');
"You will only progress once you understand a certain topic thoroughly"
call(), apply(), bind():
Used to set 'this' keyword by explicitly setting its value.
call - takes a list of arguments after the value of 'this' keyword.
apply - takes an array of arguments after the value of 'this' keyword. It will take elements from that array, and pass it into functions.
bind(): This method creates a new function with the this keyword bound to the specified object. The new function retains the this context set by .bind() no matter how the function is invoked.
call() and apply(): These methods call a function with a specified this value and arguments. The difference between them is that .call() takes arguments as a list, while .apply() takes arguments as an array.
const lufthansa = { airline: 'Lufthansa', iataCode: 'LH', bookings: [], book(flightNum, name){ console.log(`${name} booked a seat on ${this.airline} flight ${this.iataCode} ${flightNum}`); this.bookings.push({flight: `${this.iataCode} ${flightNum}`, name}); }, }; lufthansa.book(4324,'James Bond'); lufthansa.book(5342,'Julie Bond'); lufthansa; const eurowings = { airline: 'Eurowings', iataCode: 'EW', bookings: [], }; // Now for the second flight eurowings, we want to use book method, but we shouldn't repeat the code written inside lufthansa object. // "this" depends on how fn is actually called. // In a regular fn call, this keyword points to undefined. // book stores the copy of book method defuned inside the lufthansa object. const book = lufthansa.book; // Doesn't work // book(23, 'Sara Williams'); // first argument is whatever we want 'this' object to point to. // We invoked the .call() which inturn invoked the book method with 'this' set to eurowings // after the first argument, all following arguments are for fn. book.call(eurowings, 23, 'Sara Williams'); eurowings; book.call(lufthansa, 735, 'Peter Parker'); lufthansa; const swiss = { airline: 'Swiss Airlines', iataCode: 'LX', bookings: [] } // call() book.call(swiss, 252, 'Joney James'); // apply() const flightData = [652, 'Mona Lisa']; book.apply(swiss, flightData); // Below call() syntax is equivalent to above .apply() syntax. It spreads out the arguments from the array. book.call(swiss, ...flightData);
The above is the detailed content of Functions. For more information, please follow other related articles on the PHP Chinese website!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
