Callum Slater

Callum Slater

1654072135

Everything You Need To Know About JavaScript Functions

Functions are fundamental part of JavaScript. Learn the basics of JavaScript functions, how to create them, use them and how to use parameters and arguments

JavaScript Functions - All You Need to Know Pt.1

Functions are fundamental part of JavaScript programming language. Every JavaScript developer should know how to work with them. This tutorial will teach you the basics of JavaScript functions. You will learn how to create functions and how to use parameters and arguments.

The Basic

What are functions? One way to think about functions is as building blocks of programs. You can also think about them as a subprograms that are created with the purpose to do specific tasks. The main reason developers use functions is because they allow you to re-use chunks of code, without the need to write the code over and over again.

Let’s say you’ve just created a function with some code inside it. Now, when you want to execute the code inside that function all you need to do is to call that function. “Calling a function” is also called “invoking a function”. Another great thing on functions is that you can also pass values into them.

This means that even though the code inside the function remains the same what happens after calling the function can differ. What’s more, you call also pass another function as a value and then call that function you passed inside the function.

Function declaration and function expression

In JavaScript, there are two ways to create functions. One is by using function declaration. The second is by using function expression. When you want to create a function using function declaration you start with function keyword, followed by the name of the function, followed by parenthesis with parameters and curly brackets with code to be executed.

When you define function using function declaration it will be hoisted. Put simply, you can call that function before you define it in your code. JavaScript will move the function declaration to the top of the scope during the runtime. When you run the code, the function is actually available before you call it.

// Function declaration example
function myFunction() {
  // some code
}


// Function declaration and hoisting
// Call myFunction before you define it
myFunction()
// 'I run!'

// Create myFunction
function myFunction() {
  console.log('I run!')
}

In case of function expressions, you define either named or anonymous function. Using function expressions allows you to assign the function to a variable. When some function is anonymous it means that that function has no name. Unlike function declaration, function expressions are not hoisted.

A function expression is created only when the execution reaches its location in your code. It is this moment from which it is usable, not sooner. Keep this in mind when you use function expression. You can’t use functions created with function expression before you define them. About the syntax.

When you want to use function expression you start with let, const or var keyword to declare a variable. Then, you add equal sign followed by function keyword, followed by parenthesis with parameters and curly brackets with code to be executed.

// Function expression example
const myFunction = function() {
  // some code
}


// Function expression and hoisting
// Call myFunction before you define it
myFunction()
// ReferenceError: myFunction is not defined

// Create myFunction
const myFunction = function() {
  console.log('Let\'s try this.')
}

Calling, or invoking, functions

Function is not executed until you call it, or invoke it. In order to call, or invoke, a function you must reference it using the function name, followed by an open and closed parenthesis (()). If a function has some parameters (more about this in the next section) you pass them inside those parenthesis.

// Example no.1: Calling, or invoking, function with no parameters.
// Define a function printMessage using function declaration
function printMessage() {
  return 'Hello from printMessage function!'
}

// Call or invoke printMessage function
printMessage()
// 'Hello from printMessage function!'


// Or, using function expression
const printMessage = function() {
  return 'Hello from printMessage function!'
}

// Call or invoke printMessage function
printMessage()
// 'Hello from printMessage function!'


// Example no.2: Calling, or invoking, function with parameters.
function returnDouble(num) {
  return num * 2
}

// Call or invoke returnDouble function
returnDouble(98)
// 196


// Or, using function expression
const returnDouble = function(num) {
  return num * 2
}

// Call or invoke returnDouble function
returnDouble(656)
// 1312

Function parameters

Functions allow you to pass data into them using parameters. These parameters are also called function arguments. When you define a function that accepts a parameter, you can call it without passing them. The function will still execute. The problem is that missing parameter can cause some things, that depend on that parameter, to break.

So, when you specify parameters for functions make sure to also pass the necessary data when you call those functions. When it comes to parameters, there is (theoretically) no limit to how many of them you can use. The only thing to remember, if you want to use multiple parameters, is to separate them with comas.

// Create function that accepts one parameter - name
function greeting(name) {
  return `Hello ${name}! Nice to meet you.`
}

// Call getting function, passing some name
greeting('Tommy')
// "Hello Tommy! Nice to meet you."


// Call getting function without passing anything
greeting()
// "Hello undefined! Nice to meet you."


// Create function that accepts four parameters - name, age, sex, nationality
function createUser(name, age, sex, nationality) {
  // do something
}

createUser('Nikolaj Chernov', 38, 'male', 'Russian')

Functions and default parameters

When you specify parameter for function its default value will be undefined. This value will change when you call that function and pass some data to it. This is why, in the example above, calling greeting() function without passing any name led to undefined in the returned message.

Fortunately, there is now a way to prevent this from happening. Since the release of ES6 specification you can use something called default parameters. Put simply, you can specify function parameter and set it to some default value. Then, when you call that function without passing anything that parameter will no longer be undefined.

Instead, that parameter will contain the default value you specified earlier. If you do, pass something, JavaScript will use the data you passed and ignore the default. Using default parameters are very useful. They can help you avoid issues caused by forgetting to pass some data to the function.

The syntax for default parameters is very easy. When you specify the parameter, inside parenthesis, you follow it with equal sign and something. This “something” will be the default value for that parameter, i.e. function myFunction(myParam = 'Default value') {}.

// Create greeting function with name parameter
// that has default value of 'Anonymous'
function greeting(name = 'Anonymous') {
  console.log(`Hello ${name}!`)
}

// Call greeting() without passing any name
greeting()
// 'Hello Anonymous!'

// Call greeting() with some name
greeting('Toby')
// 'Hello Toby!'


// Using default parameters with parameters no.1
// Set 55 to be a default value for parameter b
function doTheMath(a, b = 55) {
  return a * b
}

doTheMath(5)
// 275


// Using default parameters with parameters no.2
// Set default values for all parameters
function introduction(name = 'Joe', sex = 'male', age = 28) {
  return `Hi, my name is ${name}, I am ${sex} and I am ${age} years old.`
}

introduction('Sandra', 'female')
// 'Hi, my name is Sandra, I am female and I am 28 years old.'

Functions, parameters and arguments

When it comes to functions, there is one thing that often confuses developers. This thing are function parameters and arguments. The problem is that both names actually talk about the same thing. They both talk about function parameters. It is no wonder many developers use these terms interchangeably.

However, there is a difference. The difference, and way to distinguish between parameters and arguments, is when you use these terms. When you are defining functions, you talk about function parameters. Here, parameters are the names created in the function definition. So, it is correct to say that some function accepts, one or more “parameters”.

Something else is when you talk about calling, or invoking, a function. Here, arguments are the values the function you invoke, or call, receives. So, the correct term to use is “argument”, i.e. passing something to function as an argument, or calling a function with argument.

// Function parameters
// Use when defining a function
// Function with parameter 'param'
function funcOne(param) {}

// Or
const funcTwo = function(param) {}


// Function arguments
// Use when calling or invoking a function
// Call funcOne with 'This is an argument.' passed as an argument
funcOne('This is an argument.')

// Or
// Call funcTwo with 'This is also an argument.' passed as an argument
funcTwo('This is also an argument.')

The arguments object

Since we are talking about parameters and arguments, there is one interesting you should know. Every function contains something called arguments object. This is an object that contains values of all arguments passed to the function. What’s more, you can access this object in your code.

The whole object is accessible via arguments. When you want to access only some arguments you can use index. This index is based on the position of the argument in argument list (the order in which you passed all arguments to the function). Remember that index in arrays and objects starts with 0.

function createUser(name, age, sex, nationality) {
  console.log(arguments)
  // [object Arguments] {
  //   0: "Thomas More",
  //   1: 43,
  //   2: "male",
  //   3: "American"
  // }

  // Access the first argument
  console.log(arguments[0])
  // "Thomas More"

  // Access the second argument
  console.log(arguments[1])
  // 43

  // Access the third argument
  console.log(arguments[2])
  // "male"

  // Access the fourth argument
  console.log(arguments[3])
  // "American"

  // Check the number of arguments
  console.log(arguments.length)
  // 4
}

createUser('Thomas More', 43, 'male', 'American')

Functions are… objects

This may sound weird, but functions are actually objects. Or, function objects to be more specific. This may sound weird. However, in JavaScript there are only two types of “things”. The first one are primitive types. The second? Object. In JavaScript, if something is not a primitive type it is an object.

This is why functions are technically objects. Otherwise, they would have to be primitive types, which they are not. Since there is no third type, they are objects. This is a good thing because in JavaScript objects allow you to do a lot of things. Since functions are objects you can do many things with them as well.

For example, you can pass one function into another. Or, you can also return a function from another function. A bit of lingo. When function accepts another function as a parameter, or it returns a function, it is called a high-order function. One example of high-order function is JavaScript map() method.

// Simple high-order function no.1: function accepting function as a parameter
// Create first function
function doSomething(func) {}

// Create second function
function doSomethingElse() {}

// Call the first function and pass the second
doSomething(doSomethingElse)


// Simple high-order function no.2: function returning function
// Create first function
function doSomething() {
  return 'Do something.'
}

// Create second function
function doSomethingElse() {
  // Call the first function
  return doSomething()
}

// Call the second function
doSomethingElse()
// 'Do something.'

Return

This is another interested thing. In JavaScript, functions always return something, some value. This is true even if you don’t explicitly specify any returning value. In that case, if there is no explicitly specified return, the function will return undefined. Otherwise, it will return the value you specified.

You can specify what should a function return using return keyword. When you work with functions and return keyword, there is one important thing to remember. Function will stop executing under the conditions. First, there is no more code to execute, including loops. Second, there is a return keyword.

This, second condition, is especially important to remember because it means that any code you write after the return keyword will never execute. When function encounters return keyword it will do two things. First, it will return the thing you want it to return. Second, it will stop execution.

This scenario, when there is a code after return keyword, is also called “unreachable code” because it is literally beyond the reach. So, pay attention to when you use the return keyword in a function. If you want all the code to be executed, put it at the end of the code block inside the function.

This natural behavior of functions is not bad. It can be actually quite useful. It can help you terminate execution of your code when it is not necessary. For example, by using if statement at the top of the function. Based on the condition you can either return, anything or nothing, or let the function to execute the rest of the code.

// Example of function with explicit return
// note: using 'return' keyword
function sayHi() {
  return 'Hello, nice to meet you'
}

sayHi()
// 'Hello, nice to meet you'


// Example of function without explicit return
// note: not using 'return' keyword
function returnNothing() {
  // nada
}

returnNothing()
// undefined


// Example: return or execute function based on condition
function iMightNotReturn() {
  // Random number is 6 stop execution - return nothing
  if (Math.floor(Math.random() * 10) === 6) return

  // Else continue executing the code
}

There is another good thing about functions always returning something. You can use function, and function expression, to return a value and save it to a variable.

// Use function expression to create a function
// that takes one parameter, a number,
// and returns that number divided by 2
let divideByTwo = function(number) {
  // return the number divided by 2
  return number / 2
}

// Declare new variable that invokes the divideByTwo function
// and save the value returned by the divideByTwo function
// inside the variable
let age = divideByTwo(39)

console.log(age)
// 19.5

JavaScript Functions – All You Need to Know Pt.2

This tutorial will help you understand them. Learn about how variables, scope and this work in the context of JavaScript functions and get a brief introduction to call(), apply() and bind() methods, and how to use them to change value of this.

Functions, variables and scope

When you work with JavaScript function you have to remember one thing. All variables you declare inside a function will be declared as local variables. This means these variables will be visible only inside that function. If you try to access them outside the function you will get an error about undefined variable. This rule applies to all types of variables, var, let and const.

///
// Local variable example
// Declare logVars function
function logVars() {
  var ex1 = 'I\'m var inside logger function'
  let ex2 = 'I\'m let inside logger function'
  const ex3 = 'I\'m const inside logger function'

  console.log(ex1)
  console.log(ex2)
  console.log(ex3)
}

// Try to access the ex variable
console.log(ex1)
// ReferenceError: ex1 is not defined

console.log(ex2)
// ReferenceError: ex2 is not defined

console.log(ex3)
// ReferenceError: ex3 is not defined

// Invoke logVars function to log ex variable
logVars()
// 'I\'m var inside logger function'
// 'I\'m let inside logger function'
// 'I\'m const inside logger function'

On the other hand, functions can access variables declared in the outer scope. These variables are also called global variables. So, if you declare some variable somewhere in your code before function you can access that variable inside that function. What’s more. You can also modify global variables, variables that exist in the outer scope, inside functions.

// Define variables in global scope
var name = 'John Doe'
let age = 27
const language = 'English'

// Declare changeVars function
function changeVars() {
  // Access variables in global scope
  console.log(name)
  // 'John Doe'

  console.log(age)
  // 27

  console.log(language)
  // 'English'

  // Change the value of name and age variables in global scope
  name = 'Jack Sawyer'
  age = 31
}

// Invoke changeVars function to log and change some global variables
changeVars()

// Log global scope variables
console.log(name)
// 'Jack Sawyer'

console.log(age)
// 31

console.log(language)
// 'English'

When you work with functions and variables there is one thing you must pay attention to. If you declare a variable, and it has the same name as a global variable, the function will ignore the outer, global, variable and work with the local. There are things to do. First, double-check you chose a different name.

Second, make sure if you really want to declare a variable or if you want to access, or modify, existing variable instead. When it comes to variables and global scope, it is a good practice to minimize the use of global variables. It is better to declare your variables inside function where you want to use them, if it is possible.

// Declare global variable someVar
let someVar = 'There will be dragons.'

// Declare readVars function
function readVars() {
  // Declare local variable someVar
  let someVar = 'No dragons in plain sight.'

  // Log the value of local variable someVar
  console.log(someVar)
}

// Invoke readVars function
readVars()
// 'No dragons in plain sight.'

// Log the value of global variable someVar
console.log(someVar)
// 'There will be dragons.'

Functions and this

If there is one thing that cause JavaScript developers a lot of troubles and headaches it is this. In case of JavaScript functions, the this can cause some headaches as well. When you work with functions and this there are two things that can happen. When you don’t use strict mode this will reference the global object, or window.

On the other hand, when you are in strict mode, the value of this, when you access it from the inside of a function, will be undefined.

// This example 1: This in a non-strict mode
// Declare thisExample function
function logThis() {
  console.log(this)
  // [object Window]

  console.log(this === window)
  // true

  console.log(this === undefined)
  // false
}

// Invoke logThis
logThis()


// This example 2: This and strict mode
// Set strict mode
'use strict'

// Declare thisExample function
function logThisTwo() {
  console.log(this)
  // undefined

  console.log(this === window)
  // false

  console.log(this === undefined)
  // true
}

// Invoke logThisTwo
logThisTwo()

Call(), apply() and bind()

As you know, the value of this inside a function, at least in strict mode, will be undefined. However, this doesn’t mean you can’t change it. You can. You can change the value of this with the help of call(), apply() and bind() methods. The first two, the call() and apply() are very similar.

The main difference between these two is that call() method accepts an argument list. The apply() method accepts an array of arguments. The last one, bind(), creates a new function that will have the value of this set to the first parameter you passed to the bind() function.

One important thing about bind(). I works only once. bind() will not work if you use try to use it again on a function you already “bound”. It will always return the first value you passed to the bind() function.

// call() example
// Declare function that logs this
function bar() {
  console.log(this)
}

// Invoke bar
bar()
// undefined

// Invoke bar and use call to change the value of this
bar.call(7)
// 7
bar.call('call')
// 'call'


// apply() example
function bar() {
  console.log(this);
}

// Invoke bar
bar()
// undefined

bar.apply(7)
// 7
bar.apply('apply')
// 'apply'


// bind() example
function bar() {
  console.log(this);
}

// Invoke bar
bar()
// undefined

// Create new function using bind and bind this to 7
const bazz = bar.bind(7)

// Invoke new function bazz
bazz()
// 7


// This will not work
// Try to re-bind bazz to 'What?!'
const bazzy = bazz.bind('What?!')

// Invoke bazzy
bazzy()
// 7
// returns the same value you bound to bazz earlier

The call(), apply() and bind() methods are advanced and very powerful features of JavaScript. Explaining thoroughly how these methods work, and how you can use them, is beyond the scope of this tutorial. If you want to learn more about these methods I recommend you take a look at Mozilla Developer Network. There is a detailed documentation for call(), apply() as well as bind().

Function constructor

There is another interesting thing you can do with JavaScript functions, that is related to this. In the previous part, you’ve learned that functions are actually objects, or function objects. You can use functions, or rather Function constructors to create new function, or instances of that Function constructor.

The best way to think about Function constructor is to think about it as a blueprint. This is useful when you want to create multiple similar objects with the same properties and methods. Instead of repeating yourself again and again you create just one object, one Function constructor.

Then when you want to create multiple copies, also called instances, of that object you don’t have to write all the code again. Instead, you take that Function constructor you created earlier and use it to create its instances. All these instances will automatically inherit all methods and properties the Function constructor contains.

The way you create properties and methods inside the Function constructor is by using this. When you want to create new property, you use this followed by the property/method name and assign it some value, i.e. this.propName = 'something'. In case of methods, the process is similar.

The only difference is that now, you assign a function, instead of a primitive, i.e. this.methodName = function() {}. When you want to access some property, or method, that belongs to the Function constructor you use the this followed by the property/method name again, i.e. this.propName.

One important thing. When you want to create an instance of a Function constructor you have to use new keyword, i.e. let newInstance = new SomeConstructor(). This is really important to remember. If you forget to use the new keyword, you will be changing the global object, instead of changing the instance you’ve just created.

// Declare Function constructor Book
// That accepts three parameters - title, author, type
function Book(title, author, type) {
  // Create properties from passed parameters
  this.title = title
  this.type = type
  this.author = author

  // Create method that returns info
  // about book created with Book Function constructor
  this.getBookDetails = function () {
    return `${this.title} written by ${this.author}.`
  }
}

// Create instance of Book function
// REMEMBER!: Always use 'new' when calling constructor
const petSematary = new Book('Pet Sematary', 'Steven King', 'Fiction')

// Log details of petSematary
console.log(petSematary.getBookDetails())
// 'Pet Sematary written by Steven King.'


// Create another instance of Book function
// REMEMBER!: Always use 'new' when calling constructor
const warAndPeace = new Book('War and Peace', 'Leo Tolstoy', 'Fiction')

// Log details of warAndPeace
console.log(warAndPeace.getBookDetails())
// 'War and Peace written by Leo Tolstoy.'

A quick side note: It is a good practice to always start the name of the Function constructor with upper-case letter. This will not change how JavaScript compiles your code. However, it will help make your code clearer and readable.

Rest parameters

Sometimes, you may not know exactly how many parameters someone may pass into a function. Or, it might just be handy to not to limit the number of parameters a function can operate with. Whatever the case is, rest parameters is what you are looking for. Rest parameters allow the function to use all parameters passed into it.

The syntax of rest parameters is very simple. You use three dots followed by the name of the array that will contain all parameters, i.e. ...params. The name can be anything you want. As I mentioned, you will get all parameters in the form of an array. So, when you want to access those parameters you can uses indices, map(), forEach(), etc.

// Declare function with rest parameters
// 'allParams' will be the name of the array that contains all parameters
function useRestParams(...allParams) {
  // Get all parameters
  console.log(allParams)
  // [ 5, 8, 9, 6, 7, true, 'Bingo' ]

  // Get first parameter
  console.log(allParams[0])
  // 5

  // Get second parameter
  console.log(allParams[1])
  // 8

  // Get last parameter
  console.log(allParams[allParams.length - 1])
  // 'Bingo'

  // Get number of parameters passed into the function
  console.log(allParams.length)
  // 7
}

// Invoke useRestParams function
useRestParams(5, 8, 9, 6, 7, true, 'Bingo')

JavaScript also allows you to combine “standard” parameters with rest parameters. If you decide to use this combination of “standard” and rest parameter there is one thing you must pay attention to, the order of parameters. The rest parameters must be always at the end. This makes sense because rest parameters gather all remaining arguments.

// Create function that combines "standard" parameters and rest parameters
function buyCar(model, manufacturer, color, ...restOfParams) {
  console.log(model)
  // 'RX-8'

  console.log(manufacturer)
  // 'Mazda'

  console.log(color)
  // 'red'

  console.log(restOfParams)
  // [ 'no transmission', 'electric', 'remote control', 'with GPS' ]
}

buyCar('RX-8', 'Mazda', 'red', 'no transmission', 'electric', 'remote control', 'with GPS')


