Shubham Ankit

Shubham Ankit

1554370917

Better loops in JavaScript

In this post, we will take a look at forms of for loop, array methods using which you can make your code simpler, more readable. These loops / methods are useful when you want to manipulate data in an array or object.

for in loop

With this kind of loop you don’t have to iterate over array indices, object keys manually.

//iterating over an array
let arr = [1, 2, 3, 4, 5]
for (let index in arr) {
  console.log(arr[index])
}
// Output: 1,2,3,4,5

//iterating over object keys
let obj = { id: 1, msg: ‘hello’ }
for (let key in obj) {
console.log(obj[key])
}
// Output: 1, hello

for of loop

Using this loop you can get the value at a particular index. This loop only works on arrays.

for (let val of arr) {
console.log(val)
}
// Output: 1,2,3,4,5

Array methods

Now let’s take a look at a few array loop methods. When processing arrays the loops tend to become too large, we have to explicitly push items into another array and so on. The following methods make it easier to deal with such scenarios. The following methods take a callback function as an argument that will be executed for each element in the array. Let’s look at a few examples.

Iterating over an array

For this, you can use the array.forEach() method. For-each takes a callback as an argument and executes it for each array element.

// display index and value
arr.forEach((value, index) => console.log(Index = ${index} Value = ${value}))

Transforming an array

To transform an existing array into another form you can use array.map() method. The map() method takes a callback as an arguement and returns a new array. The elements in the new array will be values that were returned by the callback.

Let’s say you have an array of objects, each object has id, name. You want an array that contains just the ids.

with for loop

let data = [
{ id: 1, name: ‘Phone’, type: ‘electronic’ },
{ id: 2, name: ‘Laptop’, type: ‘electronic’ },
{ id: 3, name: ‘Shirt’, type: ‘clothing’ },
]
let ids = []
for (let i = 0; i < data.length; i++) {
ids.push(data[i].id)
}

with map

let ids = data.map(function(val) {
return val.id
})

or even shorter and simpler with an arrow function

let ids = data.map(val => val.id)

Filtering elements from the array

To filter elements from the array you can make use of array.filter() method. The filter() method expects a callback, this callback will be executed for each element in the array & returns a new array that contains filtered items. If the callback function returns true for a given element that element will be in the filtered array.

Selecting electronic items

let electronics = data.filter(item => item.type == ‘electronic’)

Searching for an element in the array

If you want to search for an element in the array you can use array.find() method. Like all the other methods discussed here, this method also requires a callback. The callback function should return true or false. The the first value for which the callback returns true will be the output of this method. If there is no match, the function will return undefined.

Searching for name ‘Phone’

data.find(val => val.name == ‘Phone’)

Getting a single value from an array

To obtain a single value from an array you can use the array.reduce() method. The reduce() method, takes a callback function, initial value as an argument. The callback intern has an accumulator, currentValue as mandatory arguments. Accumulator contains the value that was obtained from the previous execution of the callback, currentValue is the array element under processing.

Sum and product of the array

let arr = [1, 2, 3, 4, 5]

//sum of array elements
arr.reduce((accumulator, currentValue) => (accumulator + currentValue), 0)
// where 0 is the initial value
// Output: 15

// product of array elements
arr.reduce((accumulator, currentValue) => (acc * currentValue), 1)
// Output: 120

Checking if a condition is true for at least one element in the array.

For this use array.some() method. This method will return true if the condition is true on at least one element in the array, otherwise it will return false.

let friends = [13, 15, 16, 18] //ages of group of friends

// checking if at least one of them is 18 or above
friends.some(val => val >= 18)

Checking if a condition is true for all the elements in the array

For this use array.every() method. This method will return true if a condition is true for all the elements in the array, otherwise it will return false.

let giftPrices = [300, 350, 399, 400]
let budgetPerGift = 450

let checkBudget = price => price <= budgetPerGift

giftPrices.every(checkBudget) // true

budgetPerGift = 300

giftPrices.every(checkBudget) // false

Things to take care of

  • The array methods are slightly slower than normal for loop, but they offer a lot of advantages, and their performance will improve with changes to JS engines.
  • All the methods that we have discussed above (except some(), find()), execute on the entire array. If you don’t want to do this than these methods are of no use to you. You can’t use break to stop the callback.

That’s it for today. These methods have lot’s of potential, go through their documentation on MDN, try these out.

If you like this post do share it :).

Originally published by Kartik Malik at https://dev.to

Learn More

☞ The Complete JavaScript Course 2019: Build Real Projects!

☞ Become a JavaScript developer - Learn (React, Node,Angular)

☞ JavaScript: Understanding the Weird Parts

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

☞ The Full JavaScript & ES6 Tutorial - (including ES7 & React)

☞ JavaScript - Step By Step Guide For Beginners

☞ The Web Developer Bootcamp

