Blocking code in javascript

block

A block statement is used to group zero or more statements. The block is delimited by a pair of braces («curly brackets») and contains a list of zero or more statements and declarations.

Try it

Syntax

Statements and declarations grouped within the block statement.

Description

The block statement is often called the compound statement in other languages. It allows you to use multiple statements where JavaScript expects only one statement. Combining statements into blocks is a common practice in JavaScript, especially when used in association with control flow statements like if. else and for . The opposite behavior is possible using an empty statement, where you provide no statement, although one is required.

In addition, combined with block-scoped declarations like let , const , and class , blocks can prevent temporary variables from polluting the global namespace, just like IIFEs do.

Block scoping rules with var or function declaration in non-strict mode

Variables declared with var or created by function declarations in non-strict mode do not have block scope. Variables introduced within a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. For example:

var x = 1;  var x = 2; > console.log(x); // 2 

This logs 2 because the var x statement within the block is in the same scope as the var x statement before the block.

In non-strict code, function declarations inside blocks behave strangely. Do not use them.

Block scoping rules with let, const, class, or function declaration in strict mode

By contrast, identifiers declared with let , const , and class do have block scope:

let x = 1;  let x = 2; > console.log(x); // 1 

The x = 2 is limited in scope to the block in which it was defined.

The same is true of const :

const c = 1;  const c = 2; > console.log(c); // 1; does not throw SyntaxError 

Note that the block-scoped const c = 2 does not throw a SyntaxError: Identifier ‘c’ has already been declared because it can be declared uniquely within the block.

In strict mode, function declarations inside blocks are scoped to that block and are hoisted.

"use strict";  foo(); // Logs "foo" function foo()  console.log("foo"); > > foo(); // ReferenceError: foo is not defined 

Examples

Using a block statement as the body of a for loop

A for loop accepts a single statement as its body.

for (let i = 0; i  10; i++) console.log(i); 

If you want to use more than one statement in the loop body, you can group them into one block statement:

for (let i = 0; i  10; i++)  console.log(i); console.log(i ** 2); > 

Using a block statement to encapsulate data

let and const declarations are scoped to the containing block. This allows you to hide data from the global scope without wrapping it in a function.

let sector;  // These variables are scoped to this block and are not // accessible after the block const angle = Math.PI / 3; const radius = 10; sector =  radius, angle, area: (angle / 2) * radius ** 2, perimeter: 2 * radius + angle * radius, >; > console.log(sector); // // radius: 10, // angle: 1.0471975511965976, // area: 52.35987755982988, // perimeter: 30.471975511965976 // > console.log(typeof radius); // "undefined" 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Feb 21, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Overview of Blocking vs Non-Blocking

This overview covers the difference between blocking and non-blocking calls in Node.js. This overview will refer to the event loop and libuv but no prior knowledge of those topics is required. Readers are assumed to have a basic understanding of the JavaScript language and Node.js callback pattern.

«I/O» refers primarily to interaction with the system’s disk and network supported by libuv.

Blocking

Blocking is when the execution of additional JavaScript in the Node.js process must wait until a non-JavaScript operation completes. This happens because the event loop is unable to continue running JavaScript while a blocking operation is occurring.

In Node.js, JavaScript that exhibits poor performance due to being CPU intensive rather than waiting on a non-JavaScript operation, such as I/O, isn’t typically referred to as blocking. Synchronous methods in the Node.js standard library that use libuv are the most commonly used blocking operations. Native modules may also have blocking methods.

All of the I/O methods in the Node.js standard library provide asynchronous versions, which are non-blocking, and accept callback functions. Some methods also have blocking counterparts, which have names that end with Sync .

Comparing Code

Blocking methods execute synchronously and non-blocking methods execute asynchronously.

Using the File System module as an example, this is a synchronous file read:

const fs = require("fs"); const data = fs.readFileSync("/file.md"); // blocks here until file is read 

And here is an equivalent asynchronous example:

const fs = require("fs"); fs.readFile("/file.md", (err, data) => < if (err) throw err; >); 

The first example appears simpler than the second but has the disadvantage of the second line blocking the execution of any additional JavaScript until the entire file is read. Note that in the synchronous version if an error is thrown it will need to be caught or the process will crash. In the asynchronous version, it is up to the author to decide whether an error should throw as shown.

Let’s expand our example a little bit:

const fs = require("fs"); const data = fs.readFileSync("/file.md"); // blocks here until file is read console.log(data); moreWork(); // will run after console.log 

And here is a similar, but not equivalent asynchronous example:

const fs = require("fs"); fs.readFile("/file.md", (err, data) => < if (err) throw err; console.log(data); >); moreWork(); // will run before console.log 

In the first example above, console.log will be called before moreWork() . In the second example fs.readFile() is non-blocking so JavaScript execution can continue and moreWork() will be called first. The ability to run moreWork() without waiting for the file read to complete is a key design choice that allows for higher throughput.

Concurrency and Throughput