// This will not work
function buyCar(model, ...restOfParams, manufacturer, color) {}

buyCar('RX-8', 'Mazda', 'red', 'no transmission', 'electric', 'remote control', 'with GPS')
// SyntaxError: Rest parameter must be last formal parameter

Functions and naming conventions

We discussed a lot of things and went through many examples. One thing that remains untouched are naming practices and conventions. Let’s take a break from code and take a look at how to name functions properly. First, allowed characters. Naming conventions for functions are the same as conventions for naming variables.

This means that function name can start with, and contain, any letter, underscore (_) or dollar sign ($). It is not allowed to start the name with a number. However, you can include numbers in the name, just make sure the name doesn’t begin with any of them. That is about allowed characters. Now, let’s talk about some good practices.

Functions are usually used to execute some actions, with the exception of Function constructors. For this reason, it is a good practice to use, or include, verbs in the name. For example, “get…”, “delete…”, “create…”, “log…”, “show…”, “open…”, “check…”, etc. Another good practice is to keep the name brief and accurate.

There is no need to use names that look more like a sentence from Shakespeare. That said, the opposite is also not a good thing to do, i.e. using names with ultra short cryptic acronyms nobody can explain what they mean. So, not too short and not too long. The name should also be descriptive.

It should describe what the function does. So, when someone read your code he will have at least some clue about what the function does. Another commonly used practice, also related to verbs, is to start a function name with a verbal prefix that describes what the function does, i.e. the examples with verbs we discussed earlier.


JavaScript Functions – All You Need to Know Pt.3

In the world of JavaScript functions there are topics that may sound more difficult than they are. This article will help you understand them. Learn about advanced topic such as recursions, immediately-invoked functions, callbacks and also the latest arrival, arrow functions.

Recursive JavaScript functions, aka recursions

When it comes to JavaScript functions there are few topics that frequently confuse beginners. One of these topics are recursions, also called recursive functions. So, what is this “recursive” thing all about? Recursion is a technique for repeating some operation over and over again until it arrives at a result.

The way recursion is done is by creating a function that calls, or returns, itself inside itself. Then, when you invoke the function, it will call, and re-invoke, itself as many times as necessary. Or, infinitely if you forget to add some terminal case. Terminal case is a condition that causes the function to stop when the condition is met.

Interestingly, in some programming languages recursion is the main way, or at least, one of the often used ways, for looping. This is not the case in JavaScript. However, that doesn’t mean that you can’t use recursions in JavaScript. You can, with JavaScript functions. And, it also doesn’t mean that using recursion is bad.

In fact, there are situations where using recursions is favorable. For example, doing some math operations, sorting and traversing nodes of complex or non-linear data structures. In these, and other cases, recursion is one of the most effective approaches. This is also why you may hear about recursions often.

Another upside of recursions is that there are easy to test. They are easy to test because it is easy to write them as pure functions. Pure functions are functions that 1) always return the same value for the same argument(s). This makes the function predictable, i.e. you don’t have to guess what happens given specific input.

If you use the same input over and over again, like one hundred times, it will always return the same output, i.e. one hundred times. 2) has no side effects. Having no side effects means that function doesn’t change local, or global, variables. So, when you invoke that function you don’t have to worry about what other parts of code it may change.

In case of recursion, both these conditions are true. They consistently return the same value for the same input. They also don’t have any side effects. They don’t change any external variables. Depending on what you do, you may never need to use recursions. Maybe just to gain some street cred among your colleagues.

Recursive JavaScript functions in practice

That said, it is still good to know at least how may recursions look like. This will help you recognize it in the code. It can also help you understand how it works and how to use it. A very good use case for recursion is factorial. Factorial is about multiplying a number again and again by each preceding integer, all the way down to one. Factorial of 5 is 5 x 4 x 3 x 2 x 1.

So, how can you use JavaScript function to handle this, to create function that will use recursion to calculate factorial? First, you will need to create a function. Let’s call it calcFactorial, using some good naming practices. This function will take one parameter, some number for which you want to calculate the factorial.

Inside this function, you will use if else statement. This statement will check if the number, passed as argument, is bigger than 0. If the number is bigger that 0 it will multiply it by the value returned by calcFactorial, after being subtracted by 1. If it is not bigger than 0, it will return 1, and do nothing more.

This one is optional. If you want to make your calcFactorial function foolproof, you can also add one more if else statement to check if the number passed as argument is indeed a number. If it is not, it will return some error message and terminate the function. Otherwise, it will proceed.

// Factorial example
// Create function for calculating factorial
function calcFactorial(num) {
  // Optional: check for numbers
  if (typeof(num) !== 'number') return 'The num must be a number.'

  if (num > 0) {
    // If num is bigger that 0
    // multiply the num by returned value
    // of calcFactorial subtracted by 1
    return (num * calcFactorial(num - 1))
  } else {
    // This is the terminal case
    // If value is 0, return 1, and do nothing after it
    return 1
  }
}

// Calculate factorial of 11
calcFactorial(11)
// 39916800

// Try to invoke calcFactorial with string
calcFactorial('152')
// 'The num must be a number.'

Another good example of recursion is creating a function that will work as a countdown. Similarly to the recursion function, this one will also take a number as a parameter.

// Create function for countdown
function countdown(num) {
  // Optional: check for numbers
  if (typeof(num) !== 'number') return 'The num must be a number.'

  if (num > 0) {
    // If num is bigger that 0
    // log the current value of num
    console.log(num)

    // Then return the countdown function itself,
    // passing num subtracted by 1 as an argument
    return countdown(num - 1)
  } else {
    // This is the terminal case
    // If value is 0, return current value of num
    // and do nothing after it
    return num
  }
}

// Countdown from 10
countdown(10)
// 10
// 9
// 8
// 7
// 6
// 5
// 4
// 3
// 2
// 1
// 0

As you can see on both examples, our functions indeed meet both conditions for being pure. First, they always return the same value for the same argument(s). It never happens the factorial function returned a different output for the same input, or number. The same applies to the countdown function.

What about the second condition? Neither of these functions has side effects. They don’t make any changes to outside environment. That’s it for recursive JavaScript functions.

Immediately-invoked functions

Another frequently mentioned thing, in the terms of JavaScript functions, are immediately-invoked functions. These functions are also referred to via its acronym IIFE. Before we get into this, there is one thing you must understand. In the past, there was only one way to declare variables in JavaScript, using var.

There was no let and const. The problem with var is that it doesn’t work with block scope. It works only with global or function scope. JavaScript developers needed some way to make var work in a block scope. So, they created it. They used JavaScript functions to create emulated scope that allowed to use var in block-like scope.

Nowadays, this is no loner need thanks to ES6 and let and const. Nonetheless, it can happen that you will encounter immediately-invoked functions from time to time. So, it is good to know how they look and how to use them. Creating immediately-invoked function is simple. You use function expression to create new function, i.e. function() {}.

Note that you are not assigning that function to any variable. Next, you wrap this function with parenthesis and add another set of parenthesis to call it, i.e. (function() {})(). Why this? When JavaScript encounters “function” keyword in your code, it thinks you want to create a new function using function declaration.

The problem is that function declaration must have a name. What if there is none? When there is no name, JavaScript will throw an error: SyntaxError: Unexpected token. This makes sense because it expects some name. It doesn’t expect a parenthesis so soon. What if you try to solve this problem by giving the function a name?

It will not work either. What’s the problem here? When you create a function with function declarations JavaScript will not allow you to call that function immediately, i.e. function myFunc() {}(). This will lead to another syntax error: SyntaxError: Unexpected token. The only way around this problem is wrapping the function with parenthesis, i.e. (function() {})().

Doing this tells JavaScript that the function you are creating is created in the context of another expression. Now, we are no longer talking about function declaration, but about function expression. With function expression we no longer need any name for our function and we can also call it immediately.

Wrapping a function with parenthesis is not the only way to create immediately-invoked functions in JavaScript. You can also use either ! (NOT operator) or + (unary plus) and put it right at the start of the function, i.e. !function() {}() or +function() {}(). Both will work. However, the approach with parenthesis is more common.

One more thing. It is not necessary to put the second pair of parenthesis, those that will invoke the function, after the parenthesis you used to wrap the function. You can also put them inside the wrapping parenthesis, right after the closing curly bracket, i.e. (function() {}()).

As I mentioned, var variables work only with global and function scope. Creating JavaScript functions this way, as immediately-invoked, creates new function scope, something like an emulation for a block scope. This allows you to have var variables restricted, or visible, only where you want them, inside the newly created function scope.

// Creating IIFE example no.1:
// invoking parenthesis outside wrapping parenthesis
(function() {
  // ... some code
})()


// Creating IIFE example no.2:
// invoking parenthesis inside wrapping parenthesis
(function() {
  // ... some code
}())


// Creating IIFE example no.3:
// using ! (NOT operator)
!function() {
  // ... some code
}()


// Creating IIFE example no.4:
// Using + (unary operator)
+function() {
  // ... some code
}()


// This will not work
function() {
  // ... some code
}()
// SyntaxError: Unexpected token

// This will also not work
function myFunc() {
  // ... some code
}()
// SyntaxError: Unexpected token

Callback functions

Another interesting thing in the world of JavaScript functions are callback functions. The idea here is that you pass a function as an argument to another function when you call it. And, you also expect that the function, you passed in as an argument, will be sooner or later called, or “called back”, inside the function you called.

This may sound weird, but it is like passing value, reference to a variable or an object. This time, you are passing a function and, instead of processing that function, you call it. Let’s take a look at simple example. Imagine you have a function eatFood(). This function will take two parameters.

The first parameter will be the food you are about to eat. The second parameter will be a callback function, function you want to “call back” inside that eatFood() function. The function we will pass in will be washTheDishes() function. The washTheDishes() function, will log a message about washing dishes in 1-second intervals, for five seconds.

The eatFood() function will log a message about what food we are eating. When we are done with eating, we will call the callback function. In this case, the washTheDishes() function.

// Create washTheDishes function
// This function will be used as a callback function
function washTheDishes() {
  // Wash the dishes, 1 plate per second
  let washingInterval = setInterval(() => {
    console.log('Washing the dishes...')
  }, 1000)

  // After 5 seconds
  setTimeout(() => {
    // Stop washing dishes
    clearInterval(washingInterval)

    // Show message
    console.log('Dishes are clean!')
  }, 5000)
}


// Create eatFood function
// This function will take two parameters - food and callback function
function eatFood(food, callbackFunc) {
  // Eat the food
  console.log(`Eating ${food}.`)

  // HERE IS THE CALLBACK FUNCTION:
  // Call the callback function (function passed as an argument)
  callbackFunc()
}

// Call eatFood function
// passing 'steak', and washTheDishes function as arguments
eatFood('steak', washTheDishes)
// 'Eating steak.'
// 'Washing the dishes...'
// 'Washing the dishes...'
// 'Washing the dishes...'
// 'Washing the dishes...'
// 'Washing the dishes...'
// 'Washing the dishes...'
// 'Dishes are clean!'

This is how callback functions look like, and work, in a nutshell. One function, passed into another function, that is called later from that another function. Another “mysterious” thing in the world of JavaScript functions that is simpler than it may sound.

Arrow functions

Arrow functions are the latest addition to the world of JavaScript functions. Arrow functions were added to JavaScript in ES6 specification. Since then, they got a lot of traction. Some JavaScript developers love them, some hate them. This relationship is very similar to JavaScript classes.

Some developers prefer arrow functions over regular JavaScript function because they use simple and concise syntax. This is also one reason some developers hate arrow functions. One argument against arrow function is that they are hard to read. There is some truth on this. The syntax of arrow functions is really short and simple.

It consists of parenthesis (for parameters), equal and right angle sign (=> or arrow), and curly brackets (for block of code), i.e. () => { someExpression }. Well, the parenthesis and curly brackets are actually optional. You don’t have to use parenthesis if arrow function takes one parameter. And, if arrow function is a one-liner, you don’t have to use curly brackets.

If, on the other hand, arrow function takes either no or two or more parameters the parenthesis around parameters are required. Omitting them will cause a syntax error. The same for curly brackets. If arrow function is a multi-line the curly braces are required. So, the only thing that is really required is the =>, arrow.

So far, you can create arrow functions only with function expressions, i.e. let myFunc = () => someExpression. Function declaration will not work, i.e. something like myFunc() => { someExpression } will cause syntax error. Note: we already used arrow functions in the example with washTheDishes() function, section “callback functions”. Hint: look at the setInterval and setTimeout.

// Create multi-line arrow function without any parameters
let myArrowFunc = () => {
  // ... some code
}


// Create multi-line arrow function with one parameter
let myArrowFunc = (param) => {
  // ... some code
}

// or
// Parenthesis are optional with one parameter
let myArrowFunc = param => {
  // ... some code
}

// Similar to "standard" function
let myArrowFunc = function() {
  // ... some code
}


// Create multi-line arrow function with multiple parameters
let myArrowFunc = (paramOne, paramTwo, paramThree) => {
  // ... some code
}


// Create one-line arrow function without any parameters
let myArrowFunc = () => // ... some code

// Is the same as:
let myArrowFunc = () => {/* ... some code */}


// Create one-line arrow function with one parameter
let myArrowFunc = param => // ... some code

// Is the same as:
let myArrowFunc = param => {/* ... some code */}


// Create arrow function with multiple parameters
let myArrowFunc = (paramOne, paramTwo, paramThree) => // ... some code

// Is the same as:
let myArrowFunc = (paramOne, paramTwo, paramThree) => {/* ... some code */}

Single-line and multi-line arrow functions

One interesting thing on arrow functions is that you can omit the curly brackets if the function is single-line. If it is single-line, the function will automatically evaluates the expression, the right side. You can imagine a return statement right after the arrow symbol, i.e. let myArrowFunc = () => return ..., but don’t use it literally.

This is important to remember when you use arrow functions. When you accidentally use a one-liner arrow function, and add return statement, JavaScript will throw a syntax error: SyntaxError: Unexpected token. You can use the return statement only if arrow function is a multi-line.

// This - single-line and implicit return
let myArrowFunc = () => /* ... some code */

// Is similar to this - multi-line and explicit return
let myArrowFunc = () => {
  return // ... some code
}


// This works - single-line and no explicit return
let myArrowFunc = () => /* ... some code */

// This also works - multi-line + return
let myArrowFunc = () => {
  return // ... some code
}

// This also works - no return at all
let myArrowFunc = () => {
  // ... some code
}


// This doesn't work - single-line and explicit return
let myArrowFunc = () => return /* ... some code */

Immediately-invoked arrow functions

Similarly to “standard” JavaScript functions, arrow functions can be also created as immediately-invoked. All you need to do is omit the function keyword and add the arrow symbol (=>), i.e. (() => {})(). When you use immediately-invoked arrow functions you have to put the last pair of parenthesis, for calling the function, outside the wrapping parenthesis.

If you try to put those parenthesis inside it, right after the closing curly bracket, JavaScript will throw a syntax error. So, no (() => {}()). The same will happen if you use ! (NOT operator) or + (unary plus). Both will lead to an error. Hence, the only valid way to create a immediately-invoked arrow function is using the wrapping parenthesis, and keeping the invoking parenthesis outside wrapping parenthesis.

// Immediately-invoked arrow function
// This will work
(() => {/* some code */})()


// This will not work - invoking parenthesis inside wrapping parenthesis
(() => {/* some code */}())

// This will also not work - unary plus
+() => {/* some code */}()

// This will also not work - NOT operator
!() => {/* some code */}()

Arrow functions and this

Another significant difference between “standard” JavaScript functions and arrow functions is a lack of this. When you use JavaScript functions, the value of this will depend on how you called that function. 

In case you are using strict mode, the value of this will be undefined. If you called the function inside an object, as an object method, the value of this will be the base object. The same happens if you called the function inside a class, as a class method. Then, the value of this will be the base class.

This doesn’t apply to arrow functions. Arrow functions don’t have their own this. They have a “lexical scope”. When you try to access this inside an arrow function, an arrow function will search for the value of this in its enclosing scope. Put simply, no matter how you call them, arrow functions always inherit this from the outside.

// 'this' in functions example
// Create Function constructor
function MyFunctionConstructor() {
  // Add some property
  this.name = 'My Function Constructor'

  // Log this
  console.log(this)
}

// Create instance of Function constructor
const myFunc = new MyFunctionConstructor()

// Create arrow function
const myArrowFunc = () => {
  // Log this
  console.log(this)
}

// Call myFunc instance
myFunc
// MyFunctionConstructor {name: 'My Function Constructor'}

// Call myArrowFunc
myArrowFunc()
// Window


// 'this' in object example
// Create object with title and names properties and one function
// that will loop over names and return a short message with current name and the title of the object

// ! This will not work: using "standard" function inside forEach()
// This will not work because function in forEach
// has its own 'this' that defaults to 'undefined'
const obj = {
  title: 'My object',
  names: ['Tony', 'Cindy', 'Trevor'],
  logNames() {
    this.names.forEach(function(name) {
      // This WILL NOT work:
      // TypeError: Cannot read property 'title' of undefined
      // 'this' here will be 'undefined'
      // So, 'this.title' will throw an error
      console.log(`The name of object "${this.title}" is ${name}.`)
    })
  }
}

obj.logNames()
// TypeError: Cannot read property 'title' of undefined (in "${this.title}")


// This will work: using arrow function inside forEach()
const obj = {
  title: 'My object',
  names: ['Tony', 'Cindy', 'Trevor'],
  logNames() {
    // This WILL work:
    this.names.forEach((name) => {
      // 'this' here will be the base object - obj variable
      // So, 'this.title' will correctly return 'My object'
      console.log(`The name of object "${this.title}" is ${name}.`)
    })
  }
}

obj.logNames()
// 'The name of object "My object" is Tony.'
// 'The name of object "My object" is Cindy.'
// 'The name of object "My object" is Trevor.'


// One more object example:
// This will also NOT work because arrow function does not have
// its own this - it inherits it from parent (function) context (global object).
const obj = {
  title: 'My object',
  // Use arrow function as object method
  logTitle: () => {
    // Log the title
    console.log(this.title)
  }
}

obj.logTitle()
// TypeError: Cannot read property 'title' of undefined

// This WILL work
// 'this' here, inside standard function in an object,
// will refer to the 'obj' itself, which has 'title' property
const obj = {
  title: 'My object',
  // Use standard function as object method
  logTitle: function() {
    // Log the title
    console.log(this.title)
  }
}

obj.logTitle()
// 'My object'


// 'this' in class example
// Create a class Person with two properties, name and languages
// and one method that will loop over languages and return a short message with person's name and current language

// ! This will not work for the same reason as mentioned in the previous example:
// This will not work because function in forEach
// has its own 'this' that defaults to 'undefined'
class Person {
  constructor(name, languages) {
    this.name = name
    this.languages = languages
  }

  sayHi() {
    this.languages.forEach(function(language) {
      // This WILL NOT work:
      // TypeError: Cannot read property 'name' of undefined
      // 'this' here will be again 'undefined'
      // So, 'this.name' will throw an error
      console.log(`Hi, my name is ${this.name} and I like ${language}.`)
    })
  }
}

// Create instance of Person class
const matthew = new Person('Matthew', ['JavaScript', 'Python', 'C++'])

// Call sayHi() method
matthew.sayHi()
// TypeError: Cannot read property 'name' of undefined


// This will work: using arrow function inside forEach()
// Create Person class
class Person {
  constructor(name, languages) {
    this.name = name
    this.languages = languages
  }

  sayHi() {
    this.languages.forEach((language) => {
      console.log(`Hi, my name is ${this.name} and I like ${language}.`)
    })
  }
}

// Create instance of Person class
const matthew = new Person('Matthew', ['JavaScript', 'Python', 'C++'])

// Call sayHi() method
matthew.sayHi()
// 'Hi, my name is Matthew and I like JavaScript.'
// 'Hi, my name is Matthew and I like Python.'
// 'Hi, my name is Matthew and I like C++.'

In the examples above, you can see that the value of this in arrow function is always the value of this in the outer scope. In the first example, it is a Window object, or global this. In the second example, the value of this is the obj object. Lastly, in the third example, the value of this is the Person class.

The fact that arrow functions don’t have their own this also means you can’t use them as Function constructor, such as the MyFunctionConstructor() in the example above.

Original article source at https://blog.alexdevero.com

#javascript #js #programming 

Everything You Need To Know About JavaScript Functions
Billy Chandler

Billy Chandler

1653899567

