Home > Software engineering >  Having trouble understanding what is going on in code
Having trouble understanding what is going on in code

Time:01-02

Here is some code I'm really having issues understanding (JavaScript)

function func(x) {
     var y = x   2;
     z = 20;
     return function(y) {
         var z = y * 3; 
         return function(z) {
             return x   y   z;
         };
     }; 
 }
 console.log(func(3)(4)("z"));

output: 7z

I have a lot of experience with Java (only Java) and I'm really having issues understanding how JavaScript works. I tried debugging and going step by step over code but I'm still very confused.

One sub-question I have is whether y on line 2 is the same y as in return function(y) line.

Any help would be greatly appreciated!

CodePudding user response:

When looking for value of variable, JS will pick it from the closest scope going upwards.

In line 5, the y is the y from the argument and not from the upper scope. That value although is enclosed (read closures), is not being used here.

Same, goes for the z below.

When running the statement return x y z; the outer scope (that is shadowing the variable y) is destroyed. So the other closes values are used ergo 3 and 4.

function func(x) {
     var y = x   2;
     z = 20;
     return function(y) {
         var z = y * 3; 
         return function(z) {
             return x   y   z;
         };
     }; 
 }
console.log(func(3)(4)("z"));

CodePudding user response:

  1. Get yourself a good code editor for JS (vscode is great and free)
  2. Go to a variable, press F2 and give it a more unique name.
  3. check which occurrences are affected.
  4. "use strict"! what is Strict Mode?

This is what your code then might look like.

"use strict";

function func(arg0) {
  var var1 = arg0   2;
  // undeclared/global variable
  z = 20; 
  return function (arg2) {
    var var2 = arg2 * 3;
    return function (arg4) {
      return arg0   arg2   arg4;
    };
  };
}

console.log(func(3)(4)("z"));

I think this makes it clearer what variable/parameter is what.

And if you run this, you'll get an error regarding your usage of the undeclared variable z, because strict mode doesn't allow this, whereas sloppy mode would create/use a global variable.

Sidenote: Take a look at Typescript. Coming from such a strict language like Java you might prefer the ability to type your code.

CodePudding user response:

What I understand is from this function call is

fun(3)(4)("Z");

first call

x = 3;
y = 5;
z = 20;

second call

y=4; 
z=60;
x=3;

third call

x=3; // from first function parameter
y=4; // y value from second function parameter
z="z" // third function parameter

In the it will return

3 4 "Z" = 7z

as string

All pre calculated values are useless

  • Related