JavaScript Basic Functions _ Drill down on variables and scope _ basics

Source: Internet
Author: User
Tags abs function definition variable scope

function definitions and calls

Define functions, in JavaScript, to define functions in the following ways:

function ABS (x) { 
if (x >=0) {return 
x;
} else{ 
return-x
}
}

The above ABS () function is defined as follows:

function indicates that this is a functional definition;

ABS is the name of the function;

(x) The parameters of the function are listed in parentheses, separated by multiple parameters;

{...} The code between is a function body, can contain several statements, and can even have no statements.

NOTE: When the statement inside the function body executes, once the return is executed, the function executes and returns the result. Thus the internal adoption of conditional judgments and loops can be very complex in implementation.

If there is no return statement, the function completes after execution and returns the result, except that the result is undefined.

Because the function of JavaScript is also an object, the ABS () function defined above is actually a function object, and the function name ABS can be considered as a variable pointing to the functions.

var abs = function (x) { 
if (x >= 0) {return 
x;
} else { 
return-x;
}
}

In this way, the function (x) {...} is an anonymous function that does not have a function name. However, this anonymous function is assigned to the variable abs, so the function can be called through the variable abs.

The two definitions are completely equivalent, note that the second method needs to add one at the end of the function body according to the complete syntax, and that the assignment statement ends.

When calling a function, you can pass in the arguments in order:

ABS (10); Return 10
ABS (-9); Return 9

Because JavaScript allows you to pass in any argument without being affected, the incoming arguments are no more problematic than the defined parameters, although they are not required within the function.

ABS (a ' blablabla '); Return 10
ABS ( -9, ' haha ', ' hehe ', NULL)//Return 9

The parameters passed in are not as problematic as the definitions

ABS (); Back to Nan

At this point, the parameter X of the ABS (x) function receives the undefined and evaluates to Nan

function ABS (x) { 
if (typeof x!== ' number ') { 
throw ' not a number ':
}
 if (x >=0) {return 
x
}} else{ 
return-x
}
}

Arguments

JavaScript also has a complimentary keyword arguments, which works only within functions and always points to all parameters passed by the caller of the current function.