JavaScript vs JSON | Parse JSON with JavaScript in Node.js Projects

JSON, or JavaScript Object Notation, is all around us. If you've ever used a web app, there's a very good chance that it used JSON to structure, store, and transmit data between its servers and your device.

In this article, we'll briefly go over the differences between JSON and JavaScript, then jump into different ways to parse JSON with JavaScript in the browser and in Node.js projects.

Differences between JSON and JavaScript

While JSON looks like regular JavaScript, it's better to think of JSON as a data format, similar to a text file. It just so happens that JSON is inspired by JavaScript syntax, which is why they look so similar.

Let's take a look at JSON objects and JSON arrays and compare them to their JavaScript counterparts.

JSON objects vs JavaScript Object Literals

First, here's a JSON object:

{
  "name": "Jane Doe",
  "favorite-game": "Stardew Valley",
  "subscriber": false
}

jane-profile.json

The main difference between a JSON object and a regular JavaScript object – also called an object literal – comes down to the quotation marks. All the keys and string type values in a JSON object have to be wrapped in double quotation marks (").

JavaScript object literals are a bit more flexible. With object literals, you don't need to wrap keys and strings in double quotation marks. Instead, you could use single quotation marks ('), or not use any type of quotation mark for the keys.

Here's what the code above might look like as a JavaScript object literal:

const profile = {
  name: 'Jane Doe',
  'favorite-game': 'Stardew Valley',
  subscriber: false
}

Note that the key 'favorite-game' is wrapped in single quotes. With object literals, you'll need to wrap keys where the words are separated by dashes (-) in quotes.

If you'd like to avoid quotation marks, you could rewrite the key to use camel case (favoriteGame) or separate the words with an underscore (favorite_game) instead.

JSON arrays vs JavaScript arrays

JSON arrays work pretty much the same way as arrays in JavaScript, and can contain strings, booleans, numbers, and other JSON objects. For example:

[
  {
    "name": "Jane Doe",
    "favorite-game": "Stardew Valley",
    "subscriber": false
  },
  {
    "name": "John Doe",
    "favorite-game": "Dragon Quest XI",
    "subscriber": true
  }
]

profiles.json

Here's what that might look like in plain JavaScript:

const profiles = [
  {
    name: 'Jane Doe',
    'favorite-game': 'Stardew Valley',
    subscriber: false
  },
  {
    name: 'John Doe',
    'favorite-game': 'Dragon Quest XI',
    subscriber: true
  }
];

JSON as a string

You might be wondering, if there are JSON objects and arrays, couldn't you use it in your program like a regular JavaScript object literal or array?

The reason why you can't do this is that JSON is really just a string.

For example, when you write JSON in a separate file like with jane-profile.json or profiles.json above, that file actually contains text in the form of a JSON object or array, which happens to look like JavaScript.

And if you make a request to an API, it'll return something like this:

{"name":"Jane Doe","favorite-game":"Stardew Valley","subscriber":false}

Just like with text files, if you want to use JSON in your project, you'll need to parse or change it into something your programming language can understand. For instance, parsing a JSON object in Python will create a dictionary.

With that understanding, let's look at different ways to parse JSON in JavaScript.

How to parse JSON in the browser

If you're working with JSON in the browser, you're probably receiving or sending data through an API.

Let's take a look at a couple of examples.

How to parse JSON with fetch

The easiest way to get data from an API is with fetch, which includes the .json() method to parse JSON responses into a usable JavaScript object literal or array automagically.

Here's some code that uses fetch to make a GET request for a developer-themed joke from the free Chuck Norris Jokes API:

fetch('https://api.chucknorris.io/jokes/random?category=dev')
  .then(res => res.json()) // the .json() method parses the JSON response into a JS object literal
  .then(data => console.log(data));

If you run that code in the browser, you'll see something like this logged to the console:

{
    "categories": ["dev"],
    "created_at": "2020-01-05 13:42:19.324003",
    "icon_url": "https://assets.chucknorris.host/img/avatar/chuck-norris.png",
    "id": "elgv2wkvt8ioag6xywykbq",
    "updated_at": "2020-01-05 13:42:19.324003",
    "url": "https://api.chucknorris.io/jokes/elgv2wkvt8ioag6xywykbq",
    "value": "Chuck Norris's keyboard doesn't have a Ctrl key because nothing controls Chuck Norris."
}

While that looks like a JSON object, it's really a JavaScript object literal, and you can use it freely in your program.

How to stringify JSON with JSON.stringify()

But what if you want to send data to an API?

For instance, say you'd like to send a Chuck Norris joke to the Chuck Norris Jokes API so other people can read it later.

First, you'd write your joke as a JS object literal:

const newJoke = {
  categories: ['dev'],
  value: "Chuck Norris's keyboard is made up entirely of Cmd keys because Chuck Norris is always in command."
};

Then, since you're sending data to an API, you'd need to turn your newJoke object literal into a JSON string.

Fortunately, JavaScript includes a super helpful method to do just that – JSON.stringify():

const newJoke = {
  categories: ['dev'],
  value: "Chuck Norris's keyboard is made up entirely of Cmd keys because Chuck Norris is always in command."
};

console.log(JSON.stringify(newJoke)); // {"categories":["dev"],"value":"Chuck Norris's keyboard is made up entirely of Cmd keys because Chuck Norris is always in command."}

console.log(typeof JSON.stringify(newJoke)); // string

While we're converting an object literal into a JSON string in this example, JSON.stringify() also works with arrays.

Finally, you'd just need to send your JSON stringified joke back to the API with a POST request.

Note that the Chuck Norris Jokes API doesn't actually have this feature. But if it did, here's what the code might look like:

const newJoke = {
  categories: ['dev'],
  value: "Chuck Norris's keyboard is made up entirely of Cmd keys because Chuck Norris is always in command."
};

fetch('https://api.chucknorris.io/jokes/submit', { // fake API endpoint
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(newJoke), // turn the JS object literal into a JSON string
})
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(err => {
    console.error(err);
  });

And just like that, you've parsed incoming JSON with fetch and used JSON.stringify() to convert a JS object literal into a JSON string.

How to work with local JSON files in the browser

Unfortunately, it's not possible (or advisable) to load a local JSON file in the browser.

fetch will throw an error if you try to load a local file. For example, say you have a JSON file with some jokes:

[
  {
    "categories": ["dev"],
    "created_at": "2020-01-05 13:42:19.324003",
    "icon_url": "https://assets.chucknorris.host/img/avatar/chuck-norris.png",
    "id": "elgv2wkvt8ioag6xywykbq",
    "updated_at": "2020-01-05 13:42:19.324003",
    "url": "https://api.chucknorris.io/jokes/elgv2wkvt8ioag6xywykbq",
    "value": "Chuck Norris's keyboard doesn't have a Ctrl key because nothing controls Chuck Norris."
  },
  {
    "categories": ["dev"],
    "created_at": "2020-01-05 13:42:19.324003",
    "icon_url": "https://assets.chucknorris.host/img/avatar/chuck-norris.png",
    "id": "ae-78cogr-cb6x9hluwqtw",
    "updated_at": "2020-01-05 13:42:19.324003",
    "url": "https://api.chucknorris.io/jokes/ae-78cogr-cb6x9hluwqtw",
    "value": "There is no Esc key on Chuck Norris' keyboard, because no one escapes Chuck Norris."
  }
]

jokes.json

And you want to parse it and create a list of jokes on a simple HTML page.

If you create a page with the following and open it in your browser:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width" />
    <title>Fetch Local JSON</title>
  </head>
  <script>
    fetch("./jokes.json", { mode: "no-cors" }) // disable CORS because path does not contain http(s)
      .then((res) => res.json())
      .then((data) => console.log(data));
  </script>
</html>

index.html

You'll see this in the console:

Fetch API cannot load file://<path>/jokes.json. URL scheme "file" is not supported

By default, browsers don't allow access to local files for security reasons. This is a good thing, and you shouldn't try to work around this behavior.

Instead, the best thing to do is to convert the local JSON file into JavaScript. Fortunately, this is pretty easy since JSON syntax is so similar to JavaScript.

All you need to do is create a new file and declare your JSON as a variable:

const jokes = [
  {
    "categories": ["dev"],
    "created_at": "2020-01-05 13:42:19.324003",
    "icon_url": "https://assets.chucknorris.host/img/avatar/chuck-norris.png",
    "id": "elgv2wkvt8ioag6xywykbq",
    "updated_at": "2020-01-05 13:42:19.324003",
    "url": "https://api.chucknorris.io/jokes/elgv2wkvt8ioag6xywykbq",
    "value": "Chuck Norris's keyboard doesn't have a Ctrl key because nothing controls Chuck Norris."
  },
  {
    "categories": ["dev"],
    "created_at": "2020-01-05 13:42:19.324003",
    "icon_url": "https://assets.chucknorris.host/img/avatar/chuck-norris.png",
    "id": "ae-78cogr-cb6x9hluwqtw",
    "updated_at": "2020-01-05 13:42:19.324003",
    "url": "https://api.chucknorris.io/jokes/ae-78cogr-cb6x9hluwqtw",
    "value": "There is no Esc key on Chuck Norris' keyboard, because no one escapes Chuck Norris."
  }
]

jokes.js

And add it to your page as a separate script:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width" />
    <title>Fetch Local JSON</title>
  </head>
  <script src="jokes.js"></script>
  <script>
    console.log(jokes);
  </script>
</html>

You'll be able to use the jokes array freely in your code.

You could also use JavaScript modules to do the same thing, but that's a bit outside the scope of this article.

But what if you want to work with local JSON files and have Node.js installed? Let's take a look at how to do that now.

How to parse JSON in Node.js

Node.js is a JavaScript runtime that allows you to run JavaScript outside of the browser. You can read all about Node.js here.

Whether you use Node.js to run code locally on your computer, or to run entire web applications on a server, it's good to know how to work with JSON.

For the following examples, we'll use the same jokes.json file:

[
  {
    "categories": ["dev"],
    "created_at": "2020-01-05 13:42:19.324003",
    "icon_url": "https://assets.chucknorris.host/img/avatar/chuck-norris.png",
    "id": "elgv2wkvt8ioag6xywykbq",
    "updated_at": "2020-01-05 13:42:19.324003",
    "url": "https://api.chucknorris.io/jokes/elgv2wkvt8ioag6xywykbq",
    "value": "Chuck Norris's keyboard doesn't have a Ctrl key because nothing controls Chuck Norris."
  },
  {
    "categories": ["dev"],
    "created_at": "2020-01-05 13:42:19.324003",
    "icon_url": "https://assets.chucknorris.host/img/avatar/chuck-norris.png",
    "id": "ae-78cogr-cb6x9hluwqtw",
    "updated_at": "2020-01-05 13:42:19.324003",
    "url": "https://api.chucknorris.io/jokes/ae-78cogr-cb6x9hluwqtw",
    "value": "There is no Esc key on Chuck Norris' keyboard, because no one escapes Chuck Norris."
  }
]

jokes.json

How to parse a JSON file with require()

Let's start with the easiest method.

If you have a local JSON file, all you need to do is use require() to load it like any other Node.js module:

const jokes = require('./jokes.json');

The JSON file will be parsed for you automatically and you can start using it in your project:

const jokes = require('./jokes.json');

console.log(jokes[0].value); // "Chuck Norris's keyboard doesn't have a Ctrl key because nothing controls Chuck Norris."

Note that this is synchronous, meaning that your program will stop until it parses the entire file before continuing. Really large JSON files can cause your program to slow down, so just be careful with that.

Also, because parsing JSON this way loads the entire thing into memory, it's better to use this method for static JSON files. If the JSON file changes while your program is running, you won't have access to those changes until you restart your program and parse the updated JSON file.

How to parse a JSON file with fs.readFileSync() and JSON.parse()

This is the more traditional way (for lack of a better term) to parse JSON files in Node.js projects – read the file with fs (file system) module, then parse with JSON.parse().

Let's see how to do this with the fs.readFileSync() method. First, add the fs module to your project:

const fs = require('fs');

Then, create a new variable to store the output of the jokes.json file and set it equal to fs.readFileSync():

const fs = require('fs');
const jokesFile = fs.readFileSync();

fs.readFileSync() takes a couple of arguments. The first is the path to the file you want to read:

const fs = require('fs');
const jokesFile = fs.readFileSync('./jokes.json');

But if you log jokesFile to the console now, you'd see something like this:

<Buffer 5b 0a 20 20 7b 0a 20 20 20 20 22 63 61 74 65 67 6f 72 69 65 73 22 3a 20 5b 22 64 65 76 22 5d 2c 0a 20 20 20 20 22 63 72 65 61 74 65 64 5f 61 74 22 3a ... 788 more bytes>

That just means that the fs module is reading the file, but it doesn't know the encoding or format the file is in. fs can be used to load pretty much any file, and not just text-based ones like JSON, so we need to tell it how the file is encoded.

For text-based files, the encoding is usually utf8:

const fs = require('fs');
const jokesFile = fs.readFileSync('./jokes.json', 'utf8');

Now if you log jokesFile to the console, you'll see the contents of the file.

But so far we're just reading the file, and it's still a string. We'll need to use another method to parse jokesFile into a usable JavaScript object or array.

To do that, we'll use JSON.parse():

const fs = require('fs');
const jokesFile = fs.readFileSync('./jokes.json', 'utf8');
const jokes = JSON.parse(jokesFile);

console.log(jokes[0].value); // "Chuck Norris's keyboard doesn't have a Ctrl key because nothing controls Chuck Norris."

As the name suggests, JSON.parse() takes a JSON string and parses it into a JavaScript object literal or array.

Like with the require method above, fs.readFileSync() is a synchronous method, meaning it could cause your program to slow down if it's reading a large file, JSON or otherwise.

Also, it only reads the file once and loads it into memory. If the file changes, you'll need to read the file again at some point. To make things easier, you might want to create a simple function to read files.

Here's what that might look like:

const fs = require('fs');
const readFile = path => fs.readFileSync(path, 'utf8');

const jokesFile1 = readFile('./jokes.json');
const jokes1 = JSON.parse(jokesFile1);

console.log(jokes1[0].value); // "Chuck Norris's keyboard doesn't have a Ctrl key because nothing controls Chuck Norris."

// the jokes.json file changes at some point

const jokesFile2 = readFile('./jokes.json');
const jokes2 = JSON.parse(jokesFile2);

console.log(jokes2[0].value); // "Chuck Norris's keyboard is made up entirely of Cmd keys because Chuck Norris is always in command."

How to parse JSON with fs.readFile() and JSON.parse()

The fs.readFile() method is very similar to fs.readFileSync(), except that it works asynchronously. This is great if you have a large file to read and you don't want it to hold up the rest of your code.

Here's a basic example:

const fs = require('fs');

fs.readFile('./jokes.json', 'utf8');

So far this looks similar to what we did with fs.readFileSync(), except we're not assigning it to a variable like jokesFile. Because it's asynchronous, any code after fs.readFile() it will run before it's finished reading the file.

Instead, we'll use a callback function and parse the JSON inside it:

const fs = require('fs');

fs.readFile('./jokes.json', 'utf8', (err, data) => {
  if (err) console.error(err);
  const jokes = JSON.parse(data);

  console.log(jokes[0].value);
});

console.log("This will run first!");

Which prints the following to the console:

This will run first!
Chuck Norris's keyboard doesn't have a Ctrl key because nothing controls Chuck Norris.

Like with fs.readFileSync(), fs.readFile() loads the file into memory, meaning you'll need to read the file again if it changes.

Also, even though fs.readFile() is asynchronous, it eventually loads the entire file it's reading into memory. If you have a massive file, it may be better to look into Node.js streams instead.

How to stringify JSON with JSON.stringify() in Node.js

Finally, if you're parsing JSON with Node.js, there's a good chance that you'll need to return JSON at some point, maybe as an API response.

Luckily, this works the same way as in the browser – just use JSON.stringify() to convert JavaScript object literals or arrays into a JSON string:

const newJoke = {
  categories: ['dev'],
  value: "Chuck Norris's keyboard is made up entirely of Cmd keys because Chuck Norris is always in command."
};

console.log(JSON.stringify(newJoke)); // {"categories":["dev"],"value":"Chuck Norris's keyboard is made up entirely of Cmd keys because Chuck Norris is always in command."}

And that's it! We've covered just about everything you need to know about working with JSON in the browser and in Node.js projects.

Original article source at https://www.freecodecamp.org

#javascript #json #js #programming #node #nodejs 

JavaScript vs JSON | Parse JSON with JavaScript in Node.js Projects

Bucles JavaScript | JavaScript For Loop: explicado con ejemplos

Los bucles son un concepto de programación que encontramos e implementamos constantemente como desarrolladores de JavaScript.

Y muchos desarrolladores están familiarizados con los bucles, pero no todos entienden cómo funcionan y por qué o cuándo deben usar un tipo específico de bucle.

En este artículo, aprenderemos qué son los bucles for, cómo funcionan y por qué los usamos. También tendremos en cuenta que existen varios tipos de bucles, cada uno de los cuales realiza una función específica aunque casi todos pueden realizar la misma función común.

¿Qué son los bucles?

Los bucles son programas informáticos que ejecutan un conjunto de instrucciones o un bloque de código una determinada cantidad de veces sin tener que volver a escribirlo hasta que se cumple una determinada condición. En otras palabras, los bucles permiten que su código ejecute una o más declaraciones tantas veces como desee.

Una vez más, hay muchos tipos de bucles, pero en este artículo solo veremos el bucle for.

Casi todos los lenguajes de programación de alto nivel, incluido JavaScript, tienen un bucle for. Solo vamos a ver JavaScript en este artículo, y veremos su sintaxis y algunos ejemplos.

Para bucles en JavaScript

El bucle for es una declaración iterativa que se utiliza para verificar ciertas condiciones y luego ejecutar repetidamente un bloque de código siempre que se cumplan esas condiciones.

s_3315FAFA14C012362B87C753E4A1C2D25C00228882CEE2A5B63A9FDA99BA4B77_1653509464069_for+bucle+diagrama de flujo+1

Diagrama de flujo para el ciclo for

Sintaxis de un bucle for

for (initialExpression; condition; updateExpression) {
    // for loop body: statement
}

El bloque de código anterior es la sintaxis estándar utilizada por for loop. Veamos cada parámetro para ver qué significa y qué hace:

  • initialExpression: Esto se usa para establecer el valor de una variable de contador, y solo se evalúa una vez, antes de que comience el bucle. Dependiendo del alcance, estas variables de contador generalmente se declaran con las palabras clave varo let.
  • condition: Esta es una expresión de evaluación constante que determina si se debe ejecutar el bucle. En términos simples, si esta condición devuelve verdadero, se ejecuta el bloque de código del bucle for. Si devuelve falso, el bucle for finaliza.
  • updateExpression: Esto se usa comúnmente para actualizar o incrementar la initialExpressionvariable del contador. En otras palabras, cuando la condición es verdadera, actualiza el valor de initialExpression.

En resumen, el bucle for hace que la initialExpressionvariable, que se establece en un valor inicial, aumente o disminuya en respuesta a updateExpressionsiempre que se cumpla la condición. Finalmente, la declaración siempre se ejecutará si la condición se evalúa como verdadera.

Ejemplos de bucle for en JavaScript

En este punto, ahora entendemos qué son los bucles, así que echemos un vistazo a algunos ejemplos y veamos cómo podemos usar los bucles.

Cómo mostrar texto varias veces

Comencemos mostrando un texto varias veces hasta que se cumpla nuestra condición.

for (var i = 0; i < 3; i++) {
  let name = "John Doe";
  console.log("Hi, my name is " + name);
}

Producción:

"Hi, my name is John Doe"
"Hi, my name is John Doe"
"Hi, my name is John Doe"

Así es como el programa procesó este bucle:

IteraciónVariableCondición: i < 3Actualización de acciones y variables
yo = 0verdadero

Hola, mi nombre es John Doe está impreso.

i aumenta a 1.

2doyo = 1verdadero

Hola, mi nombre es John Doe está impreso.

i aumenta a 2.

3royo = 2verdadero

Hola, mi nombre es John Doe está impreso.

i aumenta a 3.

4toyo=3falsoEl bucle se termina.

Nota: el ciclo finaliza porque 3 no es menor que 3, por lo que devolvió false.

Cómo mostrar una secuencia de números con un bucle For

Esta vez, mostremos una secuencia de números mostrando el valor de la iteración.

for (let i = 2; i <= 5; i++) {
    console.log(i);  // printing the value of i
}

