Functions

Sep 05, 2024 pm 07:00 PM

Functions

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
}
*/ 
Copy after login

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);
Copy after login

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');
Copy after login

"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);


Copy after login

The above is the detailed content of Functions. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles