D
D
Dmitry Timoshkin2018-02-07 11:22:18
JavaScript
Dmitry Timoshkin, 2018-02-07 11:22:18

Why is 16 output in this javascript operation?

Hello, I'm a green newbie in javascript, I started reading David Flanagan's book (specially bought for 840 rubles), but I just can't understand why 16 is displayed in this operation? I don't seem to understand the javascript logic.

var x = 2, y = 3;
function plus1(x) {
return x+1;
}
plus1(y)
var square = function(x) {
return x*x;
};
square(plus1(y))

In this construction, 16 is also obtained, although in var I changed the letters to a and b
var a = 2, b = 3;
function plus1(x) {
return x+1;
}
plus1(y)
var square = function(x) {
return x*x;
};
square(plus1(y))

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anton Spirin, 2018-02-07
@dmitriy_timoshkin

Here you need to understand that in the local scope of the plus1 and square functions, x is the value of the dedicated argument, and not the global variable x .

var x = 2, y = 3;
function plus1(x) {
return x + 1;  // тут x это значение которое вы передали при вызове аргументом
}
plus1(y)
var square = function(x) {
return x * x;  // тут тоже
};
square(plus1(y))

Let's analyze the expression:
You have y = 3.
It turns out: At the plus1(3) step:
function plus1(3) {
return 3 + 1;
}

At the output of the first function, we get 4
It turns out: at this step, the following happens:
function(4) {
return 4 * 4;
};

The output is 16

A
Ainur Valiev, 2018-02-07
@vaajnur

in the 1st example, everything is simple, you just need to understand how the functions in Js work. Use the debugger to visually study the work of the js interpreter.
In the 2nd you will not have any result, because. variables y, x are not defined.

N
nluparev, 2018-02-07
@nluparev

I do not understand how it works for you in the 2nd example. There is no identifier y for call expression plus1(y)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question