Producción:

2
3
4
5

Así es como el programa procesó este bucle:

IteraciónVariableCondición: i <= 5Actualización de acciones y variables
yo = 2verdadero

2 está impreso.

i aumenta a 3.

2doyo = 3verdadero

3 está impreso.

i aumenta a 4.

3royo = 4verdadero

4 está impreso.

i aumenta a 5.

5toyo = 5verdadero

5 está impreso.

i se incrementa a 6 .

6toyo = 6falsoEl bucle se termina.

Nota: el ciclo termina porque 6 no es menor o igual que 5, por lo que la condición devuelve falso.

Cómo mostrar una secuencia de números pares

Ahora mostremos una secuencia de números pares solo mostrando el valor de la iteración:

for (let i = 2; i <= 10; i+=2) {
    console.log(i);  // printing the value of i
}


Producción:

2
4
6
8
10

Así es como el programa procesó este bucle:

IteraciónVariableCondición: i <= 10Actualización de acciones y variables
yo = 2verdadero

2 está impreso.

i aumenta a 4.

2doyo = 4verdadero

4 está impreso.

i aumenta a 6.

3royo = 6verdadero

6 está impreso.

i aumenta a 8.

5toyo = 8verdadero

8 está impreso.

i aumenta a 10.

6toyo = 10verdadero

10 está impreso.

i aumenta a 12.

7moyo = 12falsoEl bucle se termina.

Supongamos que queremos obtener los números impares. Todo lo que tenemos que hacer es cambiar el initialExpressiona igual 1o cualquier número impar desde el que deseamos comenzar como se ve a continuación

for (let i = 1; i <= 10; i+=2) {
    console.log(i);  // printing the value of i
}

Cómo interrumpir una operación de bucle For

Hasta ahora, hemos visto cómo crear un bucle for, pero también es importante mencionar que podemos salir de un bucle usando break. La instrucción break se usa para terminar el ciclo inmediatamente cuando se encuentra.

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

Producción:

1
2
3
4

Cómo mostrar la suma de números naturales

Recorramos ahora del 1 al 10 y luego agreguemos estos números a medida que aumenta la iteración:

let sum = 0;

for (let i = 1; i <= 10; i++) {
    sum += i;  // This is same as: sum = sum + i
}

console.log('The sum of 1 to 10 is: ', sum); // "The sum of 1 to 10 is:  55"

Nota: estamos agregando console.log(…)fuera del bucle, por lo que solo nos da la salida final cuando finaliza el bucle.

También podemos decidir usar variables para establecer el número máximo de nuestra condición de esta manera:

let sum = 0;
let n = 10;

for (let i = 1; i <= n; i++) {
    sum += i;  // this is same as: sum = sum + i
}

console.log('The sum of 1 to 10 is: ', sum); // "The sum of 1 to 10 is:  55"

Cómo realizar bucles infinitos con un bucle For

Esto puede bloquear su sistema, porque continúa ejecutándose hasta que la memoria está llena, ya que la condición siempre se evalúa como verdadera.

for(let i = 1; i > 0; i++) {
    // block of code
}

Cómo recorrer una matriz para verificar números pares e impares

La mayoría de las veces trabajará con matrices, así que veamos cómo podemos recorrer una matriz de números para generar todos los números pares e impares:

var numbers = [1, 4, 44, 64, 55, 24, 32, 55, 19, 17, 74, 22, 23];
var evenNumbers = [];
var oddNumbers = [];

for (var i = 0; i < numbers.length; i++) {
    if (numbers[i] % 2 != 1) {
        evenNumbers.push(numbers[i]);
    } else {
        oddNumbers.push(numbers[i]);
    }
}

console.log("The even numbers are: " + evenNumbers); // "The even numbers are: 4,44,64,24,32,74,22"
console.log("The odd numbers are: " + oddNumbers); // "The odd numbers are: 1,55,55,19,17,23"

Cómo recorrer una matriz de números para obtener el número máximo y mínimo

Finalmente, antes de redondear este artículo, veamos cómo obtener el número máximo y mínimo de una matriz con bucle for:

Máximo:

var numbers = [1, 4, 44, 64, 55, 24, 32, 55, 19, 17, 74, 22, 23];
var max = 0;

for (var i = 0; i < numbers.length; i++) {
    if (numbers[i] > max) {
        max = numbers[i];
    }
}

console.log(max); // 74

Mínimo:

var numbers = [4, 44, 64, 55, 24, 32, 55, 19, 17, 74, 22, 23];
var min = numbers[0];

for (var i = 0; i < numbers.length; i++) {
    if (numbers[i] < min) {
        min = numbers[i];
    }
}

console.log(min); // 4

Conclusión

En este artículo, aprendimos qué es un bucle de JavaScript y vimos algunos ejemplos.

Es importante comprender que hay muchos otros tipos de bucles, incluido el bucle while, que se utiliza mejor cuando no se conoce el número de iteraciones. De lo contrario, siempre use el bucle for cuando sepa el número de iteraciones.

Fuente del artículo original en https://www.freecodecamp.org

#javascript #js

Bucles JavaScript | JavaScript For Loop: explicado con ejemplos

Циклы JavaScript | JavaScript For Loop — объяснение с примерами

Циклы — это концепция программирования, с которой мы постоянно сталкиваемся и реализуем как разработчики JavaScript.

И многие разработчики знакомы с циклами, но не все понимают, как они работают и почему или когда они должны использовать определенный тип цикла.

В этой статье мы узнаем, что такое циклы for, как они работают и почему мы их используем. Мы также будем помнить, что существует несколько типов циклов, каждый из которых выполняет определенную функцию, хотя почти все они могут выполнять одну и ту же общую функцию.

Что такое петли?

Циклы — это компьютерные программы, которые выполняют набор инструкций или блок кода определенное количество раз без необходимости его повторной записи до тех пор, пока не будет выполнено определенное условие. Другими словами, циклы позволяют вашему коду выполнять одну или несколько инструкций столько раз, сколько необходимо.

Опять же, существует множество типов циклов, но в этой статье мы рассмотрим только цикл for.

Почти каждый язык программирования высокого уровня, включая JavaScript, имеет цикл for. В этой статье мы рассмотрим только JavaScript, рассмотрим его синтаксис и несколько примеров.

Для циклов в JavaScript

Цикл for — это итеративный оператор, который вы используете для проверки определенных условий, а затем многократно выполняете блок кода, пока эти условия выполняются.

s_3315FAFA14C012362B87C753E4A1C2D25C00228882CEE2A5B63A9FDA99BA4B77_1653509464069_for+цикл+блок-схема+1

Блок-схема цикла for

Синтаксис цикла for

for (initialExpression; condition; updateExpression) {
    // for loop body: statement
}

Приведенный выше блок кода представляет собой стандартный синтаксис, используемый циклом for. Давайте посмотрим на каждый параметр, чтобы увидеть, что он означает и что он делает:

  • initialExpression: используется для установки значения переменной-счетчика и оценивается только один раз перед запуском цикла. В зависимости от области действия эти переменные-счетчики обычно объявляются с ключевыми словами varили let.
  • condition: Это константное выражение, определяющее, должен ли выполняться цикл. Проще говоря, если это условие возвращает true, выполняется блок кода цикла for. Если он возвращает false, цикл for завершается.
  • updateExpression: обычно используется для обновления или увеличения initialExpressionпеременной счетчика. Другими словами, когда условие истинно, оно обновляет значение initialExpression.

Таким образом, цикл for заставляет initialExpressionпеременную, для которой установлено начальное значение, увеличиваться или уменьшаться в ответ на то updateExpression, пока выполняется условие. Наконец, оператор всегда будет выполняться, если условие оценивается как истинное.

Примеры цикла for в JavaScript

Теперь мы понимаем, что такое циклы, поэтому давайте рассмотрим несколько примеров и посмотрим, как мы можем использовать циклы.

Как отображать текст несколько раз

Давайте начнем с отображения некоторого текста несколько раз, пока наше условие не будет выполнено.

for (var i = 0; i < 3; i++) {
  let name = "John Doe";
  console.log("Hi, my name is " + name);
}

Выход:

"Hi, my name is John Doe"
"Hi, my name is John Doe"
"Hi, my name is John Doe"

Вот как программа обработала этот цикл:

ИтерацияПеременнаяУсловие: я < 3Обновление действий и переменных
1-йя = 0истинный

Привет, меня зовут Джон Доу печатается.

я увеличивается до 1.

2-йя = 1истинный

Привет, меня зовут Джон Доу печатается.

я увеличивается до 2.

3-йя = 2истинный

Привет, меня зовут Джон Доу печатается.

я увеличивается до 3.

4-йя=3ЛОЖЬЦикл прерывается.

Примечание . Цикл завершается, поскольку 3 не меньше 3, поэтому возвращается false.

Как отобразить последовательность чисел с помощью цикла for

На этот раз давайте отобразим последовательность чисел, отображая значение итерации.

for (let i = 2; i <= 5; i++) {
    console.log(i);  // printing the value of i
}

Выход:

2
3
4
5

Вот как программа обработала этот цикл:

ИтерацияПеременнаяУсловие: я <= 5Обновление действий и переменных
1-йя = 2истинный

2 печатается.

я увеличивается до 3.

2-йя = 3истинный

3 печатается.

я увеличивается до 4.

3-йя = 4истинный

4 печатается.

я увеличивается до 5.

5-йя = 5истинный

5 печатается.

я увеличивается до 6 .

6-йя = 6ЛОЖЬЦикл прерывается.

Примечание . Цикл завершается, поскольку 6 не меньше или равно 5, поэтому условие возвращает false.

Как отобразить последовательность четных чисел

Давайте теперь отобразим последовательность четных чисел, только отображая значение итерации:

for (let i = 2; i <= 10; i+=2) {
    console.log(i);  // printing the value of i
}


Выход:

2
4
6
8
10

Вот как программа обработала этот цикл:

ИтерацияПеременнаяУсловие: я <= 10Обновление действий и переменных
1-йя = 2истинный

2 печатается.

я увеличивается до 4.

2-йя = 4истинный

4 печатается.

я увеличивается до 6.

3-йя = 6истинный

6 печатается.

я увеличивается до 8.

5-йя = 8истинный

8 печатается.

я увеличивается до 10.

6-йя = 10истинный

10 печатается.

я увеличивается до 12.

7-йя = 12ЛОЖЬЦикл прерывается.

Предположим, мы хотим получить нечетные числа. Все, что нам нужно сделать, это изменить на initialExpressionравное 1или любое нечетное число, с которого мы хотим начать, как показано ниже .

for (let i = 1; i <= 10; i+=2) {
    console.log(i);  // printing the value of i
}

Как прервать операцию цикла for

До сих пор мы видели, как создать цикл for, но также важно упомянуть, что мы можем выйти из цикла, используя break. Оператор break используется для немедленного завершения цикла при его обнаружении.

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

Выход:

1
2
3
4

Как отобразить сумму натуральных чисел

Давайте теперь зациклимся от 1 до 10, а затем сложим эти числа вместе по мере увеличения итерации:

let sum = 0;

for (let i = 1; i <= 10; i++) {
    sum += i;  // This is same as: sum = sum + i
}

console.log('The sum of 1 to 10 is: ', sum); // "The sum of 1 to 10 is:  55"

Примечание. Мы добавляем console.log(…)вне цикла, поэтому он дает нам окончательный результат только после завершения цикла.

Мы также можем решить использовать переменные для установки максимального числа нашего условия следующим образом:

let sum = 0;
let n = 10;

for (let i = 1; i <= n; i++) {
    sum += i;  // this is same as: sum = sum + i
}

console.log('The sum of 1 to 10 is: ', sum); // "The sum of 1 to 10 is:  55"

Как выполнять бесконечные циклы с помощью цикла for

Это может привести к зависанию вашей системы, поскольку она продолжает работать до тех пор, пока память не будет заполнена, поскольку условие всегда оценивается как истинное.

for(let i = 1; i > 0; i++) {
    // block of code
}

Как пройтись по массиву, чтобы проверить наличие нечетных и четных чисел

В большинстве случаев вы будете работать с массивами, поэтому давайте посмотрим, как мы можем перебрать массив чисел, чтобы вывести все нечетные и четные числа:

var numbers = [1, 4, 44, 64, 55, 24, 32, 55, 19, 17, 74, 22, 23];
var evenNumbers = [];
var oddNumbers = [];

for (var i = 0; i < numbers.length; i++) {
    if (numbers[i] % 2 != 1) {
        evenNumbers.push(numbers[i]);
    } else {
        oddNumbers.push(numbers[i]);
    }
}

console.log("The even numbers are: " + evenNumbers); // "The even numbers are: 4,44,64,24,32,74,22"
console.log("The odd numbers are: " + oddNumbers); // "The odd numbers are: 1,55,55,19,17,23"

Как перебрать массив чисел, чтобы получить максимальное и минимальное число

Наконец, прежде чем мы завершим эту статью, давайте посмотрим, как получить максимальное и минимальное число из массива с помощью цикла for:

Максимум:

var numbers = [1, 4, 44, 64, 55, 24, 32, 55, 19, 17, 74, 22, 23];
var max = 0;

for (var i = 0; i < numbers.length; i++) {
    if (numbers[i] > max) {
        max = numbers[i];
    }
}

console.log(max); // 74

Минимум:

var numbers = [4, 44, 64, 55, 24, 32, 55, 19, 17, 74, 22, 23];
var min = numbers[0];

for (var i = 0; i < numbers.length; i++) {
    if (numbers[i] < min) {
        min = numbers[i];
    }
}

console.log(min); // 4

Вывод

В этой статье мы узнали, что такое цикл JavaScript, и рассмотрели несколько примеров.

Важно понимать, что существует много других типов циклов, в том числе цикл while, который лучше всего использовать, когда неизвестно количество итераций. В противном случае всегда используйте цикл for, если известно количество итераций.

Оригинальный источник статьи на https://www.freecodecamp.org

#javascript #js 

Циклы JavaScript | JavaScript For Loop — объяснение с примерами
Duong Tran

Duong Tran

1653719420

Vòng lặp JavaScript | JavaScript For Loop - Giải thích với các ví dụ

Vòng lặp là một khái niệm lập trình mà chúng tôi thường xuyên gặp và thực hiện với tư cách là nhà phát triển JavaScript.

Và nhiều nhà phát triển đã quen thuộc với các vòng lặp, nhưng không phải ai cũng hiểu chúng hoạt động như thế nào và tại sao hoặc khi nào họ nên sử dụng một loại vòng lặp cụ thể.

Trong bài viết này, chúng ta sẽ tìm hiểu vòng lặp for là gì, cách chúng hoạt động và tại sao chúng ta sử dụng chúng. Chúng tôi cũng sẽ lưu ý rằng có một số loại vòng lặp, mỗi loại thực hiện một chức năng cụ thể mặc dù chúng hầu như đều có thể thực hiện cùng một chức năng chung.

Vòng lặp là gì?

Vòng lặp là các chương trình máy tính thực hiện một tập hợp các lệnh hoặc một khối mã một số lần nhất định mà không cần phải viết lại cho đến khi một điều kiện nhất định được đáp ứng. Nói cách khác, các vòng lặp cho phép mã của bạn thực thi một hoặc nhiều câu lệnh nhiều lần như mong muốn.

Một lần nữa, có rất nhiều loại vòng lặp, nhưng chúng ta sẽ chỉ xem xét vòng lặp for trong bài viết này.

Hầu hết mọi ngôn ngữ lập trình cấp cao, bao gồm cả JavaScript, đều có vòng lặp for. Chúng ta sẽ chỉ xem xét JavaScript trong bài viết này, và chúng ta sẽ xem xét cú pháp của nó và một số ví dụ.

Đối với các vòng lặp trong JavaScript

Vòng lặp for là một câu lệnh lặp lại mà bạn sử dụng để kiểm tra các điều kiện nhất định và sau đó thực thi lặp đi lặp lại một khối mã miễn là các điều kiện đó được đáp ứng.

s_3315FAFA14C012362B87C753E4A1C2D25C00228882CEE2A5B63A9FDA99BA4B77_1653509464069_for + loop + flowchart + 1

Lưu đồ cho vòng lặp for

Cú pháp của vòng lặp for

for (initialExpression; condition; updateExpression) {
    // for loop body: statement
}

Khối mã ở trên là cú pháp tiêu chuẩn được sử dụng bởi vòng lặp for. Hãy xem xét từng tham số để xem ý nghĩa và tác dụng của nó:

  • initialExpression: Điều này được sử dụng để đặt giá trị của một biến đếm và nó chỉ được đánh giá một lần, trước khi vòng lặp bắt đầu. Tùy thuộc vào phạm vi, các biến bộ đếm này thường được khai báo với varhoặc lettừ khóa.
  • condition: Đây là một biểu thức đánh giá hằng số xác định xem có nên thực hiện vòng lặp hay không. Nói một cách dễ hiểu, nếu điều kiện này trả về true, thì khối mã của vòng lặp for sẽ được thực thi. Nếu nó trả về false, vòng lặp for sẽ kết thúc.
  • updateExpression: Điều này thường được sử dụng để cập nhật hoặc tăng initialExpressionbiến bộ đếm. Nói cách khác, khi điều kiện đúng, nó sẽ cập nhật giá trị của initialExpression.

Tóm lại, vòng lặp for làm cho initialExpressionbiến, được đặt thành giá trị bắt đầu, tăng hoặc giảm để đáp ứng updateExpressionmiễn là điều kiện được đáp ứng. Cuối cùng, câu lệnh, sẽ luôn được thực thi nếu điều kiện đánh giá là true.

Ví dụ về vòng lặp trong JavaScript

Tại thời điểm này, chúng ta đã hiểu vòng lặp là gì, vì vậy chúng ta hãy xem một số ví dụ và xem cách chúng ta có thể sử dụng vòng lặp.

Cách hiển thị văn bản nhiều lần

Hãy bắt đầu bằng cách hiển thị một số văn bản nhiều lần cho đến khi điều kiện của chúng ta được đáp ứng.

for (var i = 0; i < 3; i++) {
  let name = "John Doe";
  console.log("Hi, my name is " + name);
}

Đầu ra:

"Hi, my name is John Doe"
"Hi, my name is John Doe"
"Hi, my name is John Doe"

Đây là cách chương trình xử lý vòng lặp này:

Sự lặp lạiBiến đổiĐiều kiện: i <3Cập nhật hành động và biến
Ngày 1i = 0thật

Xin chào, tên tôi là John Doe đã được in.

tôi được tăng lên 1.

lần 2i = 1thật

Xin chào, tên tôi là John Doe đã được in.

tôi được tăng lên 2.

lần thứ 3i = 2thật

Xin chào, tên tôi là John Doe đã được in.

tôi được tăng lên 3.

lần thứ 4i = 3saiVòng lặp được kết thúc.

Lưu ý: Vòng lặp được kết thúc vì 3 không nhỏ hơn 3, vì vậy nó được trả về false.

Cách hiển thị một dãy số với vòng lặp For

Lần này, hãy hiển thị một chuỗi số bằng cách hiển thị giá trị lặp.

for (let i = 2; i <= 5; i++) {
    console.log(i);  // printing the value of i
}

Đầu ra:

2
3
4
5

Đây là cách chương trình xử lý vòng lặp này:

Sự lặp lạiBiến đổiĐiều kiện: i <= 5Cập nhật hành động và biến
Ngày 1i = 2thật

2 được in.

tôi được tăng lên 3.

lần 2i = 3thật

3 được in.

tôi được tăng lên 4.

lần thứ 3i = 4thật

4 được in.

tôi được tăng lên 5.

ngày 5i = 5thật

5 được in.

tôi được tăng lên 6 .

Ngày 6i = 6saiVòng lặp được kết thúc.

Lưu ý: Vòng lặp bị kết thúc vì 6 không nhỏ hơn hoặc bằng 5, do đó điều kiện trả về false.

Cách hiển thị dãy số chẵn

Bây giờ chúng ta hãy hiển thị một chuỗi các số chẵn chỉ bằng cách hiển thị giá trị lặp lại:

for (let i = 2; i <= 10; i+=2) {
    console.log(i);  // printing the value of i
}


Đầu ra:

2
4
6
8
10

Đây là cách chương trình xử lý vòng lặp này:

Sự lặp lạiBiến đổiĐiều kiện: i <= 10Cập nhật hành động và biến
Ngày 1i = 2thật

2 được in.

tôi được tăng lên 4.

lần 2i = 4thật

