Open zhu-ting opened 6 years ago
Imperative Versus Declarative.
var string = "This is the midday show with Cheryl Waters"; var urlFriendly = "";
for (var i=0; i<string.length; i++) { if (string[i] === " ") {
urlFriendly += "-";
}else{
urlFriendly += string[i];
}
}
console.log(urlFriendly);
const string = "This is the mid day show with Cheryl Waters"
const urlFriendly = string.replace(/ /g, "-")
console.log(urlFriendly)
Let’s consider the task of building a document object model, or DOM. An imperative approach would be concerned with how the DOM is constructed:
var target = document.getElementById('target');
var wrapper = document.createElement('div');
var headline = document.createElement('h1');
wrapper.id = "welcome";
headline.innerText = "Hello World";
wrapper.appendChild(headline);
target.appendChild(wrapper);
let’s take a look at how we can construct a DOM declaratively using a React component:
const { render } = ReactDOM
const Welcome = () => (
<div id="welcome">
<h1>Hello World</h1>
</div>
)
render(
<Welcome />,
document.getElementById('target')
)
React is declarative. Here, the Welcome component describes the DOM that should be rendered. The render function uses the instructions declared in the component to build the DOM, abstracting away the details of how the DOM is to be rendered. We can clearly see that we want to render our Welcome component into the element with the ID of 'target'.
const ages = [21,18,42,40,64,63,34];
const max = ages.reduce(
(max, value) => (value > max) ? value : max, 0
)
console.log(max)
map and reduce are the main weapons of any functional programmer, and JavaScript is no exception. If you want to be a proficient JavaScript engineer, then you must master these functions. The ability to create one dataset from another is a required skill and is useful for any type of programming paradigm.
Array.map, Array.filter, and Array.reduce
all take functions as arguments. They are higher-order functions.
If you’ve mapped or reduced an array, then you’re already on your way to becoming a functional programmer. React, Flux, and Redux all fit within the functional JavaScript paradigm. Understanding the basic concepts of functional programming will elevate your knowledge of structuring React applications.
Functions can be sent to functions as arguments or returned from functions as results. More complex functions, called higher-order functions, can manipulate functions and use them as either arguments or results or both.
We are going to go over some of the key concepts of functional pro‐ gramming, and we’ll cover how to implement functional techniques with JavaScript.
What It Means to Be Functional
JavaScript supports functional programming because JavaScript functions are first- class citizens. This means that functions can do the same things that variables can do. ES6 adds language improvements that can beef up your functional programming techniques, including arrow functions, promises, and the spread operator