Brooke  Giles

Brooke Giles

1560840121

An introduction to Higher-Ordaer Functions in JavaScript

In this tutorial we will learn what higher order functions are, how and why is it possible to use them in Javascript.

Use functions as data, and unlock some powerful patterns.

Higher-Order Functions

A function that accepts and/or returns another function is called a higher-order function.

It’s higher-order because instead of strings, numbers, or booleans, it goes higher to operate on functions. Pretty meta.

With functions in JavaScript, you can

  • Store them as variables
  • Use them in arrays
  • Assign them as object properties (methods)
  • Pass them as arguments
  • Return them from other functions

Like any other piece of data. That’s the key here.

Functions Operate on Data

Strings Are Data

sayHi = (name) => `Hi, ${name}!`;
result = sayHi('User');

console.log(result); // 'Hi, User!'

Numbers Are Data

double = (x) => x * 2;
result = double(4);

console.log(result); // 8

Booleans Are Data

getClearance = (allowed) => allowed ?
  'Access granted' :
  'Access denied';

result1 = getClearance(true);
result2 = getClearance(false);

console.log(result1); // 'Access granted'
console.log(result2); // 'Access denied'

Objects Are Data

getFirstName = (obj) => obj.firstName;
result = getFirstName({
  firstName: 'Yazeed'
});

console.log(result); // 'Yazeed'

Arrays Are Data

len = (array) => array.length;
result = len([1, 2, 3]);

console.log(result); // 3

These 5 types are first-class citizens in every mainstream language.

What makes them first-class? You can pass them around, store them in variables and arrays, use them as inputs for calculations. You can use them like any piece of data.

Functions Can Be Data Too

Functions as Arguments

isEven = (num) => num % 2 === 0;
result = [1, 2, 3, 4].filter(isEven);

console.log(result); // [2, 4]

See how filter uses isEven to decide what numbers to keep? isEven, a function, was a parameter to another function.

It’s called by filter for each number, and uses the returned value true or false to determine if a number should be kept or discarded.

Returning Functions

add = (x) => (y) => x + y;

add requires two parameters, but not all at once. It’s a function asking for just x, that returns a function asking for just y.

Again, this is only possible because JavaScript allows functions to be a return value — just like strings, numbers, booleans, etc.

You can still supply x and y immediately, if you wish, with a double invocation

result = add(10)(20);

console.log(result); // 30

Or x now and y later:

add10 = add(10);

result = add10(20);

console.log(result); // 30

Let’s rewind that last example. add10 is the result of calling add with one parameter. Try logging it in the console.

add10 is a function that takes a y and returns x + y. After you supply y, it hurries to calculate and return your end result.

Greater Reusability

Probably the greatest benefit of HOFs is greater reusability. Without them, JavaScript’s premiere Array methods — map, filter, and reduce — wouldn’t exist!

Here’s a list of users. We’re going to do some calculations with their information.

users = [{
  name: 'Yazeed',
  age: 25
}, {
  name: 'Sam',
  age: 30
}, {
  name: 'Bill',
  age: 20
}];

Map

Without higher-order functions, we’d always need loops to mimic map’s functionality.

getName = (user) => user.name;
usernames = [];

for (let i = 0; i < users.length; i++) {
  const name = getName(users[i]);

  usernames.push(name);
}

console.log(usernames);
// ["Yazeed", "Sam", "Bill"]

Or we could do this!

usernames = users.map(getName);

console.log(usernames);
// ["Yazeed", "Sam", "Bill"]

Filter

In a HOF-less world, we’d still need loops to recreate filter’s functionality too.

startsWithB = (string) => string
  .toLowerCase()
  .startsWith('b');

namesStartingWithB = [];

for (let i = 0; i < users.length; i++) {
  if (startsWithB(users[i].name)) {
    namesStartingWithB.push(users[i]);
  }
}

console.log(namesStartingWithB);
// [{ "name": "Bill", "age": 20 }]

Or we could do this!