4 được in.

tôi được tăng lên 6.

lần thứ 3i = 6thật

6 được in.

tôi được tăng lên 8.

ngày 5i = 8thật

8 được in.

tôi được tăng lên 10.

Ngày 6i = 10thật

10 được in.

tôi được tăng lên 12.

thứ 7i = 12saiVòng lặp được kết thúc.

Giả sử chúng ta muốn lấy các số lẻ. Tất cả những gì chúng ta phải làm là thay đổi thành số initialExpressionbằng 1hoặc bất kỳ số lẻ nào mà chúng ta muốn bắt đầu từ đó như hình dưới đây

for (let i = 1; i <= 10; i+=2) {
    console.log(i);  // printing the value of i
}

Làm thế nào để phá vỡ một hoạt động vòng lặp

Cho đến nay, chúng ta đã thấy cách tạo vòng lặp for, nhưng điều quan trọng cần đề cập là chúng ta có thể thoát ra khỏi vòng lặp bằng cách sử dụng break. Câu lệnh break được sử dụng để kết thúc vòng lặp ngay lập tức khi nó gặp phải.

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

Đầu ra:

1
2
3
4

Cách hiển thị tổng các số tự nhiên

Bây giờ hãy lặp lại từ 1-10 và sau đó cộng các số này lại với nhau khi số lần lặp được tăng lên:

let sum = 0;

for (let i = 1; i <= 10; i++) {
    sum += i;  // This is same as: sum = sum + i
}

console.log('The sum of 1 to 10 is: ', sum); // "The sum of 1 to 10 is:  55"

Lưu ý: Chúng tôi đang thêm console.log(…)bên ngoài vòng lặp, vì vậy nó chỉ cung cấp cho chúng tôi đầu ra cuối cùng khi vòng lặp kết thúc.

Chúng tôi cũng có thể quyết định sử dụng các biến để đặt số lượng tối đa cho điều kiện của chúng tôi theo cách này:

let sum = 0;
let n = 10;

for (let i = 1; i <= n; i++) {
    sum += i;  // this is same as: sum = sum + i
}

console.log('The sum of 1 to 10 is: ', sum); // "The sum of 1 to 10 is:  55"

Cách thực hiện vòng lặp vô hạn với vòng lặp For

Điều này có thể làm treo hệ thống của bạn, vì nó tiếp tục chạy cho đến khi bộ nhớ đầy, vì điều kiện luôn đánh giá là đúng.

for(let i = 1; i > 0; i++) {
    // block of code
}

Cách lặp qua một mảng để kiểm tra số chẵn và lẻ

Hầu hết các lần bạn sẽ làm việc với mảng, vì vậy hãy xem cách chúng ta có thể lặp qua một mảng số để xuất ra tất cả các số chẵn và lẻ:

var numbers = [1, 4, 44, 64, 55, 24, 32, 55, 19, 17, 74, 22, 23];
var evenNumbers = [];
var oddNumbers = [];

for (var i = 0; i < numbers.length; i++) {
    if (numbers[i] % 2 != 1) {
        evenNumbers.push(numbers[i]);
    } else {
        oddNumbers.push(numbers[i]);
    }
}

console.log("The even numbers are: " + evenNumbers); // "The even numbers are: 4,44,64,24,32,74,22"
console.log("The odd numbers are: " + oddNumbers); // "The odd numbers are: 1,55,55,19,17,23"

Cách lặp qua một dãy số để có được số tối đa và nhỏ nhất

Cuối cùng, trước khi hoàn thành bài viết này, hãy xem cách lấy số lớn nhất và nhỏ nhất từ ​​một mảng với vòng lặp for:

Tối đa:

var numbers = [1, 4, 44, 64, 55, 24, 32, 55, 19, 17, 74, 22, 23];
var max = 0;

for (var i = 0; i < numbers.length; i++) {
    if (numbers[i] > max) {
        max = numbers[i];
    }
}

console.log(max); // 74

Tối thiểu:

var numbers = [4, 44, 64, 55, 24, 32, 55, 19, 17, 74, 22, 23];
var min = numbers[0];

for (var i = 0; i < numbers.length; i++) {
    if (numbers[i] < min) {
        min = numbers[i];
    }
}

console.log(min); // 4

Sự kết luận

Trong bài viết này, chúng ta đã tìm hiểu vòng lặp JavaScript là gì và xem xét một số ví dụ.

Điều quan trọng là phải hiểu rằng có nhiều loại vòng lặp khác, bao gồm cả vòng lặp while, được sử dụng tốt nhất khi bạn không biết số lần lặp. Nếu không, hãy luôn sử dụng vòng lặp for khi bạn biết số lần lặp.

Nguồn bài viết gốc tại https://www.freecodecamp.org

#javascript #js #programming 

Vòng lặp JavaScript | JavaScript For Loop - Giải thích với các ví dụ
Debbie Clay

Debbie Clay

1653711707

JavaScript Loops | JavaScript For Loop – Explained with Examples

Loops are a programming concept that we constantly encounter and implement as JavaScript developers.

And many developers are familiar with loops, but not everyone understands how they work and why or when they should use a specific type of loop.

In this article, we will learn what for loops are, how they work, and why we use them. We'll also keep in mind that there are several types of loops, each of which performs a specific function even though they can almost all perform the same common function.

What are Loops?

Loops are computer programs that execute a set of instructions or a block of code a certain number of times without having to write it again until a certain condition is met. In other words, loops let your code execute one or more statements as many times as desired.

Again, there are many types of loops, but we will only look at the for loop in this article.

Almost every high-level programming language, including JavaScript, has a for loop. We're only going to look at JavaScript in this article, and we'll look at its syntax and some examples.

For Loops in JavaScript

The for loop is an iterative statement which you use to check for certain conditions and then repeatedly execute a block of code as long as those conditions are met.

s_3315FAFA14C012362B87C753E4A1C2D25C00228882CEE2A5B63A9FDA99BA4B77_1653509464069_for+loop+flowchart+1

Flowchart for the for loop

Syntax of a for loop

for (initialExpression; condition; updateExpression) {
    // for loop body: statement
}

The code block above is the standard syntax used by for loop. Let's look at each parameter to see what it means and what it does:

  • initialExpression: This is used to set the value of a counter variable, and it is only evaluated once, before the loop starts. Depending on the scope, these counter variables are usually declared with the var or let keywords.
  • condition: This is a constant-evaluation expression that determines whether the loop should be executed. In simple terms, if this condition returns true, the for loop's block of code is executed. If it returns false, the for loop is terminated.
  • updateExpression: This is commonly used to update or increment the initialExpression counter variable. In other words, when the condition is true, it updates the value of the initialExpression.

In summary, the for loop causes the initialExpression variable, which is set to a starting value, to increase or decrease in response to the updateExpression as long as the condition is met. Finally, the statement, will always be executed if the condition evaluates to true.

For Loop Examples in JavaScript

At this point, we now understand what loops are, so let’s take a look at some examples and see how we can use loops.

How to Display Text Multiple Times

Let’s start by displaying some text several times until our condition is met.

for (var i = 0; i < 3; i++) {
  let name = "John Doe";
  console.log("Hi, my name is " + name);
}

Output:

"Hi, my name is John Doe"
"Hi, my name is John Doe"
"Hi, my name is John Doe"

Here is how the program processed this loop:

IterationVariableCondition: i < 3Action & variable update
1sti = 0true

Hi, my name is John Doe is printed.

i is increased to 1.

2ndi = 1true

Hi, my name is John Doe is printed.

i is increased to 2.

3rdi = 2true

Hi, my name is John Doe is printed.

i is increased to 3.

4thi=3falseThe loop is terminated.

Note: The loop is terminated because 3 is not less than 3, so it returned false.

How to Display a Sequence of Numbers with a For Loop

This time around, let’s display a sequence of numbers by displaying the iteration value.

for (let i = 2; i <= 5; i++) {
    console.log(i);  // printing the value of i
}

Output:

2
3
4
5

Here is how the program processed this loop:

IterationVariableCondition: i <= 5Action& variable update
1sti = 2true

2 is printed.

i is increased to 3.

2ndi = 3true

3 is printed.

i is increased to 4.

3rdi = 4true

4 is printed.

i is increased to 5.

5thi = 5true

5 is printed.

i is increased to 6.

6thi = 6falseThe loop is terminated.

Note: The loop is terminated because 6 is not less than or equal to 5, so the condition returns false.

How to Display a Sequence of Even Numbers

Let’s now display a sequence of even numbers only by displaying the iteration value:

for (let i = 2; i <= 10; i+=2) {
    console.log(i);  // printing the value of i
}


Output:

2
4
6
8
10

Here is how the program processed this loop:

IterationVariableCondition: i <= 10Action & variable update
1sti = 2true

2 is printed.

i is increased to 4.

2ndi = 4true

4 is printed.

i is increased to 6.

3rdi = 6true

6 is printed.

i is increased to 8.

5thi = 8true

8 is printed.

i is increased to 10.

6thi = 10true

10 is printed.

i is increased to 12.

7thi = 12falseThe loop is terminated.

Suppose we want to obtain the odd numbers. All we have to do is change the initialExpression to equal 1 or any odd number we wish to start from as seen below

for (let i = 1; i <= 10; i+=2) {
    console.log(i);  // printing the value of i
}

How to Break a For Loop Operation

So far, we have seen how to create a for loop, but it’s also important to mention that we can break out of a loop using break. The break statement is used to terminate the loop immediately when it is encountered.

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

Output:

1
2
3
4

How to Display the Sum of Natural Numbers

Let’s now loop from 1-10 and then add these numbers together as the iteration is increased:

let sum = 0;

for (let i = 1; i <= 10; i++) {
    sum += i;  // This is same as: sum = sum + i
}

console.log('The sum of 1 to 10 is: ', sum); // "The sum of 1 to 10 is:  55"

Note: We are adding console.log(…) outside the loop, so it only gives us the final output when the loop is terminated.

We can also decide to use variables to set the max number of our condition this way:

let sum = 0;
let n = 10;

for (let i = 1; i <= n; i++) {
    sum += i;  // this is same as: sum = sum + i
}

console.log('The sum of 1 to 10 is: ', sum); // "The sum of 1 to 10 is:  55"

How to Perform Infinite Loops with a For Loop

This can hang your system, because it continues to run until the memory is full, since the condition always evaluates as true.

for(let i = 1; i > 0; i++) {
    // block of code
}

How to Loop Through an Array to Check for Odd and Even Numbers

Most times you will be working with arrays, so let’s see how we can loop through an array of numbers to output all odd and even numbers:

var numbers = [1, 4, 44, 64, 55, 24, 32, 55, 19, 17, 74, 22, 23];
var evenNumbers = [];
var oddNumbers = [];

for (var i = 0; i < numbers.length; i++) {
    if (numbers[i] % 2 != 1) {
        evenNumbers.push(numbers[i]);
    } else {
        oddNumbers.push(numbers[i]);
    }
}

console.log("The even numbers are: " + evenNumbers); // "The even numbers are: 4,44,64,24,32,74,22"
console.log("The odd numbers are: " + oddNumbers); // "The odd numbers are: 1,55,55,19,17,23"

How to Loop Through an Array of Numbers to Get the Maximum and Minimum Number

Finally, before we round up this article, let’s see how to get the maximum and minimum number from an array with for loop:

Maximum:

var numbers = [1, 4, 44, 64, 55, 24, 32, 55, 19, 17, 74, 22, 23];
var max = 0;

for (var i = 0; i < numbers.length; i++) {
    if (numbers[i] > max) {
        max = numbers[i];
    }
}

console.log(max); // 74

Minimum:

var numbers = [4, 44, 64, 55, 24, 32, 55, 19, 17, 74, 22, 23];
var min = numbers[0];

for (var i = 0; i < numbers.length; i++) {
    if (numbers[i] < min) {
        min = numbers[i];
    }
}

console.log(min); // 4

Conclusion

In this article, we learned what a JavaScript loop is and looked at some examples.

It is important to understand that there are many other types of loops, including the while loop, which is best used when you don't know the number of iterations. Otherwise, always use the for loop when you do know the number of iterations.

Original article source at https://www.freecodecamp.org

#javascript #js #programming 

JavaScript Loops | JavaScript For Loop – Explained with Examples
Poppy Cooke

Poppy Cooke

1653382766

2 Ways to Convert Values to Boolean in JavaScript

A boolean is a primitive value that represents either true or false. In Boolean contexts, JavaScript utilizes type casting to convert values to true/false. There are implicit and explicit methods to convert values into their boolean counterparts.

This article provides an overview of truthy and falsy values and how to convert values into booleans in JavaScript.

JavaScript Truthy and Falsy Values Cheatsheet

Boolean(false);         // false
Boolean(undefined);     // false
Boolean(null);          // false
Boolean('');            // false
Boolean(NaN);           // false
Boolean(0);             // false
Boolean(-0);            // false
Boolean(0n);            // false

Boolean(true);          // true
Boolean('hi');          // true
Boolean(1);             // true
Boolean([]);            // true
Boolean([0]);           // true
Boolean([1]);           // true
Boolean({});            // true
Boolean({ a: 1 });      // true

It's best to start by first understanding which values are interpreted as truthy or falsy by JavaScript. It's also important to understand implicit coercion compared to explicit coercion.

Implicit coercion is initiated by the JavaScript engine and happens automatically. Explicit coercion is performed by manually converting values, and JavaScript provides built in methods to handle this.

The !! Operator

!!value

You may already be familiar with ! as the logical NOT operator. When using two in succession (!!), the first ! coerces the value to a boolean and inverts it. For example !true would result in false. The second ! reverses the previous inverted value, resulting in the true boolean value.

This is generally a preferred method, as it has better performance. A potential con to this method is a loss in readability, mainly if other developers are unfamiliar with how this operator works.

const value = "truthy string"
!!value // true

Here is an example breaking this down into steps:

const value = "truthy string";

!value; // false
!!value; // true

Below is a list of example output with the !! operator.

// Falsy Values

!!'' // false
!!false // false
!!null // false
!!undefined // false
!!0 // false
!!NaN // false


// Truthy Values

!![] // true
!!"false" // true
!!true // true
!!1 // true
!!{} // true

The Boolean() Function

Boolean(value)

Boolean() is a global function that converts the value it's passed into a boolean.

You shouldn't use this with the new keyword (new Boolean) as this creates an instance of a Boolean that has a type of object. Below is an example of the correct use of this function.

const value = "truthy string"
Boolean(value) // true

TL;DR

There are two methods to cast a value to a boolean in JavaScript.

1. !!

!!value

2. Boolean()

Boolean(value)
const finalThoughts = "I really enjoyed writing this article. Thanks for reading!"

!!finalThoughts // true
Boolean(finalThoughts) // true

Original article source at https://www.freecodecamp.org

#javascript #js #programming 

2 Ways to Convert Values to Boolean in JavaScript
Sean Wade

Sean Wade

1653116163

React Project Tutorial | Build and Deploy a React Admin Dashboard App

Build and Deploy a React Admin Dashboard App With Theming, Tables, Charts, Calendar, Kanban and More

Every web developer needs to build a React Admin Dashboard Application. Learn how to create the best and most modern one simply by watching this course. This Admin Panel includes one Dashboard, Three Pages, Four Apps, and Seven fully functional charts!

You'll learn how to build a fully functional calendar, a kanban board, a WYSIWYG editor, and a color picker, as well as seven different charts!

Alongside building this phenomenal application, in this video, you'll learn:
- Advanced React Best Practices such as folder and file structure, hooks, and refs
- Advanced State Management of the entire application using React Context API
- And most importantly you’ll learn how to use Syncfusion - World's Best UI Component Suite for Building Powerful Web, Desktop, and Mobile Apps

Time Stamps 👇
00:00:00 Intro
00:08:16 Setup
00:51:38 Sidebar
01:06:21 Context API
01:15:25 Navbar
01:39:45 Homepage
01:54:44 Revenue Section
02:17:36 Data Tables
02:36:10 Calendar
02:44:02 Kanban
02:49:21 WYSWYG Editor
02:53:49 Color Picker
02:59:13 Theme Fixes
03:33:10 Charts
03:51:18 Deployment

⭐Syncfusion Components: https://bit.ly/39pzH3R 
⭐Syncfusion React Components: https://bit.ly/3lhzpyB 

📚 Materials/References:
GitHub Code (give it a star ⭐): https://github.com/adrianhajdin/project_syncfusion_dashboard 
Styles & Other Code: https://gist.github.com/adrianhajdin/7d0eea1cbab4ab21a69dc8c2faf9b831 
Assets: https://minhaskamal.github.io/DownGit/#/home?url=https://github.com/adrianhajdin/project_syncfusion_dashboard/tree/main/src/data

#react #reactjs #javascript #js #webdev #programming 

React Project Tutorial | Build and Deploy a React Admin Dashboard App

JSON Mask: A Way to Select Specific Parts of a JS Object

JSON Mask

This is a tiny language and an engine for selecting specific parts of a JS object, hiding/masking the rest.

var mask = require('json-mask');
mask({ p: { a: 1, b: 2 }, z: 1 }, 'p/a,z'); // {p: {a: 1}, z: 1}

The main difference between JSONPath / JSONSelect and this engine is that JSON Mask preserves the structure of the original input object. Instead of returning an array of selected sub-elements (e.g. [{a: 1}, {z: 1}] from example above), it filters-out the parts of the object that you don't need, keeping the structure unchanged: {p: {a: 1}, z: 1}.

This is important because JSON Mask was designed with HTTP resources in mind, the structure of which I didn't want to change after the unwanted fields were masked / filtered.

If you've used the Google APIs, and provided a ?fields= query-string to get a Partial Response, you've already used this language. The desire to have partial responses in my own Node.js-based HTTP services was the reason I wrote JSON Mask.

For express users, there's an express-partial-response middleware. It will integrate with your existing services with no additional code if you're using res.json() or res.jsonp(). And if you're already using koa check out the koa-json-mask middleware.

This library has no dependencies. It works in Node as well as in the browser.

Note: the 1.5KB (gz), or 4KB (uncompressed) browser build is in the /build folder.

Syntax

