How to Setup Tailwind with PurgeCSS and PostCSS? | Tailwind Installation and Usage

How to Setup Tailwind with PurgeCSS and PostCSS

In this tutorial, we will learn how to use Tailwind with any kind of project. Know how to set up Tailwind with PurgeCSS and PostCSS, how to create a Tailwind File, what do PurgeCSS and PostCSS mean. This tutorial makes you familiar with the concept of How to Remove Unused CSS using the PurgeCSS.

Tailwind Installation

We have to install tailwind via npm or yarn:

npm init -y (if its a barebone project, -y stands for yes)
npm install tailwindcss

Create the Configuration File

We have to create a configuration for a tailwind to use:

npx tailwind init

This will create a file named tailwind.config.js in the root location of our project folder.

PostCSS Config Tailwind

Tailwind needs PostCSS (PostCSS is a software development tool that uses JavaScript-based plugins to automate routine CSS operations) and autoprefixer (Autoprefixer will use the data based on current browser popularity and property support to apply prefixes for you) to work. So we need to apply that in the postcss.config.js file:

module.exports = {
  plugins: [
    require('tailwindcss'),
    require('autoprefixer')
  ]
}

Note: If the postcss.config.js doesn’t exist, we have to create one.

We need to install PostCSS and autoprefixer from npm too:

npm install autoprefixer
npm install -g postcss-cli (-g stands for global)

How to Create the Tailwind CSS File?

Now, we will create a CSS file (style.css) and add these lines at the top:

@tailwind base;
@tailwind components;
@tailwind utilities;

Create the build command

We need to specify a build command that will help us to generate the actual CSS file after compiling with PostCSS and autoprefixer. For that, we need to add the command to the package.json file at scripts like:

"scripts": {
  "build:css": "postcss src/tailwind.css -o static/dist/tailwind.css"
}

Build Tailwind

For building the final CSS file we need to run the command npm run build in the root of the project folder.

The resulting file is in static/dist/tailwind.css

Automatically regenerate the CSS upon file changes

There is a great npm package that will compile our CSS in real-time without running the build command every time after edits. For that we need to install the watch using the command:

npm install watch

Then we need to edit the package.json file at scripts like:

"scripts": {
  "build:css": "postcss src/tailwind.css -o static/dist/tailwind.css",
  "watch": "watch 'npm run build:css' ./layouts"
}

Now for running we simply need to execute the command npm run watch and it’s all good.

Trim the File Size

If we check the final CSS file i.e after building, we can see that it’s huge in size. That large file is never appropriate for web pages. For that, we can actually trim the file to make it smaller than the original.

We need to install two more npm packages:

npm install cssnano
npm install @fullhuman/postcss-purgecss

What is PurgeCSS?

PurgeCSS is a development tool used for removing the unused CSS in a Project. It is the default library to control the Tailwind CSS Bundle Sizes. It removes unused styles and optimizes CSS Build Sizes.

How to Remove Unused Classes from Tailwind with PurgeCSS?

To remove unused CSS we use the following code. Then we add this to our PostCSS configuration file postcss.config.js:

const purgecss = require('@fullhuman/postcss-purgecss')
const cssnano = require('cssnano')

module.exports = {
  plugins: [
    require('tailwindcss'),
    require('autoprefixer'),
    cssnano({
      preset: 'default'
    }),
    purgecss({
      content: ['./layouts/**/*.html', './src/**/*.vue', './src/**/*.jsx'],
      defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || []
    })
  ]
}

In development, avoid too much processing

In development, we can use this just to add prefixes and remove comments. We need to edit the postcss.config.js like:

const purgecss = require('@fullhuman/postcss-purgecss')
const cssnano = require('cssnano')

module.exports = {
  plugins: [
    require('tailwindcss'),
    process.env.NODE_ENV === 'production' ? require('autoprefixer') : null,
    process.env.NODE_ENV === 'production'
      ? cssnano({ preset: 'default' })
      : null,
    purgecss({
      content: ['./layouts/**/*.html', './src/**/*.vue', './src/**/*.jsx'],
      defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || []
    })
  ]
}

 

The JavaScript Event Loop | What is an Event loop in JavaScript? | How it works with Example

The JavaScript Event Loop

Event Loop in JavaScript

The Event Loop is one of the most important aspects to understand about JavaScript.