☞ MERN Stack Front To Back: Full Stack React, Redux & Node.js

☞ Visual Studio Code Settings and Extensions for Faster JavaScript Development

☞ Vue.js Authentication System with Node.js Backend

#javascript

What is GEEK

Buddha Community

Better loops in JavaScript
Lowa Alice

Lowa Alice

1624406400

JavaScript Loops Tutorial

JavaScript loops made simple.

📺 The video in this post was made by Programming with Mosh
The origin of the article: https://www.youtube.com/watch?v=s9wW2PpJsmQ&list=PLTjRvDozrdlxEIuOBZkMAK5uiqp8rHUax&index=8
🔥 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 #loops #javascript loops #javascript loops tutorial

Rahul Jangid

1622207074

What is JavaScript - Stackfindover - Blog

Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.

Who invented JavaScript?

JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.

What is JavaScript?

JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.

Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.

JavaScript Hello World Program

In JavaScript, ‘document.write‘ is used to represent a string on a browser.

<script type="text/javascript">
	document.write("Hello World!");
</script>

How to comment JavaScript code?

  • For single line comment in JavaScript we have to use // (double slashes)
  • For multiple line comments we have to use / * – – * /
<script type="text/javascript">

//single line comment

/* document.write("Hello"); */

</script>

Advantages and Disadvantages of JavaScript

#javascript #javascript code #javascript hello world #what is javascript #who invented javascript

Hire Dedicated JavaScript Developers -Hire JavaScript Developers

It is said that a digital resource a business has must be interactive in nature, so the website or the business app should be interactive. How do you make the app interactive? With the use of JavaScript.

Does your business need an interactive website or app?

Hire Dedicated JavaScript Developer from WebClues Infotech as the developer we offer is highly skilled and expert in what they do. Our developers are collaborative in nature and work with complete transparency with the customers.

The technology used to develop the overall app by the developers from WebClues Infotech is at par with the latest available technology.

Get your business app with JavaScript

For more inquiry click here https://bit.ly/31eZyDZ

Book Free Interview: https://bit.ly/3dDShFg

#hire dedicated javascript developers #hire javascript developers #top javascript developers for hire #hire javascript developer #hire a freelancer for javascript developer #hire the best javascript developers

Niraj Kafle

1589255577

The essential JavaScript concepts that you should understand

As a JavaScript developer of any level, you need to understand its foundational concepts and some of the new ideas that help us developing code. In this article, we are going to review 16 basic concepts. So without further ado, let’s get to it.

#javascript-interview #javascript-development #javascript-fundamental #javascript #javascript-tips

Ida  Nader

Ida Nader

1599099600

How to Use If-Else Statements and Loops in R – Dataquest

When we’re programming in R (or any other language, for that matter), we often want to control when and how particular parts of our code are executed. We can do that using control structures like if-else statements, for loops, and while loops.

Control structures are blocks of code that determine how other sections of code are executed based on specified parameters. You can think of these as a bit like the instructions a parent might give a child before leaving the house:

“If I’m not home by 8pm, make yourself dinner.”

Control structures set a condition and tell R what to do when that condition is met or not met. And unlike some kids, R will always do what we tell it to! You can learn more about control structures in the R documentation if you would like.

In this tutorial, we assume you’re familiar with basic data structures, and arithmetic operations in R.

Not quite there yet? Check out our Introductory R Programming course that’s part of our Data Analyst in R path. It’s free to start learning, there are no prerequisites, and there’s nothing to install — you can start learning in your browser right now.

install.packages(“Dataquest”)

Start learning R today with our Introduction to R course — no credit card required!

SIGN UP

(This tutorial is based on our intermediate R programming course, so check that out as well! It’s interactive and will allow you to write and run code right in your browser.)

Comparison Operators in R

In order to use control structures, we need to create statements that will turn out to be either TRUE or FALSE. In the kids example above, the statement “It’s 8pm. Are my parents home yet?” yields TRUE (“Yes”) or FALSE (“No”). In R, the most fundamental way to evaluate something as TRUE or FALSE is through comparison operators.

Below are six essential comparison operators for working with control structures in R:

  • == means equality. The statement x == a framed as a question means “Does the value of x equal the value of a?”
  • != means “not equal”. The statement x == b means “Does the value of x not equal the value of b?”
  • < means “less than”. The statement x < c means “Is the value of x less than the value of c?”
  • <= means “less than or equal”. The statement x <= d means “Is the value of x less or equal to the value of d?”
  • > means “greater than”. The statement x > e means “Is the value of x greater than the value of e?”
  • >= means “greater than or equal”. The statement x >= f means “Is the value of xgreater than or equal to the value of f?”

#data science tutorials #beginner #for loop #for loops #if #if else #learn r #r #r tutorial #rstats #tutorial #tutorials #while loop #while loops