The syntax is loosely based on XPath:

  • a,b,c comma-separated list will select multiple fields
  • a/b/c path will select a field from its parent
  • a(b,c) sub-selection will select many fields from a parent
  • a/*/c the star * wildcard will select all items in a field

Take a look at test/index-test.js for examples of all of these and more.

Grammar

     Props ::= Prop | Prop "," Props
      Prop ::= Object | Array
    Object ::= NAME | NAME "/" Prop
     Array ::= NAME "(" Props ")"
      NAME ::= ? all visible characters except "\" ? | EscapeSeq | Wildcard
  Wildcard ::= "*"
 EscapeSeq ::= "\" ? all visible characters ?

Examples

Identify the fields you want to keep:

var fields = 'url,object(content,attachments/url)';

From this sample object:

var originalObj = {
  id: 'z12gtjhq3qn2xxl2o224exwiqruvtda0i',
  url: 'https://plus.google.com/102817283354809142195/posts/F97fqZwJESL',
  object: {
    objectType: 'note',
    content:
      'A picture... of a space ship... launched from earth 40 years ago.',
    attachments: [
      {
        objectType: 'image',
        url: 'http://apod.nasa.gov/apod/ap110908.html',
        image: { height: 284, width: 506 }
      }
    ]
  },
  provider: { title: 'Google+' }
};

Here's what you'll get back:

var expectObj = {
  url: 'https://plus.google.com/102817283354809142195/posts/F97fqZwJESL',
  object: {
    content:
      'A picture... of a space ship... launched from earth 40 years ago.',
    attachments: [
      {
        url: 'http://apod.nasa.gov/apod/ap110908.html'
      }
    ]
  }
};

Let's test that:

var mask = require('json-mask');
var assert = require('assert');

var maskedObj = mask(originalObj, fields);
assert.deepEqual(maskedObj, expectObj);

Escaping

It is also possible to get keys that contain ,*()/ using \ (backslash) as escape character.

{
  "metadata": {
    "labels": {
      "app.kubernetes.io/name": "mysql",
      "location": "WH1"
    }
  }
}

You can filter out the location property by metadata(labels(app.kubernetes.io\/name)) mask.

NOTE: In JavaScript String you must escape backslash with another backslash:

var fields = 'metadata(labels(app.kubernetes.io\\/name))'

Partial Responses Server Example

Here's an example of using json-mask to implement the Google API Partial Response

var http = require('http');
var url = require('url');
var mask = require('json-mask');
var server;

server = http.createServer(function(req, res) {
  var fields = url.parse(req.url, true).query.fields;
  var data = {
    firstName: 'Mohandas',
    lastName: 'Gandhi',
    aliases: [
      {
        firstName: 'Mahatma',
        lastName: 'Gandhi'
      },
      {
        firstName: 'Bapu'
      }
    ]
  };
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify(mask(data, fields)));
});

server.listen(4000);

Let's test it:

$ curl 'http://localhost:4000'
{"firstName":"Mohandas","lastName":"Gandhi","aliases":[{"firstName":"Mahatma","lastName":"Gandhi"},{"firstName":"Bapu"}]}

$ # Let's just get the first name
$ curl 'http://localhost:4000?fields=lastName'
{"lastName":"Gandhi"}

$ # Now, let's just get the first names directly as well as from aliases
$ curl 'http://localhost:4000?fields=firstName,aliases(firstName)'
{"firstName":"Mohandas","aliases":[{"firstName":"Mahatma"},{"firstName":"Bapu"}]}

Note: a few more examples are in the /example folder.

Command Line Interface - CLI

When installed globally using npm i -g json-mask you can use it like:

json-mask "<fields>" <input> [<output>]

Examples

Stream from online resource:

curl https://api.myjson.com/bins/krrxw | json-mask "url,object(content,attachments/url)"

Read from file and write to output file:

json-mask "url,object(content,attachments/url)" input.json > output.json

Read from file and print redirect to file:

json-mask "url,object(content,attachments/url)" input.json > output.json

CDN

unpkg

  • https://unpkg.com/json-mask/build/jsonMask.js
  • https://unpkg.com/json-mask/build/jsonMask.min.js

Download Details: 
Author: nemtsov
Source Code: https://github.com/nemtsov/json-mask 
License: MIT
#json #js #javascript #programming 

JSON Mask: A Way to Select Specific Parts of a JS Object

The JavaScript Reduce Method Explained

JavaScript’s reduce method is one of the cornerstones of functional programming. Let’s explore how it works, when you should use it, and some of the cool things it can do.

A Basic Reduction

Use it when: You have an array of amounts and you want to add them all up.

const euros = [29.76, 41.85, 46.5];

const sum = euros.reduce((total, amount) => total + amount); 

sum // 118.11

How to use it:

  • In this example, Reduce accepts two parameters, the total and the current amount.
  • The reduce method cycles through each number in the array much like it would in a for-loop.
  • When the loop starts the total value is the number on the far left (29.76) and the current amount is the one next to it (41.85).
  • In this particular example, we want to add the current amount to the total.
  • The calculation is repeated for each amount in the array, but each time the current value changes to the next number in the array, moving right.
  • When there are no more numbers left in the array the method returns the total value.

The ES5 version of the Reduce Method In JavaScript​

If you have never used ES6 syntax before, don’t let the example above intimidate you. It’s exactly the same as writing:

var euros = [29.76, 41.85, 46.5]; 

var sum = euros.reduce( function(total, amount){
  return total + amount
});

sum // 118.11

We use const instead of var and we replace the word function with a “fat arrow” (=>) after the parameters, and we omit the word ‘return’.

I’ll use ES6 syntax for the rest of the examples, since it’s more concise and leaves less room for errors.

Finding an Average with the Reduce Method In JavaScript​

Instead of logging the sum, you could divide the sum by the length of the array before you return a final value.

The way to do this is by taking advantage of the other arguments in the reduce method. The first of those arguments is the index. Much like a for-loop, the index refers to the number of times the reducer has looped over the array. The last argument is the array itself.

const euros = [29.76, 41.85, 46.5];

const average = euros.reduce((total, amount, index, array) => {
  total += amount;
  if( index === array.length-1) { 
    return total/array.length;
  }else { 
    return total;
  }
});

average // 39.37

Map and Filter as Reductions

If you can use the reduce function to spit out an average then you can use it any way you want.

For example, you could double the total, or half each number before adding them together, or use an if statement inside the reducer to only add numbers that are greater than 10. My point is that the Reduce Method In JavaScript​ gives you a mini CodePen where you can write whatever logic you want. It will repeat the logic for each amount in the array and then return a single value.

The thing is, you don’t always have to return a single value. You can reduce an array into a new array.

For instance, lets reduce an array of amounts into another array where every amount is doubled. To do this we need to set the initial value for our accumulator to an empty array.

The initial value is the value of the total parameter when the reduction starts. You set the initial value by adding a comma followed by your initial value inside the parentheses but after the curly braces (bolded in the example below).

const average = euros.reduce((total, amount, index, array) => {
  total += amount
  return total/array.length
}, 0);

In previous examples, the initial value was zero so I omitted it. By omitting the initial value, the total will default to the first amount in the array.

By setting the initial value to an empty array we can then push each amount into the total. If we want to reduce an array of values into another array where every value is doubled, we need to push the amount * 2. Then we return the total when there are no more amounts to push.

const euros = [29.76, 41.85, 46.5];

const doubled = euros.reduce((total, amount) => {
  total.push(amount * 2);
  return total;
}, []);

doubled // [59.52, 83.7, 93]

We’ve created a new array where every amount is doubled. We could also filter out numbers we don’t want to double by adding an if statement inside our reducer.

const euro = [29.76, 41.85, 46.5];

const above30 = euro.reduce((total, amount) => {
  if (amount > 30) {
    total.push(amount);
  }
  return total;
}, []);

above30 // [ 41.85, 46.5 ]

These operations are the map and filter methods rewritten as a reduce method.

For these examples, it would make more sense to use map or filter because they are simpler to use. The benefit of using reduce comes into play when you want to map and filter together and you have a lot of data to go over.

If you chain map and filter together you are doing the work twice. You filter every single value and then you map the remaining values. With reduce you can filter and then map in a single pass.

Use map and filter but when you start chaining lots of methods together you now know that it is faster to reduce the data instead.

Creating a Tally with the Reduce Method In JavaScript​

Use it when: You have a collection of items and you want to know how many of each item are in the collection.

const fruitBasket = ['banana', 'cherry', 'orange', 'apple', 'cherry', 'orange', 'apple', 'banana', 'cherry', 'orange', 'fig' ];

const count = fruitBasket.reduce( (tally, fruit) => {
  tally[fruit] = (tally[fruit] || 0) + 1 ;
  return tally;
} , {})

count // { banana: 2, cherry: 3, orange: 3, apple: 2, fig: 1 }

To tally items in an array our initial value must be an empty object, not an empty array like it was in the last example.

Since we are going to be returning an object we can now store key-value pairs in the total.

fruitBasket.reduce( (tally, fruit) => {
  tally[fruit] = 1;
  return tally;
}, {})

On our first pass, we want the name of the first key to be our current value and we want to give it a value of 1.

This gives us an object with all the fruit as keys, each with a value of 1. We want the amount of each fruit to increase if they repeat.

To do this, on our second loop we check if our total contain a key with the current fruit of the reducer. If it doesn’t then we create it. If it does then we increment the amount by one.

fruitBasket.reduce((tally, fruit) => {
  if (!tally[fruit]) {
    tally[fruit] = 1;
  } else {
    tally[fruit] = tally[fruit] + 1;
  }
  return tally;
}, {});

I rewrote the exact same logic in a more concise way up top.

Flattening an array of arrays with the Reduce Method In JavaScript​​

We can use reduce to flatten nested amounts into a single array.

We set the initial value to an empty array and then concatenate the current value to the total.

const data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

const flat = data.reduce((total, amount) => {
  return total.concat(amount);
}, []);

flat // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

More often than not, information is nested in more complicated ways. For instance, lets say we just want all the colors in the data variable below.

const data = [
  {a: 'happy', b: 'robin', c: ['blue','green']}, 
  {a: 'tired', b: 'panther', c: ['green','black','orange','blue']}, 
  {a: 'sad', b: 'goldfish', c: ['green','red']}
];

We’re going to step through each object and pull out the colours. We do this by pointing amount.c for each object in the array. We then use a forEach loop to push every value in the nested array into out total.

const colors = data.reduce((total, amount) => {
  amount.c.forEach( color => {
      total.push(color);
  })
  return total;
}, [])

colors //['blue','green','green','black','orange','blue','green','red']

If we only need unique number then we can check to see of the number already exists in total before we push it.

const uniqueColors = data.reduce((total, amount) => {
  amount.c.forEach( color => {
    if (total.indexOf(color) === -1){
     total.push(color);
    }
  });
  return total;
}, []);

uniqueColors // [ 'blue', 'red', 'green', 'black', 'orange']

Piping with Reduce

An interesting aspect of the reduce method in JavaScript is that you can reduce over functions as well as numbers and strings.

Let’s say we have a collection of simple mathematical functions. these functions allow us to increment, decrement, double and halve an amount.

function increment(input) { return input + 1;}

function decrement(input) { return input — 1; }

function double(input) { return input * 2; }

function halve(input) { return input / 2; }

For whatever reason, we need to increment, then double, then decrement an amount.

You could write a function that takes an input, and returns (input + 1) * 2 -1. The problem is that we know we are going to need to increment the amount three times, then double it, then decrement it, and then halve it at some point in the future. We don’t want to have to rewrite our function every time so we going to use reduce to create a pipeline.

A pipeline is a term used for a list of functions that transform some initial value into a final value. Our pipeline will consist of our three functions in the order that we want to use them.

let pipeline = [increment, double, decrement];

Instead of reducing an array of values we reduce over our pipeline of functions. This works because we set the initial value as the amount we want to transform.

const result = pipeline.reduce(function(total, func) {
  return func(total);
}, 1);

result // 3

Because the pipeline is an array, it can be easily modified. If we want to decrement something three times, then double it, decrement it , and halve it then we just alter the pipeline.

var pipeline = [

  increment,
  
  increment,
  
  increment,
  
  double,
  
  decrement,
  
  halve
  
];

The reduce function stays exactly the same.

Silly Mistakes to avoid

If you don’t pass in an initial value, reduce will assume the first item in your array is your initial value. This worked fine in the first few examples because we were adding up a list of numbers.

If you’re trying to tally up fruit, and you leave out the initial value then things get weird. Not entering an initial value is an easy mistake to make and one of the first things you should check when debugging.

Another common mistake is to forget to return the total. You must return something for the reduce function to work. Always double check and make sure that you’re actually returning the value you want.

Original article source at https://www.freecodecamp.org

#javascript #js #programming 

The JavaScript Reduce Method Explained

JavaScript Array Reduce() Method - Explained With Examples

Array Reduce Explained With Examples - JavaScript Tutorial

In today's video I'll be taking you through JavaScript's Array Reduce method with a few practical examples. Listen in 🙂


Array.prototype.reduce()

The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0).

Perhaps the easiest-to-understand case for reduce() is to return the sum of all the elements in an array:

const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (previousValue, currentValue) => previousValue + currentValue,
  initialValue
);

console.log(sumWithInitial);
// expected output: 10

The reducer walks through the array element-by-element, at each step adding the current array value to the result from the previous step (this result is the running sum of all the previous steps) — until there are no more elements to add.

Syntax

// Arrow function
reduce((previousValue, currentValue) => { /* ... */ } )
reduce((previousValue, currentValue, currentIndex) => { /* ... */ } )
reduce((previousValue, currentValue, currentIndex, array) => { /* ... */ } )
reduce((previousValue, currentValue, currentIndex, array) => { /* ... */ }, initialValue)

// Callback function
reduce(callbackFn)
reduce(callbackFn, initialValue)

// Inline callback function
reduce(function(previousValue, currentValue) { /* ... */ })
reduce(function(previousValue, currentValue, currentIndex) { /* ... */ })
reduce(function(previousValue, currentValue, currentIndex, array) { /* ... */ })
reduce(function(previousValue, currentValue, currentIndex, array) { /* ... */ }, initialValue)

Parameters

callbackFn

A "reducer" function.

The function is called with the following arguments:

  • previousValue: the value resulting from the previous call to callbackFn. On first call, initialValue if specified, otherwise the value of array[0].
  • currentValue: the value of the current element. On first call, the value of array[0] if an initialValue was specified, otherwise the value of array[1].
  • currentIndex: the index position of currentValue in the array. On first call, 0 if initialValue was specified, otherwise 1.
  • array: the array to traverse.

initialValue Optional

A value to which previousValue is initialized the first time the callback is called. If initialValue is specified, that also causes currentValue to be initialized to the first value in the array. If initialValue is not specified, previousValue is initialized to the first value in the array, and currentValue is initialized to the second value in the array.

Return value

The value that results from running the "reducer" callback function to completion over the entire array.

Exceptions

TypeError

The array contains no elements and initialValue is not provided.

Description

The reduce() method takes two arguments: a callback function and an optional initial value. If an initial value is provided, reduce() calls the "reducer" callback function on each element in the array, in order. If no initial value is provided, reduce() calls the callback function on each element in the array after the first element.

reduce() returns the value that is returned from the callback function on the final iteration of the array.

When to not use reduce()

Recursive functions like reduce() can be powerful but sometimes difficult to understand, especially for less experienced JavaScript developers. If code becomes clearer when using other array methods, developers must weigh the readability tradeoff against the other benefits of using reduce(). In cases where reduce() is the best choice, documentation and semantic variable naming can help mitigate readability drawbacks.

Behavior during array mutations

The reduce() method itself does not mutate the array it is used on. However, it is possible for code inside the callback function to mutate the array. These are the possible scenarios of array mutations and how reduce() behaves in these scenarios:

  • If elements are appended to the array after reduce() begins to iterate over the array, the callback function does not iterate over the appended elements.
  • If existing elements of the array do get changed, the values passed to the callback function will be the values from the time that reduce() was first called on the array.
  • Array elements that are deleted after the call to reduce() begins and before being iterated over are not visited by reduce().

Edge cases

If the array only has one element (regardless of position) and no initialValue is provided, or if initialValue is provided but the array is empty, the solo value will be returned without calling callbackFn.

If initialValue is provided and the array is not empty, then the reduce method will always invoke the callback function starting at index 0.

If initialValue is not provided then the reduce method will act differently for arrays with length larger than 1, equal to 1 and 0, as shown in the following example:

const getMax = (a, b) => Math.max(a, b);

// callback is invoked for each element in the array starting at index 0
[1, 100].reduce(getMax, 50); // 100
[    50].reduce(getMax, 10); // 50

// callback is invoked once for element at index 1
[1, 100].reduce(getMax);     // 100

// callback is not invoked
[    50].reduce(getMax);     // 50
[      ].reduce(getMax, 1);  // 1

[      ].reduce(getMax);     // TypeError

Examples

How reduce() works without an initial value

The code below shows what happens if we call reduce() with an array and no initial value.

const array = [15, 16, 17, 18, 19];

function reducer(previous, current, index, array) {
  const returns = previous + current;
  console.log(`previous: ${previous}, current: ${current}, index: ${index}, returns: ${returns}`);
  return returns;
}

array.reduce(reducer);

The callback would be invoked four times, with the arguments and return values in each call being as follows:

callback iterationpreviousValuecurrentValuecurrentIndexarrayreturn value
first call15161[15, 16, 17, 18, 19]31
second call31172[15, 16, 17, 18, 19]48
third call48183[15, 16, 17, 18, 19]66
fourth call66194[15, 16, 17, 18, 19]85

The value returned by reduce() would be that of the last callback invocation (85).

How reduce() works with an initial value

Here we reduce the same array using the same algorithm, but with an initialValue of 10 passed the second argument to reduce():

[15, 16, 17, 18, 19].reduce( (previousValue, currentValue, currentIndex, array) => previousValue + currentValue, 10 )

The callback would be invoked five times, with the arguments and return values in each call being as follows:

callback iterationpreviousValuecurrentValuecurrentIndexarrayreturn value
first call10150[15, 16, 17, 18, 19]25
second call25161[15, 16, 17, 18, 19]41
third call41172[15, 16, 17, 18, 19]58
fourth call58183[15, 16, 17, 18, 19]76
fifth call76194[15, 16, 17, 18, 19]95

The value returned by reduce() in this case would be 95.

Sum all the values of an array

let sum = [0, 1, 2, 3].reduce(function (previousValue, currentValue) {
  return previousValue + currentValue
}, 0)
// sum is 6

Alternatively written with an arrow function:

let total = [ 0, 1, 2, 3 ].reduce(
  ( previousValue, currentValue ) => previousValue + currentValue,
  0
)

Sum of values in an object array

To sum up the values contained in an array of objects, you must supply an initialValue, so that each item passes through your function.

let initialValue = 0
let sum = [{x: 1}, {x: 2}, {x: 3}].reduce(function (previousValue, currentValue) {
    return previousValue + currentValue.x
}, initialValue)

console.log(sum) // logs 6

Alternatively written with an arrow function:

let initialValue = 0
let sum = [{x: 1}, {x: 2}, {x: 3}].reduce(
    (previousValue, currentValue) => previousValue + currentValue.x
    , initialValue
)

console.log(sum) // logs 6

Flatten an array of arrays

let flattened = [[0, 1], [2, 3], [4, 5]].reduce(
  function(previousValue, currentValue) {
    return previousValue.concat(currentValue)
  },
  []
)
// flattened is [0, 1, 2, 3, 4, 5]

Alternatively written with an arrow function:

let flattened = [[0, 1], [2, 3], [4, 5]].reduce(
  ( previousValue, currentValue ) => previousValue.concat(currentValue),
  []
)

Counting instances of values in an object

const names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']

let countedNames = names.reduce(function (allNames, name) {
  if (name in allNames) {
    allNames[name]++
  }
  else {
    allNames[name] = 1
  }
  return allNames
}, {})
// countedNames is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }

Grouping objects by a property

const people = [
  { name: 'Alice', age: 21 },
  { name: 'Max', age: 20 },
  { name: 'Jane', age: 20 }
];

function groupBy(objectArray, property) {
  return objectArray.reduce(function (acc, obj) {
    let key = obj[property]
    if (!acc[key]) {
      acc[key] = []
    }
    acc[key].push(obj)
    return acc
  }, {})
}

let groupedPeople = groupBy(people, 'age')
// groupedPeople is:
// {
//   20: [
//     { name: 'Max', age: 20 },
//     { name: 'Jane', age: 20 }
//   ],
//   21: [{ name: 'Alice', age: 21 }]
// }

Bonding arrays contained in an array of objects using the spread operator and initialValue

// friends - an array of objects
// where object field "books" is a list of favorite books
const friends = [{
  name: 'Anna',
  books: ['Bible', 'Harry Potter'],
  age: 21
}, {
  name: 'Bob',
  books: ['War and peace', 'Romeo and Juliet'],
  age: 26
}, {
  name: 'Alice',
  books: ['The Lord of the Rings', 'The Shining'],
  age: 18
}]

// allbooks - list which will contain all friends' books +
// additional list contained in initialValue
let allbooks = friends.reduce(function(previousValue, currentValue) {
  return [...previousValue, ...currentValue.books]
}, ['Alphabet'])

// allbooks = [
//   'Alphabet', 'Bible', 'Harry Potter', 'War and peace',
//   'Romeo and Juliet', 'The Lord of the Rings',
//   'The Shining'
// ]

Remove duplicate items in an array

Note: If you are using an environment compatible with Set and Array.from(), you could use let arrayWithNoDuplicates = Array.from(new Set(myArray)) to get an array where duplicate items have been removed.

const myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd']
let myArrayWithNoDuplicates = myArray.reduce(function (previousValue, currentValue) {
  if (previousValue.indexOf(currentValue) === -1) {
    previousValue.push(currentValue)
  }
  return previousValue
}, [])

console.log(myArrayWithNoDuplicates)

Replace .filter().map() with .reduce()

Using Array.filter() then Array.map() traverses the array twice, but you can achieve the same effect while traversing only once with Array.reduce(), thereby being more efficient. (If you like for loops, you can filter and map while traversing once with Array.forEach()).

const numbers = [-5, 6, 2, 0,];

const doubledPositiveNumbers = numbers.reduce((previousValue, currentValue) => {
  if (currentValue > 0) {
    const doubled = currentValue * 2;
    previousValue.push(doubled);
  }
  return previousValue;
}, []);

console.log(doubledPositiveNumbers); // [12, 4]

Running Promises in Sequence

/**
 * Runs promises from array of functions that can return promises
 * in chained manner
 *
 * @param {array} arr - promise arr
 * @return {Object} promise object
 */
function runPromiseInSequence(arr, input) {
  return arr.reduce(
    (promiseChain, currentFunction) => promiseChain.then(currentFunction),
    Promise.resolve(input)
  )
}