JavaScript execution in Node.js is single threaded, so concurrency refers to the event loop’s capacity to execute JavaScript callback functions after completing other work. Any code that is expected to run in a concurrent manner must allow the event loop to continue running as non-JavaScript operations, like I/O, are occurring.

As an example, let’s consider a case where each request to a web server takes 50ms to complete and 45ms of that 50ms is database I/O that can be done asynchronously. Choosing non-blocking asynchronous operations frees up that 45ms per request to handle other requests. This is a significant difference in capacity just by choosing to use non-blocking methods instead of blocking methods.

The event loop is different than models in many other languages where additional threads may be created to handle concurrent work.

Dangers of Mixing Blocking and Non-Blocking Code

There are some patterns that should be avoided when dealing with I/O. Let’s look at an example:

const fs = require("fs"); fs.readFile("/file.md", (err, data) => < if (err) throw err; console.log(data); >); fs.unlinkSync("/file.md"); 

In the above example, fs.unlinkSync() is likely to be run before fs.readFile() , which would delete file.md before it is actually read. A better way to write this, which is completely non-blocking and guaranteed to execute in the correct order is:

const fs = require("fs"); fs.readFile("/file.md", (readFileErr, data) => < if (readFileErr) throw readFileErr; console.log(data); fs.unlink("/file.md", (unlinkErr) =>< if (unlinkErr) throw unlinkErr; >); >); 

The above places a non-blocking call to fs.unlink() within the callback of fs.readFile() which guarantees the correct order of operations.

Additional Resources

Copyright OpenJS Foundation and Node.js contributors. All rights reserved. The OpenJS Foundation has registered trademarks and uses trademarks. For a list of trademarks of the OpenJS Foundation, please see our Trademark Policy and Trademark List. Trademarks and logos not indicated on the list of OpenJS Foundation trademarks are trademarks™ or registered® trademarks of their respective holders. Use of them does not imply any affiliation with or endorsement by them.

Источник

A short guide to Blocking Code in Javascript

A short guide to Blocking Code in Javascript

When an app runs in a browser/server and it executes and an intensive chunk of code without returning control, the APP can appear to be frozen.

This is called blocking. The app is blocked from continuing to handle user input and perform other tasks until the app returns control of the processor.

Blocking Code in Browser

const btn = document.querySelector('button'); btn.addEventListener('click', () => < let myDate; for(let i = 0; i < 10000000; i++) < let date = new Date(); myDate = date; > let pElem = document.createElement('p'); pElem.textContent = 'Paragraph Added. '; document.body.appendChild(pElem); >); 

When running this and clicking the button, the paragraph does not appear until after the date has finished being calculated (10 million times).

Blocking code in Server

const fs = require('fs'); console.log("Start reading"); // blocks here until file is read cost data = fs.readFileSync('/file.md'); console.log("Finished reading"); moreWork(); 

The function moreWork() is executed only after the file-read is finished. Until then, the control is not returned and thus no other code-block is executed.

Prefer asynchronous coding to overcome the blocking and to improve the performance of the application.

Removal.AI — [SPONSOR]

Remove background from multiple images in a single upload straight to your desktop using Bulk Photo Background Remover for Windows.

  • ✅ Drag & Drop Multiple Images
  • ✅ Optimize Product Images
  • ✅ Select Your Background
  • ✅ Set Your Output Size
  • ✅ Exceptional Results

Did you find this article valuable?

Support Rahul by becoming a sponsor. Any amount is appreciated!

Источник

How node.js prevents blocking code ?

Node.js is a cross-platform JavaScript runtime environment that helps to execute and implement server-side programs. Node is assumed to prevent blocking code by using a single-threaded event loop. In this article, we will discuss this event loop and how it asynchronously implements functions by using callbacks.

Blocking and Non-blocking operations: Blocking operations refer to the pieces of code that block the execution of other code until they are completed. While non-blocking operations allow further pieces of code to execute without making them wait and use callbacks when they are completed.

Thus, blocking code can be said to work synchronously while non-blocking code works asynchronously. While discussing non-blocking code, we come up with a term called callback. The callback is a function that is invoked when a process completes its execution and wants to continue its normal execution with the outer function.

Node and Event Loop: Now we know what blocking and non-blocking operations are, we can discuss how node prevents blocking code. Node uses a single thread, which means one task can be executed at a time. This is done by using a stack. While reading the code from top to bottom, each instruction is pushed into a stack and when its execution is completed, it pops out of the stack. Now we may come across an instruction/function that will take a longer time to execute which can result in the delay in popping the stack and execution of further statements.

So what Node.js allows is the use of Event Loop. Each time when we encounter such a situation, the process causing the delay is offloaded from the stack and the execution of that process continues parallel to further execution of the main code. Thus, the callback for that function is pushed into a task queue and the code continues to execute asynchronously. When the process completes its execution, the callback function returns the desired output from that process and resumes normal execution.

Example: Let’s consider an example that will demonstrate how the event loop works.

Источник

Читайте также:  Кроссбраузерная верстка css grid
Оцените статью