function foo (x) { 
alert (x);//For
(var i=0 i < arguments.length;++) { 
alert (arguments[i]); 10,20,30
}
foo (10.20,30)

With arguments, you can get all the parameters that the caller passes in. That is, you can get the value of a parameter even if the function does not define any parameters:

function abs () { 
if (arguments.length ===0) {return 
0;
}
var x = arguments[0] return
x >=0? x:-X;
}
ABS (); ABS (0
)//
ABS (-9)//9

In fact, arguments is most commonly used to determine the number of incoming arguments. You may see the wording:

Foo (a[,b],c)

Accept 2~3 parameter, B is optional parameter, if only two parameters, B defaults to null

function foo (a,b,c) { 
if (arguments.length ===2) { 
//The actual obtained parameter is a and B c to undefined
C = b;
b = null; b becomes the default value

To change the middle argument B to an optional argument, you can only judge by arguments, and then resize the argument and assign a value.

Rest parameters

Because JavaScript functions allow you to receive any argument, we have to use arguments to get all the arguments:

function foo (a,b) { 
var i, rest = [];
if (Arguments.length > 2) {for 
(i = 2; i < arguments.length; i++) { 
rest.push (arguments[i]);
}
Console.log (' a = ' + a ');
Console.log (' B = ' + B ');
Console.log (rest);
}

In order to get parameters other than the defined parameters A, B, we had to use arguments, and the loop starts with index 2 to exclude the first two parameters, which is awkward, but is there a better way to get extra rest parameters?

The ES6 standard introduces rest parameters, and the above functions can be rewritten as:

function foo (a,b,... rest) { 
Console.log (' a = ' + a ');
Console.log (' B = ' + B ');
Console.log (rest);
}
Foo (1,2,3,4,5);
Results
//A = 1
//b = 2
//array[3,4,5]
foo (1)
//Results
//A = 1
//b = undefined
//Arra y []

Rest parameters can only be written at the end, preceded by ... The indication, from the operation result, that the incoming argument first binds a, B, and the extra parameters are given to the variable rest in an array form, so

We get all the parameters if we don't need arguments.

It does not matter if the incoming arguments are not filled with the normally defined parameters, and the rest parameter receives an empty array (note that it is not undefined).

Return statement

As we mentioned earlier, the JavaScript engine has a mechanism for automatically adding semicolons at the end of a line, which may give you a big hole in the return statement:

function foo () {return 
{name: ' foo '};
}
Foo (); {name: ' foo '}

To note:

The function foo () {return://is 
automatically added with a semicolon, which is equivalent to return undefined
{name: ' foo '};//The line statement is no longer executable.
}

So the right multi-line notation is

function foo () {return 
{//) does not automatically add a semicolon here because the statement has not yet ended.
name: ' foo '
}
}

Variable scope

In JavaScript, the Var declaration is actually scoped.

If a variable is declared inside the function body, the variable is scoped to the entire function body and should not be referenced outside the function body.

' Use strict ':
function foo () { 
var x = 1;
x = x +1;
}
x = x +2; Refrenceerror cannot reference this variable outside the function body X

If two different functions declare the same variable, then the variable only works in its own function. In other words, variables of the same name within different functions are independent and do not affect each other:

' Use struct ':
function foo () { 
var x = 1;
x = x +1;
}
function Bar () { 
var x= ' A ';
x = x + ' B ';
}

Since JavaScript functions can be nested, internal functions can access variables defined by external functions, and vice versa:

' Use strict ';
function foo () { 
var x =1;
function Bar () { 
var x = 1;
function Bar () { 
var y= x +1;//bar can access Foo's variable x
}
var z = y + 1;//refernceerror! Foo is not allowed to access bar variables y!
}
}

What if the variable name of the internal function and the external function is duplicate?

' Use strict ':
function foo () { 
var x = 1;
function Bar () { 
var x = ' A ';
Alert (' X in bar () = ' + x '); ' A '
}
alert (' X in foo () = ' +x ')//1
Bar ();
}

Variable elevation

The function definition of JavaScript has a feature that scans the statement of the entire function body and "promotes" all declared variables to the top of the function:

' Use strict ';
function foo () { 
var x= ' Hello, ' +y;
alert (x);
var y = ' Bob ';
}
Foo ();

For the above foo () function, the JavaScript engine sees code that is equivalent to:

function foo () { 
var y;//Ascending variable Y's
var x = ' Hello ' + y;
alert (x);
y = ' Bob ';
}

Because of this weird "feature" of JavaScript, when we define variables inside a function, we strictly observe the rule "declare all variables first within a function". The most common practice is to use all the variables used internally by a VAR declaration function:

function foo () { 
var x =1,//x initialized to 1
y = x +1,//y initialized to 2
z,i;//z and I for undefined
//other statements for
(i =0; i&l t;100; i++) { 
...}}
}

Global scope

Variables that are not defined within any function have global scope, in fact, JavaScript defaults to a global scope variable that actually binds to a property of window.

' Use strict ';
var sourse = ' Learn JavaScript ';
Alert (course); ' Learn JavaScript ';
alert (window.course); ' Learn JavaScript '

Name space

Global variables are bound to Windows, and if different JavaScript files use the same global variables, or if the top-level function with the same name is defined, it can cause

Naming conflicts, and it's hard to be found,

One way to reduce conflicts is to bind all of your own variables and functions to a global variable.

The unique Quju opera variable MYAPP
var MYAPP = {};
Other variables:
myapp.name = ' MYAPP ';
Myapp.version = 1.0;

Other functions
Myapp.foo = function () {return 
' foo ';
};

Putting your own code into a unique namespace MyApp can greatly reduce the likelihood of global variable conflicts.

Local scope

Because the variable scope of JavaScript is actually inside the function, we cannot define a variable with a local scope that cannot be defined in a statement block such as a For loop.

function foo () {for 
(var i = 0; i<100; i++) { 
//
}
i+=100;//can still refer to the variable;
}

In order to solve block-level scopes, ES6 introduced a new keyword let, with let instead of Var can declare a block-level scope variables:

function foo () { 
var sum = 0;
for (let i=0; i<100;i++) { 
sum +=i;
}
I +=1;
}

Constant

Because of the variables of Var and let declarations, if you want to declare a constant, it's not going to work before ES6, and we usually mean that it's a constant with all uppercase variables.

Don't change his value.

var PI = 3.14;
The ES6 standard introduces a new keyword const to define constants, and both const and let have block-level scopes;
Const PI = 3.14;
PI = 3;//Some browsers do not complain, but no effect.
PI; 3.14

The above JavaScript basic function _ in-depth analysis of variables and scope is small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.