// promise function 1
function p1(a) {
  return new Promise((resolve, reject) => {
    resolve(a * 5)
  })
}

// promise function 2
function p2(a) {
  return new Promise((resolve, reject) => {
    resolve(a * 2)
  })
}

// function 3  - will be wrapped in a resolved promise by .then()
function f3(a) {
 return a * 3
}

// promise function 4
function p4(a) {
  return new Promise((resolve, reject) => {
    resolve(a * 4)
  })
}

const promiseArr = [p1, p2, f3, p4]
runPromiseInSequence(promiseArr, 10)
  .then(console.log)   // 1200

Function composition enabling piping

// Building-blocks to use for composition
const double = x => x + x
const triple = x => 3 * x
const quadruple = x => 4 * x

// Function composition enabling pipe functionality
const pipe = (...functions) => initialValue => functions.reduce(
    (acc, fn) => fn(acc),
    initialValue
)

// Composed functions for multiplication of specific values
const multiply6 = pipe(double, triple)
const multiply9 = pipe(triple, triple)
const multiply16 = pipe(quadruple, quadruple)
const multiply24 = pipe(double, triple, quadruple)

// Usage
multiply6(6)   // 36
multiply9(9)   // 81
multiply16(16) // 256
multiply24(10) // 240

Write map using reduce

if (!Array.prototype.mapUsingReduce) {
  Array.prototype.mapUsingReduce = function(callback, initialValue) {
    return this.reduce(function(mappedArray, currentValue, currentIndex, array) {
      mappedArray[currentIndex] = callback.call(initialValue, currentValue, currentIndex, array)
      return mappedArray
    }, [])
  }
}

[1, 2, , 3].mapUsingReduce(
  (currentValue, currentIndex, array) => currentValue + currentIndex + array.length
) // [5, 7, , 10]

For your reference, check this out:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce 

#javascript #js #programming 

JavaScript Array Reduce() Method - Explained With Examples
Poppy Cooke

Poppy Cooke

1651657095

11 Ways to Convert a String to Number in JavaScript

How to Convert a String to a Number in JavaScript

There are many ways to convert a string into a number using JavaScript. But what does that look like in code?

In this article, I will show you 11 ways to convert a string into a number.

  1. using the Number() function
  2. using the parseInt() function
  3. using the parseFloat() function
  4. using the unary plus operator (+)
  5. multiplying the string by the number 1
  6. dividing the string by the number 1
  7. subtracting the number 0 from the string
  8. using the bitwise NOT operator (~)
  9. using the Math.floor() function
  10. using the Math.ceil() function
  11. using the Math.round() function

How to convert a string to a number in JavaScript using the Number() function

One way to convert a string into a number would be to use the Number() function.

In this example, we have a string called quantity with the value of "12".

const quantity = "12";

If we used the typeof operator on quantity, then it will return the type of string.

console.log(typeof quantity);

Screen-Shot-2022-05-01-at-9.50.17-AM

We can convert quantity into a number using the Number function like this:

Number(quantity)

We can check that it is now a number by using the typeof operator again.

console.log(typeof Number(quantity));

Screen-Shot-2022-05-01-at-9.57.35-AM

If you tried to pass in a value that cannot be converted into a number, then the return value would be NaN (Not a Number).

console.log(Number("awesome"));

Screen-Shot-2022-05-01-at-10.00.34-AM

How to convert a string to a number in JavaScript using the parseInt() function

Another way to convert a string into a number is to use the parseInt() function. This function takes in a string and an optional radix.

A radix is a number between 2 and 36 which represents the base in a numeral system. For example, a radix of 2 would represent the binary system, while a radix of 10 represents the decimal system.

We can use the quantity variable from earlier to convert that string into a number.

const quantity = "12";

console.log(parseInt(quantity, 10));

What happens if I try to change the quantity variable to "12.99"? Will the result using parseInt() be the number 12.99?

const quantity = "12.99";

console.log(parseInt(quantity, 10));

Screen-Shot-2022-05-01-at-10.45.08-AM

As you can see, the result is a rounded integer. If you wanted to return a floating point number, then you would need to use parseFloat().

How to convert a string to a number in JavaScript using the parseFloat() function

The parseFloat() function will take in a value and return a floating point number. Examples of floating point numbers would be 12.99 or 3.14.

If we modify our example from earlier to use parseFloat(), then the result would be the floating point number of 12.99.

const quantity = "12.99";

console.log(parseFloat(quantity));

Screen-Shot-2022-05-01-at-10.55.03-AM

If you have leading or trailing whitespace in your string, then parseFloat() will still convert that string into a floating point number.

const quantity = "   12.99    ";

console.log(parseFloat(quantity));

Screen-Shot-2022-05-01-at-11.05.35-AM

If the first character in your string cannot be converted into number, then parseFloat() will return NaN.

const quantity = "F12.99";

console.log(parseFloat(quantity));

Screen-Shot-2022-05-01-at-11.08.33-AM

How to convert a string to a number in JavaScript using the unary plus operator (+)

The unary plus operator (+) will convert a string into a number. The operator will go before the operand.

const quantity = "12";

console.log(+quantity);

Screen-Shot-2022-05-01-at-11.14.51-AM

We can also use the unary plus operator (+) to convert a string into a floating point number.

const quantity = "12.99";

console.log(+quantity);

Screen-Shot-2022-05-01-at-11.16.38-AM

If the string value cannot be converted into a number then the result will be NaN.

const quantity = "awesome";

console.log(+quantity);

Screen-Shot-2022-05-01-at-11.18.10-AM

How to convert a string to a number in JavaScript by multiplying the string by the number 1

Another way to convert a string into a number is to use a basic math operation. You can multiply the string value by 1 and it will return a number.

const quantity = "12";

console.log(quantity * 1);

Screen-Shot-2022-05-01-at-11.42.58-AM

As you can see, when we multiply the quantity value by 1, then it returns the number 12. But how does this work?

In this example, JavaScript is converting our string value to a number and then performing that mathematical operation.  If the string cannot be converted to a number, then the mathematical operation will not work and it will return NaN.

const quantity = "awesome";

console.log(quantity * 1);

Screen-Shot-2022-05-01-at-11.18.10-AM

This method will also work for floating point numbers.

const quantity = "10.5";

console.log(quantity * 1);

Screen-Shot-2022-05-01-at-11.56.19-AM

How to convert a string to a number in JavaScript by dividing the string by the number 1

Instead of multiplying by 1, you can also divide the string by 1. JavaScript is converting our string value to a number and then performing that mathematical operation.

const quantity = "10.5";

console.log(quantity / 1);

Screen-Shot-2022-05-01-at-12.08.37-PM

How to convert a string to a number in JavaScript by subtracting the number 0 from the string

Another method would be to subtract 0 from the string. Like before, JavaScript is converting our string value to a number and then performing that mathematical operation.

const quantity = "19";

console.log(quantity - 0);

Screen-Shot-2022-05-01-at-12.11.59-PM

How to convert a string to a number in JavaScript using the bitwise NOT operator (~)

The bitwise NOT operator (~) will invert the bits of an operand and convert that value to a 32-bit signed integer. A 32-bit signed integer is a value that represents an integer in 32 bits (or 4 bytes).

If we use one bitwise NOT operator (~)  on a number, then it will perform this operation: -(x + 1)

console.log(~19);

Screen-Shot-2022-05-01-at-12.20.18-PM

But if we use two bitwise NOT operators (~), then it will convert our string to a number.

const quantity = "19";

console.log(~~quantity);

Screen-Shot-2022-05-01-at-12.28.16-PM

This method will not work for floating point numbers because the result would be an integer.

const quantity = "19.99";

console.log(~~quantity);

Screen-Shot-2022-05-01-at-12.31.16-PM

If you tried to use this method on non-numeric characters, then the result would be zero.

const quantity = "awesome";

console.log(~~quantity);

Screen-Shot-2022-05-01-at-12.32.45-PM

This method does have its limitations because it will start to break for values that are considered too large. It is important to make sure that your number is between the values of a signed 32 bit integer.

const quantity = "2700000000";

console.log(~~quantity);

Screen-Shot-2022-05-01-at-12.36.16-PM

To learn more about the bitwise NOT operator (~) , please read up in the documentation.

How to convert a string to a number in JavaScript using the Math.floor() function

Another way to convert a string to a number is to use the Math.floor() function. This function will round the number down to the nearest integer.

const quantity = "13.4";

console.log(Math.floor(quantity));

Screen-Shot-2022-05-01-at-12.44.53-PM

Just like in earlier examples, if we tried to use non-numeric characters, then the result would be NaN.

const quantity = "awesome";

console.log(Math.floor(quantity));

Screen-Shot-2022-05-01-at-12.46.08-PM

How to convert a string to a number in JavaScript using the Math.ceil() function

The Math.ceil() function will round a number up to the nearest integer.

const quantity = "7.18";

console.log(Math.ceil(quantity));

Screen-Shot-2022-05-01-at-12.48.15-PM

How to convert a string to a number in JavaScript using the Math.round() function

The Math.round() function will round the number to the nearest integer.

If I have the value of 6.3, then Math.round() will return 6.

const quantity = "6.3";

console.log(Math.round(quantity));

Screen-Shot-2022-05-01-at-12.50.20-PM

But if I changed that value to 6.5, then Math.round() will return 7.

const quantity = "6.5";

console.log(Math.round(quantity));

Screen-Shot-2022-05-01-at-12.51.35-PM

Conclusion

In this article, I showed you 11 ways to convert a string to a number using JavaScript.

Here are the 11 different methods discussed in the article.

  1. using the Number() function
  2. using the parseInt() function
  3. using the parseFloat() function
  4. using the unary plus operator (+)
  5. multiplying the string by the number 1
  6. dividing the string by the number 1
  7. subtracting the number 0 from the string
  8. using the bitwise NOT operator (~)
  9. using the Math.floor() function
  10. using the Math.ceil() function
  11. using the Math.round() function

I hope you enjoyed this article and best of luck on your JavaScript journey.
 

Original article source at https://www.freecodecamp.org

#javascript #js #programming 

11 Ways to Convert a String to Number in JavaScript
Felix Kling

Felix Kling

1651127659

How to Navigate the DOM in JavaScript

JavaScript Traversing the DOM | How to navigate the DOM | Learn JavaScript

In this JavaScript tutorial you are goin to learn how to navigate the DOM also known as traversing the DOM in JavaScript.

Timestamps:
00:00 - Intro & Project overview
00:00 - Basic Setup


JavaScript HTML DOM Navigation

With the HTML DOM, you can navigate the node tree using node relationships.

DOM Nodes

According to the W3C HTML DOM standard, everything in an HTML document is a node:

  • The entire document is a document node
  • Every HTML element is an element node
  • The text inside HTML elements are text nodes
  • Every HTML attribute is an attribute node (deprecated)
  • All comments are comment nodes

DOM HTML tree

With the HTML DOM, all nodes in the node tree can be accessed by JavaScript.

New nodes can be created, and all nodes can be modified or deleted.

Node Relationships

The nodes in the node tree have a hierarchical relationship to each other.

The terms parent, child, and sibling are used to describe the relationships.

  • In a node tree, the top node is called the root (or root node)
  • Every node has exactly one parent, except the root (which has no parent)
  • A node can have a number of children
  • Siblings (brothers or sisters) are nodes with the same parent
<html>

  <head>
    <title>DOM Tutorial</title>
  </head>

  <body>
    <h1>DOM Lesson one</h1>
    <p>Hello world!</p>
  </body>

</html>
Node tree

From the HTML above you can read:

  • <html> is the root node
  • <html> has no parents
  • <html> is the parent of <head> and <body>
  • <head> is the first child of <html>
  • <body> is the last child of <html>

and:

  • <head> has one child: <title>
  • <title> has one child (a text node): "DOM Tutorial"
  • <body> has two children: <h1> and <p>
  • <h1> has one child: "DOM Lesson one"
  • <p> has one child: "Hello world!"
  • <h1> and <p> are siblings

Navigating Between Nodes

You can use the following node properties to navigate between nodes with JavaScript:

  • parentNode
  • childNodes[nodenumber]
  • firstChild
  • lastChild
  • nextSibling
  • previousSibling

Child Nodes and Node Values

A common error in DOM processing is to expect an element node to contain text.

Example:

<title id="demo">DOM Tutorial</title>

The element node <title> (in the example above) does not contain text.

It contains a text node with the value "DOM Tutorial".

The value of the text node can be accessed by the node's innerHTML property:

myTitle = document.getElementById("demo").innerHTML;

Accessing the innerHTML property is the same as accessing the nodeValue of the first child:

myTitle = document.getElementById("demo").firstChild.nodeValue;

Accessing the first child can also be done like this:

myTitle = document.getElementById("demo").childNodes[0].nodeValue;

All the (3) following examples retrieves the text of an <h1> element and copies it into a <p> element:

Example

<html>
<body>

<h1 id="id01">My First Page</h1>
<p id="id02"></p>

<script>
document.getElementById("id02").innerHTML = document.getElementById("id01").innerHTML;
</script>

</body>
</html>

Example

<html>
<body>

<h1 id="id01">My First Page</h1>
<p id="id02"></p>

<script>
document.getElementById("id02").innerHTML = document.getElementById("id01").firstChild.nodeValue;
</script>

</body>
</html>

Example

<html>
<body>

<h1 id="id01">My First Page</h1>
<p id="id02">Hello!</p>

<script>
document.getElementById("id02").innerHTML = document.getElementById("id01").childNodes[0].nodeValue;
</script>

</body>
</html>

InnerHTML

In this tutorial we use the innerHTML property to retrieve the content of an HTML element.

However, learning the other methods above is useful for understanding the tree structure and the navigation of the DOM.

DOM Root Nodes

There are two special properties that allow access to the full document:

  • document.body - The body of the document
  • document.documentElement - The full document

Example

<html>
<body>

<h2>JavaScript HTMLDOM</h2>
<p>Displaying document.body</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = document.body.innerHTML;
</script>

</body>
</html>

Example

<html>
<body>

<h2>JavaScript HTMLDOM</h2>
<p>Displaying document.documentElement</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = document.documentElement.innerHTML;
</script>

</body>
</html>

The nodeName Property

The nodeName property specifies the name of a node.

  • nodeName is read-only
  • nodeName of an element node is the same as the tag name
  • nodeName of an attribute node is the attribute name
  • nodeName of a text node is always #text
  • nodeName of the document node is always #document

Example

<h1 id="id01">My First Page</h1>
<p id="id02"></p>

<script>
document.getElementById("id02").innerHTML = document.getElementById("id01").nodeName;
</script>

Note: nodeName always contains the uppercase tag name of an HTML element.

The nodeValue Property

The nodeValue property specifies the value of a node.

  • nodeValue for element nodes is null
  • nodeValue for text nodes is the text itself
  • nodeValue for attribute nodes is the attribute value

The nodeType Property

The nodeType property is read only. It returns the type of a node.

Example

<h1 id="id01">My First Page</h1>
<p id="id02"></p>

<script>
document.getElementById("id02").innerHTML = document.getElementById("id01").nodeType;
</script>

The most important nodeType properties are:

NodeTypeExample
ELEMENT_NODE1<h1 class="heading">W3Schools</h1>
ATTRIBUTE_NODE2 class = "heading" (deprecated)
TEXT_NODE3W3Schools
COMMENT_NODE8<!-- This is a comment -->
DOCUMENT_NODE9The HTML document itself (the parent of <html>)
DOCUMENT_TYPE_NODE10<!Doctype html>

Type 2 is deprecated in the HTML DOM (but works). It is not deprecated in the XML DOM.


Traversing the DOM with JavaScript

A good JavaScript developer needs to know how to traverse the DOM—it’s the act of selecting an element from another element.

But why do we need to learn to traverse the DOM? Isn’t document.querySelector enough for most of our needs?

In this article, I’m going to show you why traversing is better that document.querySelector, and how to traverse like a pro. So sit back, relax, and enjoy the article!

Why we traverse

Let’s say you want to go to your neighbor’s house. What’s the fastest and most efficient way to get there?

  1. Move from your house to their house (since you already know their address)
  2. Lookup their address on Google maps, then walk according to the directions Google gives you.

If you move directly from your house to their house, you’re doing the equivalent of traversing the DOM—selecting one element from a neighboring element.

If you lookup their address on Google, you’re doing the equivalent of document.querySelector to find elements.

Can you guess which method is more efficient?

<div class="neighborhood">
  <div class="your-house">😎</div>
  <div class="neighbor-house">🎉</div>
</div>

You probably know the answer—it’s always easier to move from an element to another (compared do doing a full search). That’s why we traverse the DOM.

You can traverse in three directions:

  1. Downwards
  2. Sideways
  3. Upwards

(Note: there’s a second reason—it’s more reliable—but that’s an advanced topic for another day.)

Traversing downwards

There are two methods to traverse downwards:

  1. querySelector or querySelectorAll
  2. children

querySelector or querySelectorAll

To traverse downwards from a specific element, you can use element.querySelector or element.querySelectorAll.

If we put element.querySelector into the house analogy, we search for a specific room in your house. It’s faster than searching for the same room from outer space (the document).

<div class="component">
  <h2 class="component__title">Component title</h2>
</div>
const component = document.querySelector('.component')
const title = component.querySelector('.component__title')

console.log(title) // <h2 class="component__title"> ... </h2>

children

children is a property that lets you select direct descendants (elements that are immediately nested in another element). It returns a HTML Collection that updates when children elements are changed.

<ul class="list">
  <li><a href="#">Link 1</a></li>
  <li><a href="#">Link 2</a></li>
  <li><a href="#">Link 3</a></li>
  <li><a href="#">Link 4</a></li>
  <li><a href="#">Link 5</a></li>
</ul>
const list = document.querySelector('.list')
const listItems = list.children

console.log(listItems)

Selecting all list items with the children property

Selecting all list items with the children property

A HTML Collection is similar to a NodeList (that querySelectorAll returns). There are subtle differences that don’t really matter for the context of this article.

What matters is—a HTML collection is an array-like object. If you want to loop over it with Array.prototype.forEach, you need to convert it into an array with Array.from first.

const array = Array.from(HTMLCollection)
array.forEach(el => { /* do whatever you want */})

Selecting a specific child

You can select the nth-item in the list from both NodeLists (result from querySelectorAll) and HTML Collections (result from children). To do so, you use the index of the element, just like how you select a specific item from an Array.

<ul class="list">
  <li><a href="#">Link 1</a></li>
  <li><a href="#">Link 2</a></li>
  <li><a href="#">Link 3</a></li>
  <li><a href="#">Link 4</a></li>
  <li><a href="#">Link 5</a></li>
</ul>
const listItems = document.querySelectorAll('li')

const firstItem = listItems[0]
const secondItem = listItems[1]
const thirdItem = listItems[2]
const fourthItem = listItems[3]
const fifthItem = listItems[4]

console.log(firstItem)
console.log(secondItem)
console.log(thirdItem)
console.log(fourthItem)
console.log(fifthItem)

Select a specific child with [index]

Select a specific child with [index]

Try the above code with a HTML Collection. You’ll get the same result.

Traversing upwards

There are two methods to traverse upwards:

  1. parentElement
  2. closest

parentElement

parentELement is a property that lets you select the parent element. The parent element is the element that encloses the current element.

In the following HTML, .list is the parent element of all <li>. Each <li> is the parent element of their respective <a>.

<ul class="list">
  <li><a href="#">Link 1</a></li>
  <li><a href="#">Link 2</a></li>
  <li><a href="#">Link 3</a></li>
  <li><a href="#">Link 4</a></li>
  <li><a href="#">Link 5</a></li>
</ul>
const firstListItem = document.querySelector('li')
const list = firstListItem.parentElement

console.log(list)
// <ul class="list">...</ul>

closest

parentElement is great for selecting one level upwards. To find an element that can be multiple levels above the current element, you use the closest method.

closest lets you select the closest ancestor element that matches a selector. Here’s the syntax:

const closestAncestor = Element.closest(selector)

As you may suspect, selector is the same selector you pass to querySelector and querySelectorAll.

In the following HTML, you can select .list from the <a> effortlessly with Element.closest:

<ul class="list">
  <li><a href="#">Link 1</a></li>
  <li><a href="#">Link 2</a></li>
  <li><a href="#">Link 3</a></li>
  <li><a href="#">Link 4</a></li>
  <li><a href="#">Link 5</a></li>
