Extenza-Academy / WebDev-100_2021-Q1

24 Lessons, 12 Weeks, Get Started as a Web Developer
2 stars 0 forks source link

2.2.1. Pre-Lecture Quiz #29

Closed mserykh closed 3 years ago

mserykh commented 3 years ago

JavaScript Basics: Methods and Functions

JavaScript Basics - Functions

Sketchnote by Tomomi Imura

Pre-Lecture Quiz

Complete this quiz in class

  1. What's an argument?
  1. True or false: a function must return something
dev-experience commented 3 years ago

No. 2: Why do you say so? What will happen if function doesn't return anything?

(We are in the "JavaScript Basics" topic. In Turbo Pascal it would be different)

mserykh commented 3 years ago

@dev-experience I do not understand a question. Not yours, neither in this assignment.

Functions as I understand return something always. Is that correct? To demonstrate my understanding:

function nothing() {
   5;
}

nothing(); // undefined
dev-experience commented 3 years ago

Well...

If you try it out in the console, console prints all the results of every operation. That's why you see undefined in a console:

image

If you do it in your code, you wouldn't see the difference:

image

Docs say:

A function returns undefined if a value was not returned

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined#Description

So, technically: yes, JavaScript functions always return some value explicitly or implicitly. However, conceptually I wouldn't consider implicit undefined as a returned value.

In other languages, functions can be declared with void as a return type. Which is a way to say that function doesn't return anything. void is a type without a value. So, looks like under the hood, technically all functions return something. However, you can consider that function without return statement or with empty return statement actually doesn't return a value.

Technically they are the same, but conceptually they are different.

function nothing1() {
}

function nothing2() {
  return;
}

function nothing3() {
  return undefined;
}

image

So, in C# it wouldn't be possible to assign the result of such function to a variable:

void Nothing()
{
}

// ...

object o = Nothing(); // CS0029 Cannot implicitly convert type 'void' to 'object'

Please let me know if you have any more questions on that.