This post aims to explain the inner details of how JavaScript works with a single thread, and how it handles asynchronous functions.

Your JavaScript code runs single-threaded. There is just one thing happening at a time.

This is a limitation that’s actually very helpful, as it simplifies a lot how you program without worrying about concurrency issues.

You just need to pay attention to how you write your code and avoid anything that could block the thread, like synchronous network calls or infinite loops.

Do Check: 

In general, in most browsers there is an event loop for every browser tab, to make every process isolated and avoid a web page with infinite loops or heavy processing to block your entire browser.

The environment manages multiple concurrent event loops, to handle API calls for example. Web Workers run in their own event loop as well.

You mainly need to be concerned that your code will run on a single event loop, and write code with this thing in mind to avoid blocking it.

This tutorial of JavaScript Event Loop Include the following:

Blocking the event loop

Any JavaScript code that takes too long to return back control to the event loop will block the execution of any JavaScript code in the page, even block the UI thread, and the user cannot click around, scroll the page, and so on.

Almost all the I/O primitives in JavaScript are non-blocking. Network requests, Node.js filesystem operations, and so on. Blocking is the exception, which is why JavaScript is based so much on callbacks, and more recently on promises and async/await.

The call stack

The call stack is a LIFO queue (Last In, First Out).

The event loop continuously checks the call stack to see if there’s any function that needs to run.

While doing, it adds any function call it finds to the call stack and executes each one in order.

You know the error stack trace you might be familiar with, in the debugger or in the browser console? The browser looks up the function names in the call stack to inform you which function originates the current call:

A simple event loop explanation

An example to explain it through,

Consider the previous code, but this time not throwing any DOMexception.

const bar = () => {
  console.log("bar")
};

const baz = () => console.log("baz")

const foo = () => {
  console.log("foo")
  bar()
  baz()
};
foo()

The Output would be:

foo
bar
baz

When this code runs, first, foo() is called. Inside foo() we first call, bar() then we call baz().

At this point the call stack looks like this:

The event loop on every iteration looks if there’s something in the call stack, and executes it until stack is empty.

Queuing function execution

The above example looks normal, there’s nothing special about it: JavaScript finds things to execute, runs them in order.

Let’s see how to defer a function until the stack is clear.

The use case of setTimeout(() => {}), 0) is to call a function, but execute it once every other function in the code has been executed.

Take this example:

const bar = () => console.log('bar')

const baz = () => console.log('baz')

const foo = () => {
  console.log('foo')
  setTimeout(bar, 0)
  baz()
}

foo()

Result:

When setTimeout() is called, the Browser or Node.js start the timer. Once the timer expires, in this case immediately as we put 0 as the timeout, the callback function is put in the Message Queue.

The Message Queue is also where user-initiated events like click or keyboard events, or fetch responses are queued before your code has the opportunity to react to them. Or also DOM Events like onLoad.

The loop gives priority to the call stack, and it first processes everything it finds in the call stack, and once there’s nothing in there, it goes to pick up things in the message queue.

We don’t have to wait for functions likesetTimeout, fetch or other things to do their own work, because they are provided by the browser, and they live on their own threads. For example, if you fix thesetTimeouttimeout to 2 seconds, you don’t have to wait 2 seconds – then wait happens elsewhere.

ES6 Job Queue

ECMA introduced the concept of the Job Queue, which is used by Promises (also introduced in ES6/ES2015). It’s a way to execute the result of an async function as soon as possible, rather than being put at the end of the call stack.

Promises that resolve before the current function ends will be executed right after the current function.

I find nice the analogy of a rollercoaster ride at an amusement park: the message queue puts you at the back of the queue, behind all the other people, where you will have to wait for your turn, while the job queue is the Fastpass ticket that lets you take another ride right after you finished the previous one.

Example:

const bar = () => console.log('bar')

const baz = () => console.log('baz')

const foo = () => {
  console.log('foo')
  setTimeout(bar, 0)
  new Promise((resolve, reject) =>
    resolve('should be right after baz, before bar')
  ).then(resolve => console.log(resolve))
  baz()
}

foo()

Output:

The Object is() method | JavaScript Object is() method Syntax, Description, Parameters & Examples

The Object is() method

Javascript Object is() Method with Example is discussed here elaborately for better understanding to beginners and experienced programmers. Want to gain more knowledge about the javascript object.is() method? Look at the below sections by using the direct links available here.