</ul>
const firstLink = document.querySelector('a')
const list = firstLink.closest('.list')

console.log(list)
// <ul class="list"> ... </ul>

Note: closest starts searching from the current element, then proceeds upwards until it reaches the document. It stops returns the first element it finds.

const firstLink = document.querySelector('a')
const firstLinkThroughClosest = firstLink.closest('a')

console.log(firstLinkThroughClosest)
// <a href="#">Link 1</a>

closest is pretty new. It doesn’t work on IE Edge 14 and below. It doesn’t work on Opera mini too. If you need to support older browsers, you may want to use a polyfill.

Traversing sideways

There are three methods to traverse sideways:

  1. nextElementSibling
  2. previousElementSibling
  3. Combining parentElement, children, and index.

nextElementSibling

You can select the next element with nextElementSibling.

const nextElem = Node.nextElementSibling
<ul class="list">
  <li><a href="#">Link 1</a></li>
  <li><a href="#">Link 2</a></li>
  <li><a href="#">Link 3</a></li>
  <li><a href="#">Link 4</a></li>
  <li><a href="#">Link 5</a></li>
</ul>
const firstListItem = document.querySelector('li')
const secondListItem = firstListItem.nextElementSibling

console.log(secondListItem)
// <li><a href="#">Link 2</a></li>

previousElementSibling

Likewise, you can select the previous element with previousElementSibling.

<ul class="list">
  <li><a href="#">Link 1</a></li>
  <li><a href="#">Link 2</a></li>
  <li><a href="#">Link 3</a></li>
  <li><a href="#">Link 4</a></li>
  <li><a href="#">Link 5</a></li>
</ul>
const secondListItem = document.querySelectorAll('li')[1]
const firstListItem = secondListItem.previousElementSibling

console.log(firstListItem)
// <li><a href="#">Link 1</a></li>

Combining parentElement, children, and index

This method lets you select a specific sibling. It’s easier to explain how it works with an example, so let’s do that. Say you want to select the fourth item from the first item in this HTML.

<ul class="list">
  <li><a href="#">Link 1</a></li>
  <li><a href="#">Link 2</a></li>
  <li><a href="#">Link 3</a></li>
  <li><a href="#">Link 4</a></li>
  <li><a href="#">Link 5</a></li>
</ul>

Let’s say you already have the first item:

const firstItem = document.querySelector('li')

To select the fourth item, you can use firstItem.parentElement to get the list, then list.children to get a HTML Collection. Once you have the HTML Collection, you can find the fourth item by using a index of 3. (Remember, zero-based index!).

const firstItem = document.querySelector('li')
const list = firstItem.parentElement
const allItems = list.children
const fourthItem = allItems[3]

console.log(fourthItem)
// <li><a href="#">Link 4</a></li>

Putting everything together in one step:

const firstItem = document.querySelector('li')
const fourthItem = firstITem.parentElement.children[3]

console.log(fourthItem)
// <li><a href="#">Link 4</a></li>

Exercise

Practice traversing the DOM with the methods taught in this lesson. With the HTML given below, do these tasks:

  1. Select .characters with document.querySelector
  2. Select .humans from .characters
  3. Select all humans with querySelectorAll, starting from .humans
  4. Select all hobbits with children
  5. Select the Merry (the hobbit)
  6. Select .enemies from Sauron
  7. Select the .characters div from Nazgûl
  8. Select Elrond from Glorfindel
  9. Select Legolas from Glorfindel
  10. Select Arwen from Glorfindel
<div class="characters">
  <ul class="hobbits">
    <li>Frodo Baggins</li>
    <li>Samwise "Sam" Gamgee</li>
    <li>Meriadoc "Merry" Brandybuck</li>
    <li>Peregrin "Pippin" Took</li>
    <li>Bilbo Baggins</li>
  </ul>
  <ul class="humans">
    <li>Gandalf</li>
    <li>Saruman</li>
    <li>Aragorn</li>
    <li>Boromir</li>
    <li>Faramir</li>
  </ul>
  <ul class="elves">
    <li>Legolas</li>
    <li>Glorfindel</li>
    <li>Elrond</li>
    <li>Arwen Evenstar</li>
  </ul>
  <ul class="enemies">
    <li>Sauron</li>
    <li>Nazgûl</li>
  </ul>
</div>

Wrapping up

You learned how to traverse the DOM in three directions—downwards, upwards, and sideways—in this lesson. Here’s a quick bullet point to summarize the methods you learned:

  1. Traversing downwards
    1. element.querySelector
    2. element.querySelectorAll
    3. element.children
  2. Traversing upwards
    1. element.parentElement
    2. element.closest
  3. Traversing sideways
    1. element.nextElementSibling
    2. element.previousElementSibling
    3. Combine parentElement, children, and index

I hope this lesson helps clarify why we traverse the DOM and how you can do it.

#javascript #js #programming 

How to Navigate the DOM in JavaScript

40 JavaScript Projects for Beginners [Code Included]

The best way to learn a new programming language is to build projects.

I have created a list of 40 beginner friendly project tutorials in Vanilla JavaScript, React, and TypeScript.

My advice for tutorials would be to watch the video, build the project, break it apart and rebuild it your own way. Experiment with adding new features or using different methods.

That will test if you have really learned the concepts or not.

Vanilla JavaScript Projects

  1. How to create a Color Flipper
  2. How to create a counter
  3. How to create a review carousel
  4. How to create a responsive navbar
  5. How to create a sidebar
  6. How to create a modal
  7. How to create a FAQ page
  8. How to create a restaurant menu page
  9. How to create a video background
  10. How to create a navigation bar on scroll
  11. How to create tabs that display different content
  12. How to create a countdown clock
  13. How to create your own Lorem ipsum
  14. How to create a grocery list
  15. How to create an image slider
  16. How to create a Rock Paper Scissors game
  17. How to create a Simon Game
  18. How to create a Platformer Game
  19. How to create Doodle Jump
  20. How to create Flappy Bird
  21. How to create a Memory game
  22. How to create a Whack-a-mole game
  23. How to create Connect Four game
  24. How to create a Snake game
  25. How to create a Space Invaders game
  26. How to create a Frogger game
  27. How to create a Tetris game

React Projects

  1. How to build a Tic-Tac-Toe game using React Hooks
  2. How to build a Tetris Game using React Hooks
  3. How to create a Birthday Reminder App
  4. How to create a tours page
  5. How to create an accordion menu
  6. How to create tabs for a portfolio page
  7. How to create a review slider
  8. How to create a color generator
  9. How to create a Stripe payment menu page
  10. How to create a shopping cart page
  11. How to create a cocktail search page

TypeScript Projects

  1. How to build a Quiz App with React and TypeScript
  2. How to create an Arkanoid game with TypeScript

Vanilla JavaScript Projects

If you have not learned JavaScript fundamentals, then I would suggest watching this course before proceeding with the projects.

Many of the screenshots below are from here.

How to create a Color Flipper

color-flipper

In this John Smilga tutorial, you will learn how to create a random background color changer. This is a good project to get you started working with the DOM.

In Leonardo Maldonado's article on why it is important to learn about the DOM, he states:

By manipulating the DOM, you have infinite possibilities. You can create applications that update the data of the page without needing a refresh. Also, you can create applications that are customizable by the user and then change the layout of the page without a refresh.

Key concepts covered:

  • arrays
  • document.getElementById()
  • document.querySelector()
  • addEventListener()
  • document.body.style.backgroundColor
  • Math.floor()
  • Math.random()
  • array.length

Before you get started, I would suggest watching the introduction where John goes over how to access the setup files for all of his projects.

How to create a Counter

counter

In this John Smilga tutorial, you will learn how to create a counter and write conditions that change the color based on positive or negative numbers displayed.

This project will give you more practice working with the DOM and you can use this simple counter in other projects like a pomodoro clock.

Key concepts covered:

  • document.querySelectorAll()
  • forEach()
  • addEventListener()
  • currentTarget property
  • classList
  • textContent

How to create a Review carousel

reviewsIn this tutorial, you will learn how to create a carousel of reviews with a button that generates random reviews.

This is a good feature to have on an ecommerce site to display customer reviews or a personal portfolio to display client reviews.

Key concepts covered:

  • objects
  • DOMContentLoaded
  • addEventListener()
  • array.length
  • textContent

How to create a responsive Navbar

navbar-1

In this tutorial, you will learn how to create a responsive navbar that will show the hamburger menu for smaller devices.

Learning how to develop responsive websites is an important part of being a web developer. This is a popular feature used on a lot of websites.

Key concepts covered:

  • document.querySelector()
  • addEventListener()
  • classList.toggle()

How to create a Sidebar

sidebar

In this tutorial, you will learn how to create a sidebar with animation.

This is a cool feature that you can add to your personal website.

Key concepts covered:

  • document.querySelector()
  • addEventListener()
  • classList.toggle()
  • classList.remove()

How to create a Modal

modal

In this tutorial, you will learn how to create a modal window which is used on websites to get users to do or see something specific.

A good example of a modal window would be if a user made changes in a site without saving them and tried to go to another page. You can create a modal window that warns them to save their changes or else that information will be lost.

Key concepts covered:

  • document.querySelector()
  • addEventListener()
  • classList.add()
  • classList.remove()

How to create a FAQ page

FAQ-section

In this tutorial, you will learn how to create a frequently asked questions page which educates users about a business and drives traffic to the website through organic search results.    

Key concepts covered:

  • document.querySelectorAll()
  • addEventListener()
  • forEach()
  • classList.remove()
  • classList.toggle()

How to create a restaurant menu page

menu

In this tutorial, you will learn how to make a restaurant menu page that filters through the different food menus. This is a fun project that will teach you higher order functions like map, reduce, and filter.

In Yazeed Bzadough's article on higher order functions, he states:

the greatest benefit of HOFs is greater reusability.

Key concepts covered:

  • arrays
  • objects
  • forEach()
  • DOMContentLoaded
  • map, reduce, and filter
  • innerHTML
  • includes method

How to create a video background

video-1

In this tutorial, you will learn how to make a video background with a play and pause feature.  This is a common feature found in a lot of websites.

Key concepts covered:

  • document.querySelector()
  • addEventListener()
  • classList.contains()
  • classList.add()
  • classList.remove()
  • play()
  • pause()

How to create a navigation bar on scroll

scroll-page

In this tutorial, you will learn how to create a navbar that slides down when scrolling and then stays at a fixed position at a certain height.

This is a popular feature found on many professional websites.

Key concepts covered:

  • document.getElementById()
  • getFullYear()
  • getBoundingClientRect()
  • slice method
  • window.scrollTo()

How to create tabs that display different content

tabs

In this tutorial, you will learn how to create tabs that will display different content which is useful when creating single page applications.

Key concepts covered:

  • classList.add()
  • classList.remove()
  • forEach()
  • addEventListener()

How to create a countdown clock

countdown

In this tutorial, you will learn how to make a countdown clock which can be used when a new product is coming out or a sale is about to end on an ecommerce site.

Key concepts covered:

  • getFullYear()
  • getMonth()
  • getDate()
  • Math.floor()
  • setInterval()
  • clearInterval()

How to create your own Lorem ipsum

lorem-ipsum

In this tutorial, you will learn how to create your own Lorem ipsum generator.

Lorem ipsum is the go to placeholder text for websites. This is a fun project to show off your creativity and create your own text.

Key concepts covered:

  • parseInt()
  • Math.floor()
  • Math.random()
  • isNaN()
  • slice method
  • event.preventDefault()

How to create a grocery list

grocery-list

In this tutorial, you will learn how to update and delete items from a grocery list and create a simple CRUD (Create, Read, Update, and Delete) application.

CRUD plays a very important role in developing full stack applications. Without it, you wouldn't be able to do things like edit or delete posts on your favorite social media platform.  

Key concepts covered:

  • DOMContentLoaded
  • new Date()
  • createAttribute()
  • setAttributeNode()
  • appendChild()
  • filter()
  • map()

How to create an image slider

image-slider

In this tutorial, you will learn how to build an image slider that you can add to any website.

Key concepts covered:

  • querySelectorAll()
  • addEventListener()
  • forEach()
  • if/else statements

How to create a Rock Paper Scissors game

rock-paper-scissors

In this tutorial, Tenzin will teach you how to create a Rock Paper Scissors game. This is a fun project that will give more practice working with the DOM.

Key concepts covered:

  • addEventListener()
  • Math.floor()
  • Math.random()
  • switch statements

How to create a Simon Game

simon-game

In this tutorial, Beau Carnes will teach you how to create the classic Simon Game. This is a good project that will get you thinking about the different components behind the game and how you would build out each of those functionalities.

Key concepts covered:

  • querySelector()
  • addEventListener()
  • setInterval()
  • clearInterval()
  • setTimeout()
  • play()
  • Math.floor()
  • Math.random()

How to create a Platformer Game

platformer-game

In this tutorial, Frank Poth will teach you how to build a platformer game. This project will introduce you to Object Oriented Programming principles and the Model, View, Controller software pattern.

Key concepts covered:

  • this keyword
  • for loop
  • switch statements
  • OOP principles
  • MVC pattern
  • Canvas API

How to create Doodle Jump and Flappy Bird

doodle-jump

In this video series, Ania Kubow will teach you how to build Doodle Jump and Flappy Bird.

Building games are a fun way to learn more about JavaScript and will cover many popular JavaScript methods.

Key concepts covered:

  • createElement()
  • forEach()
  • setInterval()
  • clearInterval()
  • removeChild()
  • appendChild()
  • addEventListener()
  • removeEventListener()

How to create seven classic games with Ania Kubow

7-js-games

You will have a lot of fun creating seven games in this course by Ania Kubow:

  1. Memory Game
  2. Whack-a-mole
  3. Connect Four
  4. Snake
  5. Space Invaders
  6. Frogger
  7. Tetris

Key concepts covered:

  • for loops
  • onclick event
  • arrow functions
  • sort()
  • pop()
  • unshift()
  • push()
  • indexOf()
  • includes()
  • splice()
  • concat()

React Projects

If you are not familiar with React fundamentals, then I would suggest taking this course before proceeding with the projects.

How to build a Tic-Tac-Toe game using React Hooks

tic-tac-game-1

In this freeCodeCamp article, Per Harald Borgen talks about Scrimba's Tic-Tac-Toe game tutorial led by Thomas Weibenfalk. You can view the video course on Scimba's YouTube Channel.

This is a good project to start getting comfortable with React basics and working with hooks.

Key concepts covered:

  • useState()
  • import / export
  • JSX

How to build a Tetris Game using React Hooks

react-tetris-1

In this tutorial, Thomas Weibenfalk will teach you how to build a Tetris game using React Hooks and styled components.

Key concepts covered:

  • useState()
  • useEffect()
  • useRef()
  • useCallback()
  • styled components

How to create a Birthday Reminder App

brithday-app

Screenshot from https://react-projects.netlify.app/

In this John Smilga course, you will learn how to create a birthday reminder app. This is a good project to start getting comfortable with React basics and working with hooks.

I would also suggest watching John's video on the startup files for this project.

Key concepts covered:

  • useState()
  • import / export
  • JSX
  • map()

How to create a Tours Page

tours-page

Screenshot from https://react-projects.netlify.app/

In this tutorial, you will learn how to create a tours page where the user can delete which tours they are not interested in.

This will give you practice with React hooks and the async/await pattern.

Key concepts covered:

  • try...catch statement
  • async/await pattern
  • useEffect()
  • useState()

How to create an accordion menu

accordion-react

Screenshot from https://react-projects.netlify.app/

In this tutorial, you will learn how to create a questions and answers accordion menu. These menus can be helpful in revealing content to users in a progressive way.

Key concepts covered:

  • React icons
  • useState()
  • map()

How to create tabs for a portfolio page

tabs-portfolio-page-react

Screenshot from https://react-projects.netlify.app/

In this tutorial, you will learn how to create tabs for a mock portfolio page. Tabs are useful when you want to display different content in single page applications.

Key concepts covered:

  • async/await pattern
  • React icons
  • useEffect()
  • useState()

How to create a review slider

react-slider

Screenshot from https://react-projects.netlify.app/

In this tutorial, you will learn how to create a review slider that changes to a new review every few seconds.

This is a cool feature that you can incorporate into an ecommerce site or portfolio.

Key concepts covered:

  • React icons
  • useEffect()
  • useState()
  • map()

How to create a color generator

react-color-generator

Screenshot from https://react-projects.netlify.app/

In this tutorial, you will learn how to create a color generator. This is a good project to continue practicing working with hooks and setTimeout.

Key concepts covered:

  • setTimeout()
  • clearTimeout()
  • useEffect()
  • useState()
  • try...catch statement
  • event.preventDefault()

How to create a Stripe payment menu page

stripe-page

Screenshot from https://react-projects.netlify.app/

In this tutorial, you will learn how to create a Stripe payment menu page. This project will give you good practice on how to design a product landing page using React components.

Key concepts covered:

  • React icons
  • useRef()
  • useEffect()
  • useState()
  • useContext()

How to create a shopping cart page

shopping-cart-page

Screenshot from https://react-projects.netlify.app/

In this tutorial, you will learn how to create a shopping cart page that updates and deletes items. This project will also be a good introduction to the useReducer hook.

Key concepts covered:

  • map()
  • filter()
  • <svg> elements
  • useReducer()
  • useContext()

How to create a cocktail search page

cocktails-page

Screenshot from https://react-projects.netlify.app/

In this tutorial, you will learn how to create a cocktail search page. This project will give you an introduction to how to use React router.

React router gives you the ability to create a navigation on your website and change views to different components like an about or contact page.

Key concepts covered:

  • <Router>
  • <Switch>
  • useCallback()
  • useContext()
  • useEffect()
  • useState()

TypeScript Projects

If you are unfamiliar with TypeScript, then I would suggest watching this course before proceeding with this project.

How to build a Quiz App with React and TypeScript

quiz-app

In this tutorial, Thomas Weibenfalk will teach you how to build a quiz app with React and TypeScript. This is a good opportunity to practice the basics of TypeScript.

Key concepts covered:

  • React.FC
  • styled components
  • dangerouslySetInnerHTML

How to create an Arkanoid game with TypeScript

akrnoid-game

In this tutorial, Thomas Weibenfalk will teach you how to build the classic Arkanoid game in TypeScript. This is a good project that will give you practice working with the basic concepts for TypeScript.

Key concepts covered:

  • Types
  • Classes
  • Modules
  • HTMLCanvasElement


I hope you enjoy this list of 40 project tutorials in Vanilla JavaScript, React and TypeScript.

Happy coding!

Original article source at https://www.freecodecamp.org

#javascript #js #programming #developer #react #typescript 

40 JavaScript Projects for Beginners [Code Included]
Alfie Mellor

Alfie Mellor

1650870061

JavaScript Output Explained with Examples

JavaScript Output defines the ways to display the output of a given code. 

JavaScript Display Possibilities

JavaScript can "display" data in different ways:

  • Writing into an HTML element, using innerHTML.
  • Writing into the HTML output using document.write().
  • Writing into an alert box, using window.alert().
  • Writing into the browser console, using console.log().

Using innerHTML

To access an HTML element, JavaScript can use the document.getElementById(id) method.

The id attribute defines the HTML element. The innerHTML property defines the HTML content:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My First Paragraph</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>

</body>
</html>

Using document.write()

For testing purposes, it is convenient to use document.write():

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<script>
document.write(5 + 6);
</script>

</body>
</html>

Using document.write() after an HTML document is loaded, will delete all existing HTML:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<button type="button" onclick="document.write(5 + 6)">Try it</button>

</body>
</html>

The document.write() method should only be used for testing.


Using window.alert()

You can use an alert box to display data:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<script>
window.alert(5 + 6);
</script>

</body>
</html>

You can skip the window keyword.

In JavaScript, the window object is the global scope object, that means that variables, properties, and methods by default belong to the window object. This also means that specifying the window keyword is optional:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<script>
alert(5 + 6);
</script>

</body>
</html>

Using console.log()

For debugging purposes, you can call the console.log() method in the browser to display data.

Example

<!DOCTYPE html>
<html>
<body>

<script>
console.log(5 + 6);
</script>

</body>
</html>

JavaScript Print

JavaScript does not have any print object or print methods.

You cannot access output devices from JavaScript.

The only exception is that you can call the window.print() method in the browser to print the content of the current window.

Example

<!DOCTYPE html>
<html>
<body>

<button onclick="window.print()">Print this page</button>

</body>
</html>

#javascript #js #programming

JavaScript Output Explained with Examples