Skip to content

02. Loops and Functions

idavidov13 edited this page Oct 10, 2023 · 5 revisions

Loops

FOR Loop

The for loop in JavaScript is a control flow statement that allows code to be executed repeatedly based on a given condition. It's one of the primary means to perform iteration in JavaScript. for (let i=1; i <= 5; i++) { console.log(i) };

FOR-OF Loop

for (let item of array)

  • using indexes from FOR-OF loop - for (let [i, anything] of array.entries())

WHILE Loop

The while loop in JavaScript is a control flow statement that repeatedly executes a block of code as long as a specified condition evaluates to true. let i=1; while (i <= 5) { console.log(i); i++ };

continue and break

  • continue - terminate the current iteration of the loop and continue with the next
  • break - completely terminate the whole loop

Functions

function logger() {
console.log('My name is Ivan');
}
// calling / running/ invoking function
logger();

Function declaration

function calcAge1(birthYear) {
return 2023 - birthYear;
}
const age1 = calcAge1(1990);

Function Expression

const calcAge2 = function (birthYear) {
return 2023 - birthYear;
}

Arrow Function

const calcAge3 = birthYear => 2023 - birthYear;
const age3 = calcAge3(1990)

return keyword immediately stops the function's execution and returns the specified value to the caller

function readFullName(firstName, lastName) {
return firstName + " " + lastName;
}
const fullName = readFullName("John","Smith");
console.log(fullName) //John Smith

Default values for function's parameters

function (parameter1, parameter2 = 'default value', parameter3 = 'default value' * parameter2){}

First-class vs. Higher-order functions

image

Callback functions

They help to split our code into more understandable and reusable parts and allow us to make an abstraction (hide the details when we don't care about them).

Immediately Invoked Function Expressions (IIFE)

(function () {console.log('This will never run again!');})();
(() => console.log('This will never run again!'))()

Closures

image image image image

Clone this wiki locally