JavaScript Object is() Method

This method was introduced in ES2015. Mainly, it intends to help to compare values. TheObject.is()method is used to decide whether two values are the same or not. Two values can be the same if they hold one of the following properties:

  • In case both the values are undefined.
  • If both the values are null.
  • In case both the values are true or false.
  • If both the strings are of the same length with the same characters and in the same order.
  • In case both the values are numbers and both are “+0”.
  • If both the values are numbers and both are “-0”.
  • In case both the values are numbers and both are “NaN” or both non-zero and both not NaN and both have the same value.

Syntax of Object is() Javascript Method:

Object.is(value1, value2); 
//Object.is(a, b);

The result is always false unless:

  • a and b are the same exact object
  • a and b are equal strings (strings are equal when composed by the same characters, in the same order)
  • a and b are equal numbers (numbers are equal when their value is equal)
  • a and b are both undefined, both null, both NaN, both true or both false

0 and -0 are different values in JavaScript, so pay attention in this special case (convert all to +0 using the + unary operator before comparing, for example).

Also Check:

Parameters Used

  • value1: The first value to compare.
  • value2: The second value to compare.

Return Value

Javascript Object.is() method takes two arguments which are the values to be compared and declares a boolean indicating whether the two arguments are the same or not.

Browser Support

Chrome 30
Edge Yes
Firefox 22
Opera Yes

Example Using Object.is() Method

// Case 1: Evaluation result is the same as using ===
Object.is(25, 25);                // true
Object.is('foo', 'foo');          // true
Object.is('foo', 'bar');          // false
Object.is(null, null);            // true
Object.is(undefined, undefined);  // true
Object.is(window, window);        // true
Object.is([], []);                // false
var foo = { a: 1 };
var bar = { a: 1 };
Object.is(foo, foo);              // true
Object.is(foo, bar);              // false

// Case 2: Signed zero
Object.is(0, -0);                 // false
Object.is(+0, -0);                // false
Object.is(-0, -0);                // true
Object.is(0n, -0n);               // true

// Case 3: NaN
Object.is(NaN, 0/0);              // true
Object.is(NaN, Number.NaN)        // true

Polyfill

if (!Object.is) {
  Object.defineProperty(Object, "is", {
    value: function (x, y) {
      // SameValue algorithm
      if (x === y) {
        // return true if x and y are not 0, OR
        // if x and y are both 0 of the same sign.
        // This checks for cases 1 and 2 above.
        return x !== 0 || 1 / x === 1 / y;
      } else {
        // return true if both x AND y evaluate to NaN.
        // The only possibility for a variable to not be strictly equal to itself
        // is when that variable evaluates to NaN (example: Number.NaN, 0/0, NaN).
        // This checks for case 3.
        return x !== x && y !== y;
      }
    }
  });
}

How to list all methods of an object in JavaScript | Javascript get methods of Object

How to list all methods of an object in JavaScript

Objects in JavaScript are combinations of key/value pairs. The values can be made up of properties and methods and may include all other JavaScript data types, like strings, numbers, and Booleans. All javascript objects descend from the parent Object constructor.

An Object has many helpful built-in methods we can utilize and access to start working with individual objects straightforward. In this tutorial, you will learn How to list all methods of an object in JavaScript with examples from the below direct links.

JavaScript Object Methods – Example

var person = {
  firstName: "John",
  lastName : "Doe",
  id       : 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};

JavaScript Methods

JavaScript Methods are operations that can be implemented on objects. The definition of a JavaScript method is a property containing a function.

Property Value
firstName John
lastName Doe
age 50
eyeColor blue
fullName function() {return this.firstName + ” ” + this.lastName;}

Do Check:

Accessing Object Methods of JavaScript

Here is the syntax to access the object method:

objectName.methodName()

List all Methods of an Object in JavaScript

We can use theObject.getOwnPropertyNames()function to get all the property names linked to an object.

Then we can filter the resulting array, to only include that property name if it’s a function.

We determine if it’s a function by usingtypeofon it.

For example here is how we might create a utility function to do what we need:

getMethods = (obj) => Object.getOwnPropertyNames(obj).filter(item => typeof obj[item] === 'function')

This lists only the methods defined on that specific object, not any method defined in its prototype chain.