namesStartingWithB = users
  .filter((user) => startsWithB(user.name));

console.log(namesStartingWithB);
// [{ "name": "Bill", "age": 20 }]

Reduce

Yup, reduce too… Can’t do much cool stuff without higher-order functions!! 😁

total = 0;

for (let i = 0; i < users.length; i++) {
  total += users[i].age;
}

console.log(total);
// 75

How’s this?

totalAge = users
  .reduce((total, user) => user.age + total, 0);

console.log(totalAge);
// 75

Summary

  • Store them as variables
  • Use them in arrays
  • Assign them as object properties (methods)
  • Pass them as arguments
  • Return them from other functions

Learn More

Introducing TensorFlow.js: Machine Learning in Javascript

5 ways to build real-time apps with JavaScript

Full Stack Developers: Everything You Need to Know

ES5 to ESNext — here’s every feature added to JavaScript since 2015

24 JavaScript Libraries for Creating Beautiful Charts

12 Concepts That Will Level Up Your JavaScript Skills

Vuejs 2 Authentication Tutorial

The Complete JavaScript Course 2019: Build Real Projects!

JavaScript Bootcamp - Build Real World Applications

JavaScript: Understanding the Weird Parts

Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

#javascript

What is GEEK

Buddha Community

An introduction to Higher-Ordaer Functions in JavaScript
Vincent Lab

Vincent Lab

1605017502

The Difference Between Regular Functions and Arrow Functions in JavaScript

Other then the syntactical differences. The main difference is the way the this keyword behaves? In an arrow function, the this keyword remains the same throughout the life-cycle of the function and is always bound to the value of this in the closest non-arrow parent function. Arrow functions can never be constructor functions so they can never be invoked with the new keyword. And they can never have duplicate named parameters like a regular function not using strict mode.

Here are a few code examples to show you some of the differences
this.name = "Bob";

const person = {
name: “Jon”,

<span style="color: #008000">// Regular function</span>
func1: <span style="color: #0000ff">function</span> () {
    console.log(<span style="color: #0000ff">this</span>);
},

<span style="color: #008000">// Arrow function</span>
func2: () =&gt; {
    console.log(<span style="color: #0000ff">this</span>);
}

}

person.func1(); // Call the Regular function
// Output: {name:“Jon”, func1:[Function: func1], func2:[Function: func2]}

person.func2(); // Call the Arrow function
// Output: {name:“Bob”}

The new keyword with an arrow function
const person = (name) => console.log("Your name is " + name);
const bob = new person("Bob");
// Uncaught TypeError: person is not a constructor

If you want to see a visual presentation on the differences, then you can see the video below:

#arrow functions #javascript #regular functions #arrow functions vs normal functions #difference between functions and arrow functions

Madyson  Reilly

Madyson Reilly

1601069940

Function Expression vs Function Declaration in JavaScript

Function Expression vs Function Declaration in JavaScript.

It was until during one of the JavaScript mock interviews did I came across the term function expression.

The question was: What is the difference between these two syntax?

function x(){

}

let x = function(){

}

I was clueless for a moment. After thinking a little, I could only come up with: the second syntax invokes an _anonymous _function and is assigned to a variable.

I was alien to the term hoisting.

In this article, we will acquaint ourselves with three simple terms: function declaration,_ function expression, _and hoisting.

What is function declaration?

Function declaration is also known as _function statement. _It contains the name of the function, parameters, and a return statement. **Naming the function **is what sets function declaration apart. Parameters and return statement is optional.

Image for post

Function Declaration

What is function expression?

Function expression also has a name, parameters, and return statement. All of which are optional. The important thing to bear in mind is: the function here is _assigned _to a JavaScript variable.

Image for post

Function Expression

#function-expression #function-declaration #functions-in-javascript #coding #javascript #express

Lowa Alice

Lowa Alice

1624410000

JavaScript Factory Functions

JavaScript factory functions made simple.

