DEV Community

loading...
Cover image for (Javascript) My learning journey Part 4: Functions

(Javascript) My learning journey Part 4: Functions

ericchapman profile image Eric Chapman ・2 min read

An essential point to remember a training course is to take notes and discuss the subject with others. That's why every day I will post on dev.to the concepts and notes that I learned the day before.

If you want to miss nothing click follow and you are welcome to comments and discuss with me.

Without further ado here is a summary of my notes for day 4.

Functions

A function is a piece of code that we can be re-use over and over again in our code.

function displayHello() {
  console.log('Hello World')
}

// Function can be invoke (run)
displayHello() // 'Hello World'

// Data can be pass to function
function display(greeting) {
  console.log(greeting)
}

// Invoke with the data pass as parameter
display('Hello World') // 'Hello World'


// Function can return value
function sumNumber(number1, number2) {
  return number1 + number2
}

console.log(sumNumber(10, 5)) // 15

Enter fullscreen mode Exit fullscreen mode

Function declaration vs function expression

// Function declaration (can be call before declaration)
function displayGreeting(greeting) {
  return 'Hello ' + greeting
}

// Function expression (can be use in code in place of expression)
const displayGreeting = function (greeting) {
  return 'Hello ' + greeting
}

Enter fullscreen mode Exit fullscreen mode

Arrow Function

// Shorthand function expression 
// 1. Remove the function() keyword 
// 2. Remove curly brace {}
// 3. Remove return keyword 
// 4. Add => between parameters and function body
const displayGreeting = greeting => 'Hello ' + greeting

// With mutli parameters
const addNumber = (number1, number2) => number1 + number2

// With no parameters
const displayGreeting = () => 'Hello World'

// Multi-lines Arrow function
// Bring back the curly brace and return keyword
const displayGreeting = (greeting) => {
  console.log('Hello World')
  console.log('Hello Mike')
  return true 
}

Enter fullscreen mode Exit fullscreen mode

Conclusion

That's it for this part. In the next one we will cover Array and Object!

Discussion (0)

Forem Open with the Forem app