Giter VIP home page Giter VIP logo

javascript-loops's Introduction

JavaScript Loops

Twitter Follow

Support the author to create more educational materials
Paypal Logo

JavaScript Loops

In programming we use different loops to carry out repetitive tasks. Therefore, loop can help us to automate tedious and repetitive task. JavaScript has also different types of loops which we can use to work on repetitive task.

Imagine if your are asked to print Hello world one thousand times without a loop, it may take an hour or two to do this tedious task. However, using loop we can print it in less than a second.

Loops:

  • for
  • while
  • do while
  • for of
  • forEach
  • for in

A loop usually goes until the condition gets false. But sometimes we like to intrupt the loop or skip an item during iteration. We use break to intrupt the loop and continue to skip an item during iteration.

Types of Loops

1. for

We use for loop when we know how many iteration we go. Let's see the following example

// for loop syntax

for (initialization, condition, increment/decrement) {
    code goes here
}

This code prints from 0 to 5.

for (let i = 0; i < 6; i++) {
  console.log(i)
}

For example if we want to sum all the numbers from 0 to 100.

let sum = 0
for (let i = 0; i < 101; i++) {
  sum += i
}

console.log(sum)

If we want to sum only even numbers:

let sum = 0
for (let i = 0; i < 101; i += 2) {
  sum += i
}

console.log(sum)

// or another way

let total = 0
for (let i = 0; i < 101; i++) {
  if (i % 2 == 0) {
    total += i
  }
}
console.log(total)

This code iterates through the array

const nums = [1, 2, 3, 4, 5]
for (let i = 0; i < 6; i++) {
  console.log(nums[i])
}

This code prints 5 to 0. Looping in reverse order

for (let i = 5; i >= 0; i--) {
  console.log(i)
}

The Code below can reverse an array.

const nums = [1, 2, 3, 4, 5]
const lastIndex = nums.length - 1
const newArray = []
for (let i = lastIndex; i >= 0; i--) {
  newArray.push(nums[i])
}

console.log(newArray)

2. while

We use the while loop when we do not know how man iteration we go in advance.

let count = prompt('Enter a positive number: ')
while (count > 0) {
  console.log(count)
  count--
}

3. do while

Do while run at least once if the condition is true or false

let count = 0
do {
  console.log(count)
  count++
} while (count < 11)

The code below runs ones though the condition is false

let count = 11
do {
  console.log(count)
  count++
} while (count < 11)

While loop is the least important loop in many programming languages.

4. for of

The for of loop is very handy to use it with array. If we are not interested in the index of the array a for of loop is preferable to regular for loop or forEach loop.

const numbers = [1, 2, 3, 4, 5]
for (const number of numbers) {
  console.log(number)
}

const countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland']
for (const country of countries) {
  console.log(country.toUpperCase())
}

5. forEach

If we are interested in the index of the array forEach is preferable to for of loop. The forEach array method takes a callback function, the callback function takes three arguments: the item, the index and the array itself.

const numbers = [1, 2, 3, 4, 5]
numbers.forEach((number, i) => {
  console.log(number, i)
})

const countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland']
countries.forEach((country, i, arr) => {
  console.log(i, country.toUpperCase())
})

6. for in

The for in loop can be used with object literals to get the keys of the object.

const user = {
  firstName: 'Asabeneh',
  lastName: 'Yetayeh',
  age: 250,
  country: 'Finland',
  skills: ['HTML', 'CSS', 'JS', 'React', 'Node', 'Python', 'D3.js'],
}

for (const key in user) {
  console.log(key, user[key])
}

Intrupting a loop and skipping an item

break

Break is used to interrupt a loop.

for (let i = 0; i <= 5; i++) {
  if (i == 3) {
    break
  }
  console.log(i)
}

// 0 1 2

The above code stops if 3 found in the iteration process.

continue

We use the keyword continue to skip a certain iterations.

for (let i = 0; i <= 5; i++) {
  if (i == 3) {
    continue
  }
  console.log(i)
}
// 0 1 2 4 5

Conclusions

  • Regular for loop can be used anywhere when the number of iteration is known.
  • While loop when the number of iteration is not know
  • Do while loop and while loop are almost the same but do while loop run at least once even when the condition is false
  • for of is used only for array
  • forEach is used for array
  • for in is used for object

More Materials

For more JavaScript and other programming lessons and tutorials, you may check Washera YouTube channel.

If you want to dive deep into JavaScript, you can give it a try to the 30DaysOfJavaScript challenge. This challenge will take quite long time to finish but you can get all you need about JavaScript

JavaScript

  1. 30DaysJavaScript challenge
  2. JavaScript for Everyone
  3. Functional programming in JavaScript
  4. Destructuring in JavaScript

React

  1. React for Everyone

Python

  1. 30DaysOfPython

๐ŸŽ‰ CONGRATULATIONS ๐ŸŽ‰

Now, you knew everything you need to know about JavaScript loops.

javascript-loops's People

Contributors

asabeneh avatar

Stargazers

HuynhXuanLam-IT44 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.