📺 The video in this post was made by Programming with Mosh
The origin of the article: https://www.youtube.com/watch?v=jpegXpQpb3o&list=PLTjRvDozrdlxEIuOBZkMAK5uiqp8rHUax&index=9
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#javascript #factory functions #functions #javascript factory functions

Higher-Order Functions Beginners Should Be Familiar With.

Higher-order functions are functions that operate on other functions, either by taking them as arguments or by returning them.

There are a lot more higher order functions than what will be covered in this article, but these are good ones to get you up and running as a beginner. These standard array methods are forEach() , filter() , map() and sort() .

  1. **forEach( ): **This is used when you want to operate on or interact with any element inside of an array. Basically works like the_ for loop._

N.B- I’d be using examples to illustrate each method so you can get a clearer picture, and also just printing to the console to keep the examples as simple and basic as possible.

Example: Lets say in an array of a group or friends, and we want to loop through that array and print to the console each element of that array.

Using a for loop ;

const friends = ['Toyin', 'Olumide', 'Fola', 'Tola'];

for ( let i=0; i < friends.length ; i++) {
  cosole.log (friends[i])
};

The action same as above can be achieved using theforEach() method as seen below;

const friends =  ['Toyin', 'Olumide', 'Fola', 'Tola'];

friends.forEach(function(name) {
  console.log(name)
};

What the forEach() method simply does is to take in a function as an argument and loop through each item in the array without using iteration[i].

This is really awesome when the ES6 arrow functions are used, our code is reduced to a single line that is clean and maintainable. As seen below:

const friends =  ['Toyin', 'Olumide', 'Fola', 'Tola'];

friends.forEach(name => console.log (name));

2. **_filter( ) : _**Just like the name implies, it is used to filter out elements of an array that do not meet the conditions set in the callback function passed as an argument. The callback function passed to the filter() method accepts 3 parameters: elementindex, and array , but most times only the element parameter is used.

**Example : **In an array showing a group of friends and their ages, lets say we want to print to the console the friends that can drink assuming the age limit for drinking is 18. Using a for loop without high order functions;

const friends = [
  {name : 'Toyin', age: 24},
  {name : 'Olumide', age: 14},
  {name : 'Fola', age: 12},
  {name : 'David', age: 42}
];
for ( let i=0 ; i<friends.length ; i++) {
   if (friends[i].age > 18) {
    console.log(`${friends[i].name} can drink`);
 }
};

Now using the filter() method :

const friends = [
  {name : 'Toyin', age: 24},
  {name : 'Olumide', age: 14},
  {name : 'Fola', age: 12},
  {name : 'David', age: 42}
];
friends.filter (function (friend) {
  if (friend.age > 18){
   return true;
 } 
});

#functional-programming #beginners-guide #javascript #higher-order-function #es5-vs-es6 #function

Introduction With Basic JavaScript

The world’s most misunderstood programming language is JavaScript but JavaScript is now used by an incredible number of high-profile applications. So, it’s an important skill for any web or mobile developer to enrich the deeper knowledge in it.

Unlike most programming languages, the JavaScript language has no concept of input or output. It is designed to run as a scripting language in a host environment, and it is up to the host environment to provide mechanisms for communicating with the outside world.

Its syntax is based on the Java and C languages — many structures from those languages apply to JavaScript as well. JavaScript supports object-oriented programming with object prototypes, instead of classes. JavaScript also supports functional programming — because they are objects, functions may be stored in variables and passed around like any other object.

Let’s start off by looking at the building blocks of any language: the types. JavaScript programs manipulate values, and those values all belong to a type. JavaScript’s types are:

· Number

· String

· Boolean

· Function

· Object

· Symbol

and undefined and null, which are … slightly odd. And Array, which is a special kind of object. Date and RegExp, which are objects that you get for free. And to be technically accurate, functions are just a special type of object. So the type of diagram looks like this:

#beginner-javascript #javascript #javascript-introduction #javascript-fundamental #basic-javascritp