To do that we must take a slightly different route. We must first iterate the prototype chain and list all the properties in an array. Then we check if each single property is a function.

An easy way to make sure we don’t duplicate methods as we navigate the prototype chain (like constructor which is always present), we use a Set data structure that makes sure values are unique:

const getMethods = (obj) => {
  let properties = new Set()
  let currentObj = obj
  do {
    Object.getOwnPropertyNames(currentObj).map(item => properties.add(item))
  } while ((currentObj = Object.getPrototypeOf(currentObj)))
  return [...properties.keys()].filter(item => typeof obj[item] === 'function')
}

Example usage:

getMethods("")
getMethods(new String('test'))
getMethods({})
getMethods(Date.prototype)

Example on Get all methods of any object JavaScript

const returnMethods = (obj = {}) => {
   const members = Object.getOwnPropertyNames(obj);
   const methods = members.filter(el => {
      return typeof obj[el] === 'function';
   })
   return methods;
};
console.log(returnMethods(Array.prototype));

Output:

Here is the output in the console:

[
'constructor', 'concat', 'copyWithin',
'fill', 'find', 'findIndex', 'lastIndexOf', 'pop', 'push',
'reverse', 'shift', 'unshift', 'slice', 'sort', 'splice',
'includes', 'indexOf', 'join',
'keys', 'entries', 'values',
'forEach', 'filter', 'flat',
'flatMap', 'map', 'every',
'some', 'reduce', 'reduceRight',
'toLocaleString', 'toString'
]

JavaScript, how to export a function | Export function in Javascript with Example Programs

JavaScript, how to export a function

In this tutorial, you will be learning Javascript, how to export a function, Syntax, Example codes using Export functions. The exportstatement is utilized when building JavaScript modules to export live bindings to functions, objects, or primitive values from the module so they can be done by other programs with the import statement. Export and import functions in Javascript directives have different syntax variants.

JavaScript Export Function

In JavaScript, we can separate a program into separate files. How do we make a function we define in a file available to other files?

You typically write a function, like below

function sum(a, b) {
  return a + b
}

Export Syntax

We have two types of exports in Javascript:

  1. Named Exports (Zero or more exports per module)
  2. Default Exports (One per module)

1. Named Export Syntax

// Export list
export { name1, name2, …, nameN };

2. Default Export Syntax

Also, you can make it possible for any other file with the help of this javascript export function syntax

 export default sum

The above syntax code defines the default export function.

Also Check:

Import Function Syntax

The files that need the function exported will import it using this syntax

import sum from 'myfile'

Sample Code Using Named Exports

// export features declared earlier
export { myFunction, myVariable };

// export individual features (can export var, let,
// const, function, class)
export let myVariable = Math.sqrt(2);
export function myFunction() { ... };

Sample Code using Default Exports

// module "my-module.js"

export default function cube(x) {
  return x * x * x;
}

Export apart from declarations

Moreover, we can place export separately.

Here we first declare, and then export:

// say.js
function sayHi(user) {
  alert(`Hello, ${user}!`);
}

function sayBye(user) {
  alert(`Bye, ${user}!`);
}

export {sayHi, sayBye}; // a list of exported variables

Or, technically we could placeexport above functions as well.

Export before declarations

We can identify any declaration as exported by puttingexportbefore it, be it a variable, function, or a class.

For example, below all exports are valid:

// export an array
export let months = ['Jan', 'Feb', 'Mar','Apr', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

// export a constant
export const MODULES_BECAME_STANDARD_YEAR = 2015;

// export a class
export class User {
  constructor(name) {
    this.name = name;
  }
}

The Object getOwnPropertyDescriptors() method | JavaScript Object.getOwnPropertyDescriptors() Method Syntax with Example

The Object getOwnPropertyDescriptors() method

Object.getOwnPropertyDescriptors(obj) accepts an object, and returns a new object that provides a list of the descriptors. Also, this method states all own (non-inherited) properties descriptors of an object. Stay continue with this tutorial and get complete details about JavaScript Object.getOwnPropertyDescriptors() Method, declaration or syntax, parameters, description, example using getOwnPropertyDescriptors().

JavaScript Object.getOwnPropertyDescriptors() Method

The Object.getOwnPropertyDescriptors() method returns all own property descriptors of a given object. The getOwnPropertyDescriptors() method ignores symbolic properties so this is the biggest difference between getOwnPropertyDescriptors() and getOwnPropertyDescriptor() method.

Do Check: 

Syntax

The syntax of the JavaScript getOwnPropertyDescriptors() method is:

Object.getOwnPropertyDescriptors(obj)

The getOwnPropertyDescriptors()method, signifying a static method, is described applying the Object class name.

getOwnPropertyDescriptors() Parameters

ThegetOwnPropertyDescriptors()method needs in:

obj – It is the object for which to get all own property descriptors.

Return value from getOwnPropertyDescriptors()

JavaScript getOwnPropertyDescriptors() method returns an object containing all own property descriptors of an object. Also, it may return an empty object in case there are no properties.

Browser Support:

Firefox 50
Edge 15
Chrome 54
Opera 41

Example using JavaScript getOwnPropertyDescriptors() Method

let obj = {
  x: 10,
  get number() {
    return this.x;
  },
};

let value = Object.getOwnPropertyDescriptors(obj);
console.log(value);

// getOwnPropertyDescriptors() can be used for shallow clone
let cloneObj = Object.create(
  Object.getPrototypeOf(obj),
  Object.getOwnPropertyDescriptors(obj)
);

console.log(cloneObj); // { x: 10, number: [Getter] }

Output:

{
  x: { value: 10, writable: true, enumerable: true, configurable: true },
  number: {
    get: [Function: get number],
    set: undefined,
    enumerable: true,
    configurable: true
  }
}
{ x: 10, number: [Getter] }

Other Example on getOwnPropertyDescriptors() in JavaScript

const dog = {}
Object.defineProperties(dog, {
  breed: {
    value: 'Siberian Husky'
  }
})
Object.getOwnPropertyDescriptors(dog)
/*
{
  breed: {
    value: 'Siberian Husky',
    writable: false,
    enumerable: false,
    configurable: false
  }
}
*/

Use Case for Object.getOwnPropertyDescriptors() – Copying Properties into an object 

There is one use case that makes this property very useful. ES2015 gave us Object.assign(), which copies all enumerable own properties from one or more objects, and returns a new object. However, there is a problem with that, because it does not correctly copy properties with non-default attributes.

If an object for example has just a setter, it’s not correctly copied to a new object, using Object.assign(). For example with this object:

const person1 = {
  set name(newName) {
    console.log(newName)
  }
}

This copy attempt won’t work:

const person2 = {}
Object.assign(person2, person1)

But this will work and copy over the setter correctly:

const person3 = {}
Object.defineProperties(person3, Object.getOwnPropertyDescriptors(person1))

As you can see with a console test:

person1.name = 'x'
"x"
person2.name = 'x'
person3.name = 'x'
"x"

person2 misses the setter, it was not copied over.

The same limitation goes for shallow cloning objects with Object.create().

The JavaScript Global Object | What is a Global Object in JavaScript? | JavaScript Global Variables, Properties, Functions

The JavaScript Global Object

JavaScript implements a global object which holds a kit of properties, functions, and objects that are accessed globally, without a namespace. Want to learn more about the JavaScript Global Object Variables, Functions & Properties? Then, this tutorial is the perfect one for all beginners and experienced programmers. So, dive into this page and directly get into the topic using the direct links available below.

What is a Global Object in JavaScript?

Objects in JavaScript are distinct from the Global Object. Applying the new operator, you cannot build global objects. When the scripting engine is initialized then only it comes into existence. Once the initialization is completed, the functions and constants are ready to use while coding in JavaScript.

A global object enables you to perform the below conditions −

  • It provides access to built-in functions and values. Call alert immediately like the below code snippet, with window −
alert("Demo Text");
// or
window.alert("Demo Text");
  • Even, it also provides access to global function declarations and var variables in JavaScript. Look at the below code –
<script>
         var str = "Demo Text";
         // using window
         alert( window.str );
</script>

Some of the JavaScript Global objects are:

  • Array
  • Boolean
  • Date
  • Function
  • JSON
  • Math
  • Number
  • Object
  • RegExp
  • String
  • Symbol

and errors:

  • Error
  • EvalError
  • RangeError
  • ReferenceError
  • SyntaxError
  • TypeError
  • URIError

Window object in the Browser

In the Browser, the window object is the Global Object. Any JavaScript Global Variables or Functions can be accessed as properties of thewindowobject while programming.

Do Refer:

JavaScript Global Properties

The properties of JavaScript Global Object are:

  • Infinity
  • NaN
  • undefined

Infinity

Infinity in JavaScript is a value that represents infinity.

Positive infinity. To get negative infinity, use the  operator: -Infinity.

Those are equivalent to Number.POSITIVE_INFINITY and Number.NEGATIVE_INFINITY.

Adding any number to Infinity, or multiplying Infinity for any number, still gives Infinity.

NaN

The global NaN value is an acronym for Not a Number. It’s returned by operations such as zero divided by zero, invalid parseInt() operations, or other operations.

parseInt()    //NaN
parseInt('a') //NaN
0/0           //NaN

A special thing to consider is that a NaN value is never equal to another NaN value. You must use the isNaN() global function to check if a value evaluates to NaN:

NaN === NaN //false
0/0 === NaN //false
isNaN(0/0)  //true

undefined

The global undefined property holds the primitive value undefined.

Running a function that does not specify a return value returns undefined:

const testFunc = () => {}
testFunc() //undefined

Unlike NaN, we can compare an undefined value with undefined, and get true:

undefined === undefined

It’s common to use the typeof operator to determine if a variable is undefined:

if (typeof cat === 'undefined') {

}

JavaScript Global Functions

The functions are:

  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • eval()
  • isFinite()
  • isNaN()
  • parseFloat()
  • parseInt()

decodeURI()

Performs the opposite operation of encodeURI()

decodeURIComponent()

Performs the opposite operation of encodeURIComponent()

encodeURI()

This function is used to encode a complete URL. It does encode all characters to their HTML entities except the ones that have a special meaning in a URI structure, including all characters and digits, plus those special characters:

~!@#$&*()=:/,;?+-_.

Example:

encodeURI("http://google.com/good morning/")
//"http://google.com/good%20morning/"

encodeURIComponent()

Similar to encodeURI()encodeURIComponent() is meant to have a different job.

Instead of being used to encode an entire URI, it encodes a portion of a URI.

It does encode all characters to their HTML entities except the ones that have a special meaning in a URI structure, including all characters and digits, plus those special characters:

-_.!~*'()

Example:

encodeURIComponent("http://www.example.org/a file with spaces.html")
// "http%3A%2F%2Fwww.example.org%2Fa%20file%20with%20spaces.html"

eval()

This is a special function that takes a string that contains JavaScript code and evaluates/runs it.

isFinite()

Returns true if the value passed as parameter is finite.

isFinite(1)                        //true
isFinite(Number.POSITIVE_INFINITY) //false
isFinite(Infinity)                 //false

isNaN()

Returns true if the value passed as parameter evaluates to NaN.

isNaN(NaN)        //true
isNaN(Number.NaN) //true
isNaN('x')        //true
isNaN(2)          //false
isNaN(undefined)  //true

This function is very useful because a NaN value is never equal to another NaN value. You must use the isNaN() global function to check if a value evaluates to NaN:

0/0 === NaN //false
isNaN(0/0)  //true

parseFloat()

Like parseInt()parseFloat() is used to convert a string value into a number, but retains the decimal part:

parseFloat('10.000', 10) //10     
parseFloat('10.20', 10)  //10.2   
parseFloat('10.81', 10)  //10.81

parseInt()

This function is used to convert a string value into a number.

Another good solution for integers is to call the parseInt() function:

const count = parseInt('1234', 10) //1234

Don’t forget the second parameter, which is the radix, always 10 for decimal numbers, or the conversion might try to guess the radix and give unexpected results.

parseInt() tries to get a number from a string that does not only contain a number:

parseInt('10 lions', 10) //10

but if the string does not start with a number, you’ll get NaN (Not a Number):

parseInt("I'm 10", 10) //NaN

Also, just like Number, it’s not reliable with separators between the digits:

parseInt('10.20', 10)  //10 
parseInt('10.81', 10)  //10

Write JavaScript loops using map, filter, reduce and find | How to use Map, reduce, and filter in Javascript?

Write JavaScript loops using map, filter, reduce and find

In JavaScript, Map, reduce, and filter is considered array methods. Individually one will iterate over an array and make a transformation or computation. Also, each will return a new array on the basis of the result of the function. In this tutorial, our expert programming team discussed in-depth knowledge on how to write JavaScript Loops using map(), filter(), reduce(), and find():

JavaScript Loops

Loops are generally used, in any programming language, to perform operations on arrays: given an array, you can iterate over its elements and perform a calculation.

map, filter, reduce, find

Those are 3 really powerful array functions:

  • map returns an array with the same length.
  • filter as the name implies, it returns an array with fewer items than the original array.
  • reduce returns a single value (or object).
  • find returns the first items in an array that satisfies a condition.

mapfilter and reduce were introduced in ES5, so you can safely use them as implemented in every browser for years.

find was introduced in ES6/ES2015.

Also Check:

Execute something on every element with a map

A loop would look like this:

const doSomething = (item) => {
  //...
  return item
}
const items = ['a', 'b', 'c']
items.forEach((item) => {
  doSomething(item)
})

With a declarative approach, you tell JavaScript to perform something on every element using:

const items = ['a', 'b', 'c']
const newItemsArray = items.map((item) => doSomething(item))

This generates a new array, without editing the original one (what we call immutability).

Finding a single element in the array

Sometimes you need to look for a specific item in the array and return it.

This is how you would do so with a loop:

const items = [
  { name: 'a', content: { /* ... */ }},
  { name: 'b', content: { /* ... */ }},
  { name: 'c', content: { /* ... */ }}
]
for (const item of items) {
  if (item.name === 'b') {
    return item
  }
}

Here is the non-loop version, using find() (ES6+):

const b = items.find((item) => item.name === 'b')

Here is the same functionality using filter() (ES5+):

const b = items.filter((item) => item.name === 'b').shift()

Note: shift() mutates the array, but the array it mutates is the one returned by filter(), not the original array. If this sounds unacceptable, you can check if the array is not empty and get the first item using b[0].

filter() and reduce() will iterate over all the array items, while find() will be faster.

Iterate over an array to count the property of each item

Use reduce() to get a single value out of an array. For example sum the items content.value property:

const items = [
  { name: 'A', content: { value: 5 }},
  { name: 'B', content: { value: 6 }},
  { name: 'C', content: { value: 7 }}
]

using a loop:

let count = 0
for (const item of items) {
  count += item.content.value
}

can be syntax as

const count = items.reduce((result, { content: { value } }) => result + value, 0)

The String slice() method in JavaScript | Definition, Syntax, How it works, Examples of JavaScript String slice() method

JavaScript String slice() method

In this ultimate tutorial, we have discussed complete details about the JavaScript String slice() method like definition, syntax, how to use the string slice() method to extract a substring from a string with examples.

JavaScript String slice() method – Definition

Return a new string from the part of the string included between the begin and end positions.

The original string is not mutated.

end is optional.

"This is my work".slice(5)
//"is my work"
"This is my work".slice(5,10)
//"is my"

If you set a negative first parameter, the start index starts from the end, and the second parameter must be negative as well, always counting from the end:

"This is my work".slice(-4)
//"work"
"This is my work".slice(-4,-1)
//"wor"

String.prototype.slice() Syntax

slice(beginIndex)
slice(beginIndex, endIndex)

Parameters Included in String Slice() Method

1. beginIndex: 

The zero-based index whereat to start extraction. In the case of negative, it is treated as str.length + beginIndex. (For instance, if beginIndexis -2, it is interpreted as str.length – 2.) If beginIndex is not a numeral after Number (beginIndex), it is considered as 0. In case beginIndexis greater than or equal to the str.length, an empty string is returned.

2. endIndex (Optional):

The zero-based index before which to end extraction. The character at this index wouldn’t be involved.

If endIndex is excluded or undefined, or greater than str.length, slice() extracts to the edge of the string. If negative, it is handled as str.length + endIndex. (For instance, if endIndex is -5, it is treated as str.length – 5.) If it is not undefined, and the Number(endIndex) is not positive, an empty string is returned.

If endIndex is defined, then beginIndex should be smaller than endIndex otherwise, an empty string is returned. (For example, slice(-3, 0), slice(-1, -3), or slice(3, 1) returns "".)

Return Values

It returns a part or a slice of the furnished input string.

Do Check:

Examples on String slice() method in JavaScript

In this section, you will find plenty of example programs to learn how to create and use the javascript string slice() method in various conditions:

1. Using slice() to create a new string

The following examples utilize the string slice() method to create a new string.

let str1 = 'The morning is upon us.', // the length of str1 is 23.
    str2 = str1.slice(1, 8),
    str3 = str1.slice(4, -2),
    str4 = str1.slice(12),
    str5 = str1.slice(30);
console.log(str2)  // OUTPUT: he morn
console.log(str3)  // OUTPUT: morning is upon u
console.log(str4)  // OUTPUT: is upon us.
console.log(str5)  // OUTPUT: ""

2. Using slice() with negative indexes

The following example uses slice() with negative indexes.

<script> 
var str = "Javatpoint"; 
document.writeln(str.slice(-5)); 
</script>

Output:

point

How to uppercase the first letter of a string in JavaScript? | JavaScript Program to Convert the First Letter of a String into UpperCase

How to Uppercase the first letter of a String in JavaScript

In this tutorial, passionate learners can grab the opportunity to study and understand how to write a JavaScript program that converts the first letter of a string into uppercase. Here, we have used two approaches with neat examples and explained How to Capitalize the First Letter of a String in JavaScript. So, check out the below links directly and learn thoroughly.

How to Uppercase the first letter of a string in JavaScript?

JavaScript offers several methods to capitalize a string to make the first character uppercase. Discover what are the various ways, and also find out which one is best for using with plain JavaScript.

The most common operation with strings is to make the string capitalized: uppercase its first letter, and leave the rest of the string as-is.

The best way to do this is by a combination of two functions. One uppercases the first letter, and the second slices the string and returns it starting from the second character.

const name = "flavio";
const nameCapitalized = name.charAt(0).toUpperCase() + name.slice(1);
console.log(nameCapitalized);

You can extract that to a function, which also checks if the passed parameter is a string, and returns an empty string if not.

const capitalize = (s) => {
  if (typeof s !== 'string') return ''
  return s.charAt(0).toUpperCase() + s.slice(1)
}

capitalize('flavio') //'Flavio'
capitalize('f')      //'F'
capitalize(0)        //''
capitalize({})       //''

Instead of using s.charAt(0) you could also use string indexing (not supported in older IE versions): s[0].

Some solutions online advocate for adding the function to the String prototype.

String.prototype.capitalize = function() {
  return this.charAt(0).toUpperCase() + this.slice(1)
}

(we use a regular function to make use of this -arrow functions would fail in this case, as this in arrow functions does not reference the current object)

This solution is not ideal, because editing the prototype is not generally recommended, and it’s a much slower solution than having an independent function.

Don’t forget that if you just want to capitalize for presentational purposes on a Web Page, CSS might be a better solution, just add a capitalize class to your HTML paragraph and use:

p.capitalize {
  text-transform: capitalize;
}

Do Refer:

Example 1: Convert the First letter to UpperCase

Let’s see the below program on converting the first letter to uppercase. Here, the user is prompted to enter a string and that string is transferred into the capitalizeFirstLetter() function.

  • First and foremost, the string’s first character is extracted performing charAt() method. Here, str.charAt(0); gives p.
  • The toUpperCase() method changes the string to uppercase. Here, str.charAt(0).toUpperCase(); gives P.
  • The rest of the string is return by the slice() method. Here, str.slice(1); gives Programming
  • Finally, these two values are concatenated using the + operator.
// program to convert first letter of a string to uppercase
function capitalizeFirstLetter(str) {

    // converting first letter to uppercase
    const capitalized = str.charAt(0).toUpperCase() + str.slice(1);

    return capitalized;
}

// take input
const string = prompt('Enter a string: ');

const result = capitalizeFirstLetter(string);

console.log(result);

Output:

Enter a string: programming 
Programming

Example 2: Convert the First letter to UpperCase using Regex

Below the given program, convert the first letter of a string to uppercase by using the regular expression (regex).

  • The regex pattern is /^./ meets the first character of a string.
  • The toUpperCase() method changes the string to uppercase.
// program to convert first letter of a string to uppercase
function capitalizeFirstLetter(str) {

    // converting first letter to uppercase
    const capitalized = str.replace(/^./, str[0].toUpperCase());

    return capitalized;
}

// take input
const string = prompt('Enter a string: ');

const result = capitalizeFirstLetter(string);

console.log(result);

Output:

Enter a string: programming 
Programming