Dirk Harriman Banner Image

 

Notes Javascript - Functions


 

 

Functions


There are a few different ways to create a function. There are also a set of predefined functions.


 

Function Declaration

A function definition (also called a function declaration, or function statement) consists of the function keyword, followed by:

For example, the following code defines a simple function named square:

function square(number) { return number * number; }

Parameters are essentially passed to functions by value, so if the code within the body of a function assigns a completely new value to a parameter that was passed to the function, the change is not reflected globally or in the code which called that function.

When you pass an object as a parameter, if the function changes the object's properties, that change is visible outside the function, as shown in the following example:

function myFunc(theObject) { theObject.make = "Toyota"; } const mycar = { make: "Honda", model: "Accord", year: 1998, }; // x gets the value "Honda" const x = mycar.make; // the make property is changed by the function myFunc(mycar); // y gets the value "Toyota" const y = mycar.make;

When you pass an array as a parameter, if the function changes any of the array's values, that change is visible outside the function, as shown in the following example:

function myFunc(theArr) { theArr[0] = 30; } const arr = [45]; console.log(arr[0]); // 45 myFunc(arr); console.log(arr[0]); // 30

Show Car Function Call
 

Function Expression

While the function declaration above is syntactically a statement, functions can also be created by a function expression.

Such a function can be anonymous; it does not have to have a name. For example, the function square could have been defined as:

const square = function (number) { return number * number; }; const x = square(4); // x gets the value 16

Adding A Name To Allow Recursion

However, a name can be provided with a function expression. Providing a name allows the function to refer to itself, as in a recursive call, and also makes it easier to identify the function in a debugger's stack traces:

// EXAMPLE OF A RECURSIVE FUNCTION EXPRESSION const factorial = function fac(n) { return n < 2 ? 1 : n * fac(n - 1); }; console.log(factorial(3));

Function As A Parameter

Function expressions are convenient when passing a function as an argument to another function. The following example shows a map function that should receive a function as first argument and an array as second argument:

// FUNCTION TAKES TWO PARAMETERS - A FUNCTION f, AND AN ARRAY a. function map(f, a) { const result = new Array(a.length); // BUILD A RESULT ARRAY THE SAME SIZE AS THE INPUT ARRAY for (let i = 0; i < a.length; i++) { // LOOP THROUGH INPUT ARRAY a result[i] = f(a[i]); // ASSIGN THE RESULT OF A FUNCTION CALL TO f TO RESULT ARRAY } return result; // REURN THE RESULT ARRAY }

Example Of Function As A Parameter

In the following code, the function receives a function defined by a function expression and executes it for every element of the array received as a second argument:

// FUNCTION TAKES TWO PARAMETERS - A FUNCTION f, AND AN ARRAY a. function map(f, a) { const result = new Array(a.length); // BUILD A RESULT ARRAY THE SAME SIZE AS THE INPUT ARRAY for (let i = 0; i < a.length; i++) { // LOOP THROUGH INPUT ARRAY a result[i] = f(a[i]); // ASSIGN THE RESULT OF A FUNCTION CALL TO f TO RESULT ARRAY } return result; // REURN THE RESULT ARRAY } // CREATE A FUNCTION f, TO PASSED INTO THE ABOVE FUNCTION const f = function (x) { return x * x * x; }; // CREATE AN ARRAY TO BE PASSED INTO THE ABOVE FUNCTION const numbers = [0, 1, 2, 5, 10]; // MAKE FUNCTION CALL TO ABOVE FUNCTION USING THE FUNCTION f AND THE ARRAY numbers const cube = map(f, numbers); console.log(cube);

Show Result

Function returns: [0, 1, 8, 125, 1000].

In JavaScript, a function can be defined based on a condition. For example, the following function definition defines myFunc only if num equals 0:

let myFunc; if (num === 0) { myFunc = function (theObject) { theObject.make = "Toyota"; }; }

Calling Functions

A function within scope can be called by simply using its name and parameters if it has any. Functions are hoisted so it doesn't matter where it is called, but good programming practice would be to declare the function in the code before calling it. There are other ways to call functions. There are often cases where a function needs to be called dynamically, or the number of arguments to a function vary, or in which the context of the function call needs to be set to a specific object determined at runtime.

Functions Are Objects

It turns out that functions are themselves objects, and in turn, these objects have methods. (See the Function object.) The call() and apply() methods can be used to achieve this goal.

Functions & Scope

Functions must be in scope when they are called, but the function declaration can be hoisted (appear below the call in the code). The scope of a function declaration is the function in which it is declared (or the entire program, if it is declared at the top level).

The scope of variables and functions depend upon where they are placed within the hierarchy of the code. Variables and functions declared at the root level of the code are global. The scope of variables and functions declared within a closure are only available within the closure unless they are exposed to the outside.

Function Arguments

The arguments of a function are not limited to strings and numbers. You can pass whole objects to a function. The showProps() function (defined in Working with objects) is an example of a function that takes an object as an argument.

Function Scope

Variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function. However, a function can access all variables and functions defined inside the scope in which it is defined.

In other words, a function defined in the global scope can access all variables defined in the global scope. A function defined inside another function can also access all variables defined in its parent function, and any other variables to which the parent function has access.

// THE FOLLOWING VARIABLES ARE DEFINED IN THE GLOBAL SCOPE const num1 = 20; const num2 = 3; const name = "Chamakh"; // THIS FUNCTION IS DEFINED IN THE GLOBAL SCOPE function multiply() { return num1 * num2; } multiply(); // Returns 60 // A NESTED FUNCTION EXAMPLE function getScore() { const num1 = 2; const num2 = 3; function add() { return `${name} scored ${num1 + num2}`; } return add(); } getScore(); // RETURNS "Chamakh scored 5"

Recursion

A function can refer to and call itself. There are two ways for a function to refer to itself:

1. The function's name
2. An in-scope variable that refers to the function

For example, consider the following function definition:

const foo = function bar() { // statements go here };

Within the function body, the following are all equivalent:

1. bar()
2. foo()
Recursion & The Stack

Recursive functions use something called the "call stack". When a program calls a function, that function goes on top of the call stack. This is similar to a stack of books. You add things one at a time. Then, when you are ready to take something off, you always take off the top item.

Recursion uses the stack to keep track of states. Each recursive call that doesn't meet the exit condition will push its state onto the stack. When the exit condition is met, it starts popping the stack.

Recursion Debugging

Recursive functions can be difficult to debug. The easiest way to work through the code is by keeping track of what is on the stack. Consider the following recursive function call.

function loop(x) { // "x >= 5" IS THE EXIT CONDITION (EQUIVALENT TO "!(x < 10)") if (x >= 5) { return; } // DO STUFF loop(x + 1); // THE RECURSIVE CALL // WHERE THE CODE GOES AFTER EXIT CONDITION IS MET AND return IS CALLED } loop(0);

Show Loop Stack
Iteration Action The Stack
1 The parameter 0 is not greater than or equal to 5, so it is placed on the "call stack" and a recursive call is made to loop(0+1 = 1) 0
2 The parameter 1 is not greater than or equal to 5, so it is placed on the "call stack" and a recursive call is made to loop(1+1 = 2) 1
0
3 The parameter 2 is not greater than or equal to 5, so it is placed on the "call stack" and a recursive call is made to loop(2+1 = 3) 2
1
0
4 The parameter 3 is not greater than or equal to 5, so it is placed on the "call stack" and a recursive call is made to loop(3+1 = 4) 3
2
1
0
5 The parameter 4 is not greater than or equal to 5, so it is placed on the "call stack" and a recursive call is made to loop(4+1 = 5) 4
3
2
1
0
6 The parameter 5 is equal to 5, the exit condition is met, so the return statement is called,
The code upon return that is executed is the code following the recursive call,
In this function there is no code, so the "call stack" is popped until it's empty.
3
2
1
0
7 The "call stack" is popped. 2
1
0
8 The "call stack" is popped. 1
0
9 The "call stack" is popped. 0
10 The "call stack" is empty. (Empty Call Stack)

 

Anonymous Function Expression

In the following function expression has an anonymous function. An anonymous function has no name assigned to it.

const square = function (number) { return number * number; }; const x = square(4); // x gets the value 16

IIEF - Immediately Invoked Function Expression

Sometimes you may want to have a function that executes whenever a page is loaded. This is how Javascript frameworks like jQuery are set up.
An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.

(function () { // ... })(); (() => { // ... })(); (async () => { // ... })();

It is a design pattern which is also known as a Self-Executing Anonymous Function and contains two major parts:

1. The first is the anonymous function with lexical scope enclosed within the Grouping Operator (). This prevents accessing variables within the IIFE idiom as well as polluting the global scope.
2. The second part creates the immediately invoked function expression () through which the JavaScript engine will directly interpret the function.

Breakdown Of IIFE

The anonymous function:

(function(){ // CODE HERE })

What makes it self-executing, adding the () to the end:

(function(){ // CODE HERE })();

All variables and functions defined within the anonymous function are not available to the code outside of it, effectively closing the code off;
sealing itself from the outside world. This is known as closure.

The following code will fail because the function calls are made outside of the closure and they are out of scope at the global level.

(function(){ var foo = 'Hello'; var bar = 'World!' function baz(){ return foo + ' ' + bar; } })(); // THESE ALL THROW EXCEPTIONS: console.log(foo); console.log(bar); console.log(baz());

Granting Access To Closure Elements

To allow access to a variable or function, we need to expose it to the global "window" object.

(function(){ var foo = 'Hello'; var bar = 'World!' function baz(){ return foo + ' ' + bar; } window.baz = baz; // ASSIGN 'baz' TO THE GLOBAL VARIABLE 'baz'... })(); console.log(baz()); // AND NOW THIS WORKS // IT IS IMPORTANT TO NOTE THAT THESE STILL WON'T WORK: console.log(foo); console.log(bar);


 

One of the major benefits of this pattern is that you can limit access to variables and functions within your closure, essentially making them private and only choosing to expose an API of your choice to the global scope.

It is common with the use of IIFE to pass in some commonly used objects, such as the window object and or the jQuery object. Passing in the jQuery object will allow jquery to work within the closure.

(function(window, jQuery){ var foo = 'Hello'; var bar = 'World!' function baz(){ return foo + ' ' + bar; } // IN THIS CONTEXT, 'window' REFERS TO THE PARAMETER window.baz = baz; })(window, jQuery); // PASS IN A REFERENCE TO THE GLOBAL WINDOW OBJECT AND THE JQUERY OBJECT

Rename Passed In Objects

When minifying your code, this design pattern will yield great results. All references to window in your code can be renamed to w, jQuery to $ symbol and doc to document, for example:

(function(w, doc, $){ console.log(w === window); //Returns 'true' })(window, document, jQuery);

Avoid Polluting The Global Namespace

Because our application could include many functions and global variables from different source files, it's important to limit the number of global variables. If we have some initiation code that we don't need to use again, we could use the IIFE pattern. As we will not reuse the code again, using IIFE in this case is better than using a function declaration or a function expression.

(() => { // some initiation code let firstVariable; let secondVariable; })(); // firstVariable and secondVariable will be discarded after the function is executed.

Execute An Async Function

An async IIFE allows you to use await and for-await even in older browsers and JavaScript runtimes that have no top-level await:

const getFileStream = async (url) => { // implementation }; (async () => { const stream = await getFileStream("https://domain.name/path/file.ext"); for await (const chunk of stream) { console.log({ chunk }); } })();

The Module Pattern

We would also use IIFE to create private and public variables and methods. For a more sophisticated use of the module pattern and other use of IIFE, you could see the book Learning JavaScript Design Patterns by Addy Osmani.

const makeWithdraw = (balance) => ((copyBalance) => { let balance = copyBalance; // THIS VARIABLE IS PRIVATE const doBadThings = () => { console.log("I will do bad things with your money"); }; doBadThings(); return { withdraw(amount) { if (balance >= amount) { balance -= amount; return balance; } return "Insufficient money"; }, }; })(balance); const firstAccount = makeWithdraw(100); // "I will do bad things with your money" console.log(firstAccount.balance); // undefined console.log(firstAccount.withdraw(20)); // 80 console.log(firstAccount.withdraw(30)); // 50 console.log(firstAccount.doBadThings); // undefined; this method is private const secondAccount = makeWithdraw(20); // "I will do bad things with your money" console.log(secondAccount.withdraw(30)); // "Insufficient money" console.log(secondAccount.withdraw(20)); // 0

Accessing IIEF Elements

Passing in things like the window object can give the code in the closure access to things outside.

In order to expose variables or methods outside of the closure, you'll need to use the window object.

In the following code the methods AddElement and ShowElement are exposed so they can be called outside of the closure.

// IIEF - IMMEDIATELY INVOKED FUNCTION EXPRESSION (function (w, $) { var Element = ""; var RowLimit = 25; var AddElement = function () { Element = "Initialized"; }; var ShowElement = function() { return "Row Limit: "+ RowLimit +'\n'+ "Element: "+ Element; }; var ClearElement = function() { Element = ""; }; w.AddElement = AddElement; w.ShowElement = ShowElement; })(window, jQuery); $(document).ready(function () { AddElement(); }); function runscript5() { resultstr = ShowElement(); alert(resultstr); }

Test IIFE Access
Renaming Methods On The Outside

Sometimes, due to naming conflict, you may need to rename the method in the global environment.

// IIEF - IMMEDIATELY INVOKED FUNCTION EXPRESSION (function (w, $) { var Element = ""; var RowLimit = 22; var AddElement = function () { Element = "Initialized"; }; var ShowElement = function() { return "Row Limit: "+ RowLimit +'\n'+ "Element: "+ Element; }; var Clearlement = function() { Element = ""; }; w.AddEl = AddElement; // RENAMED FOR OUTSIDE API w.ShowEl = ShowElement; // RENAMED FOR OUTSIDE API })(window, jQuery); $(document).ready(function () { AddEl(); }); function runscript5() { resultstr = ShowEl(); alert(resultstr); }

 
 
 

Nested Functions & Closures

You may nest a function within another function. The nested (inner) function is private to its containing (outer) function.

It also forms a closure. A closure is an expression (most commonly, a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).

Since a nested function is a closure, this means that a nested function can "inherit" the arguments and variables of its containing function. In other words, the inner function contains the scope of the outer function.

To summarize:

The following example shows nested functions:

function addSquares(a, b) { function square(x) { return x * x; } return square(a) + square(b); } const a = addSquares(2, 3); // returns 13 const b = addSquares(3, 4); // returns 25 const c = addSquares(4, 5); // returns 41

Since the inner function forms a closure, you can call the outer function and specify arguments for both the outer and inner function:

function outside(x) { function inside(y) { return x + y; } return inside; } const fnInside = outside(3); // THINK OF IT LIKE: GIVE ME A FUNCTION THAT ADDS 3 TO WHATEVER YOU GIVE IT const result1 = fnInside(5); // RETURNS 8 const result2 = outside(3)(5); // RETURNS 8

Test Nested
Preservation Of Variables

Notice how x is preserved when inside is returned. A closure must preserve the arguments and variables in all scopes it references. Since each call provides potentially different arguments, a new closure is created for each call to outside. The memory can be freed only when the returned inside is no longer accessible.

This is not different from storing references in other objects, but is often less obvious because one does not set the references directly and cannot inspect them.

Multiply-Nested Functions

Functions can be multiply-nested. For example:

Thus, the closures can contain multiple scopes; they recursively contain the scope of the functions containing it. This is called scope chaining.

Consider the following example:

function A(x) { function B(y) { function C(z) { console.log(x + y + z); } C(3); } B(2); } A(1); // Logs 6 (which is 1 + 2 + 3)

In this example, C accesses B's y and A's x.

This can be done because:

The reverse, however, is not true. A cannot access C, because A cannot access any argument or variable of B, which C is a variable of. Thus, C remains private to only B.


 

Closures

Closures are one of the most powerful features of JavaScript. JavaScript allows for the nesting of functions and grants the inner function full access to all the variables and functions defined inside the outer function (and all other variables and functions that the outer function has access to).

However, the outer function does not have access to the variables and functions defined inside the inner function. This provides a sort of encapsulation for the variables of the inner function.

Also, since the inner function has access to the scope of the outer function, the variables and functions defined in the outer function will live longer than the duration of the outer function execution, if the inner function manages to survive beyond the life of the outer function. A closure is created when the inner function is somehow made available to any scope outside the outer function.

// The outer function defines a variable called "name" const pet = function (name) { const getName = function () { // The inner function has access to the "name" variable of the outer function return name; }; return getName; // Return the inner function, thereby exposing it to outer scopes }; const myPet = pet("Vivie"); myPet(); // Returns "Vivie"

It can be much more complex than the code above. An object containing methods for manipulating the inner variables of the outer function can be returned.

const createPet = function (name) { let sex; const pet = { // setName(newName) IS EQUIVALENT TO setName: function (newName) // IN THIS CONTEXT setName(newName) { name = newName; }, getName() { return name; }, getSex() { return sex; }, setSex(newSex) { if ( typeof newSex === "string" && (newSex.toLowerCase() === "male" || newSex.toLowerCase() === "female") ) { sex = newSex; } }, }; return pet; }; const pet = createPet("Vivie"); pet.getName(); // Vivie pet.setName("Oliver"); pet.setSex("male"); pet.getSex(); // male pet.getName(); // Oliver

In the code above, the name variable of the outer function is accessible to the inner functions, and there is no other way to access the inner variables except through the inner functions. The inner variables of the inner functions act as safe stores for the outer arguments and variables. They hold "persistent" and "encapsulated" data for the inner functions to work with. The functions do not even have to be assigned to a variable, or have a name.

const getCode = (function () { const apiCode = "0]Eal(eh&2"; // A code we do not want outsiders to be able to modify... return function () { return apiCode; }; })(); getCode(); // Returns the apiCode

Avoid Name Conflicts

Note: There are a number of pitfalls to watch out for when using closures!

If an enclosed function defines a variable with the same name as a variable in the outer scope, then there is no way to refer to the variable in the outer scope again. (The inner scope variable "overrides" the outer one, until the program exits the inner scope. It can be thought of as a name conflict.)

const createPet = function (name) { // The outer function defines a variable called "name". return { setName(name) { // The enclosed function also defines a variable called "name". name = name; // How do we access the "name" defined by the outer function? }, }; };


 

The arguments Object

The arguments of a function are maintained in an array-like object. Within a function, you can address the arguments passed to it as follows:

arguments[i];

where i is the ordinal number of the argument, starting at 0. So, the first argument passed to a function would be arguments[0]. The total number of arguments is indicated by arguments.length.

Using the arguments object, you can call a function with more arguments than it is formally declared to accept. This is often useful if you don't know in advance how many arguments will be passed to the function. You can use arguments.length to determine the number of arguments actually passed to the function, and then access each argument using the arguments object.

For example, consider a function that concatenates several strings. The only formal argument for the function is a string that specifies the characters that separate the items to concatenate. The function is defined as follows:

function myConcat(separator) { let result = ""; // initialize list // iterate through arguments for (let i = 1; i < arguments.length; i++) { result += arguments[i] + separator; } return result; }

You can pass any number of arguments to this function, and it concatenates each argument into a string "list":

// returns "red, orange, blue, " myConcat(", ", "red", "orange", "blue"); // returns "elephant; giraffe; lion; cheetah; " myConcat("; ", "elephant", "giraffe", "lion", "cheetah"); // returns "sage. basil. oregano. pepper. parsley. " myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley");

Note: The arguments variable is "array-like", but not an array. It is array-like in that it has a numbered index and a length property. However, it does not possess all of the array-manipulation methods.


 

Function Parameters

There are two special kinds of parameter syntax: default parameters and rest parameters.

Default Parameters

In JavaScript, parameters of functions default to undefined. However, in some situations it might be useful to set a different default value. This is exactly what default parameters do.

In the past, the general strategy for setting defaults was to test parameter values in the body of the function and assign a value if they are undefined.

In the following example, if no value is provided for b, its value would be undefined when evaluating a*b, and a call to multiply would normally have returned NaN. However, this is prevented by the second line in this example:

function multiply(a, b) { b = typeof b !== "undefined" ? b : 1; return a * b; } multiply(5); // 5

With default parameters, a manual check in the function body is no longer necessary. You can put 1 as the default value for b in the function head:

function multiply(a, b = 1) { return a * b; } multiply(5); // 5

Rest Parameters

The rest parameter syntax allows us to represent an indefinite number of arguments as an array, providing a way to represent variadic functions in JavaScript.

Note: In mathematics and in computer programming, a variadic function is a function of indefinite arity, i.e., one which accepts a variable number of arguments.

In the following example, the function multiply uses rest parameters to collect arguments from the second one to the end. The function then multiplies these by the first argument.

function multiply(multiplier, ...theArgs) { return theArgs.map((x) => multiplier * x); } const arr = multiply(2, 1, 2, 3); console.log(arr); // [2, 4, 6]


 

Arrow Functions

An arrow function expression (also called a fat arrow to distinguish from a hypothetical -> syntax in future JavaScript) has a shorter syntax compared to function expressions and does not have its own this, arguments, super, or new.target. Arrow functions are always anonymous.

() => expression param => expression (param) => expression (param1, paramN) => expression () => { statements } param => { statements } (param1, paramN) => { statements }

Two factors influenced the introduction of arrow functions: shorter functions and non-binding of this.

Shorter Functions

In some functional patterns, shorter functions are welcome. Compare:

const a = ["Hydrogen", "Helium", "Lithium", "Beryllium"]; const a2 = a.map(function (s) { return s.length; }); console.log(a2); // [8, 6, 7, 9] const a3 = a.map((s) => s.length); console.log(a3); // [8, 6, 7, 9]

No Separate this

Until arrow functions, every new function defined its own this value (a new object in the case of a constructor, undefined in strict mode function calls, the base object if the function is called as an "object method", etc.). This proved to be less than ideal with an object-oriented style of programming.

function Person() { // The Person() constructor defines `this` as itself. this.age = 0; setInterval(function growUp() { // In nonstrict mode, the growUp() function defines `this` // as the global object, which is different from the `this` // defined by the Person() constructor. this.age++; }, 1000); } const p = new Person();

In ECMAScript 3/5, this issue was fixed by assigning the value in this to a variable that could be closed over.

function Person() { // Some choose `that` instead of `self`. // Choose one and be consistent. const self = this; self.age = 0; setInterval(function growUp() { // The callback refers to the `self` variable of which // the value is the expected object. self.age++; }, 1000); }

Alternatively, a bound function could be created so that the proper this value would be passed to the growUp() function.

An arrow function does not have its own this; the this value of the enclosing execution context is used. Thus, in the following code, the this within the function that is passed to setInterval has the same value as this in the enclosing function:

function Person() { this.age = 0; setInterval(() => { this.age++; // `this` properly refers to the person object }, 1000); } const p = new Person();


 

Exposing Methods In Closures

In the following code, the functions in the closure, AddElement, ShowElement and Clearlement are internal to the closure.

In lines 20 and 21, the internal methods are exposed outside of the closure using the window object which is renamed w in the function parameter list.

// IIEF - IMMEDIATELY INVOKED FUNCTION EXPRESSION (function (w, $) { var Element = ""; var RowLimit = 22; // INTERNAL FUNCTION AddElement var AddElement = function () { Element = "Initialized"; }; // INTERNAL FUNCTION ShowElement var ShowElement = function() { return "Row Limit: "+ RowLimit +'\n'+ "Element: "+ Element; }; // INTERNAL FUNCTION Clearlement var Clearlement = function() { Element = ""; }; // EXPOSING FUNTIONS OUTSIDE OF THE CLOSURE USING THE window OBJECT w.AddEl = AddElement; // RENAMED FOR OUTSIDE API w.ShowEl = ShowElement; // RENAMED FOR OUTSIDE API })(window, jQuery); $(document).ready(function () { AddElement(); // THIS WILL CAUSE AN ERROR }); $(document).ready(function () { AddEl(); // THIS WILL RUN }); function runscript5() { resultstr = ShowElement(); // THIS WILL CAUSE AN ERROR alert(resultstr); } function runscript5() { resultstr = ShowEl(); // THIS WILL RUN alert(resultstr); }

The window Interface Object

The Window interface represents a window containing a DOM document;
the document property points to the DOM document loaded in that window.

A window for a given document can be obtained using the document.defaultView property.

A global variable, window, representing the window in which the script is running, is exposed to JavaScript code.

The Window interface is home to a variety of functions, namespaces, objects, and constructors which are not necessarily directly associated with the concept of a user interface window. However, the Window interface is a suitable place to include these items that need to be globally available.

In a tabbed browser, each tab is represented by its own Window object; the global window seen by JavaScript code running within a given tab always represents the tab in which the code is running. That said, even in a tabbed browser, some properties and methods still apply to the overall window that contains the tab, such as resizeTo() and innerHeight. Generally, anything that can't reasonably pertain to a tab pertains to the window instead.


 

Predefined Functions

JavaScript has several top-level, built-in functions:

eval() The eval() method evaluates JavaScript code represented as a string.
isFinite() The global isFinite() function determines whether the passed value is a finite number. If needed, the parameter is first converted to a number.
isNaN() The isNaN() function determines whether a value is NaN or not. Note: coercion inside the isNaN function has interesting rules; you may alternatively want to use Number.isNaN() to determine if the value is Not-A-Number.
parseFloat() The parseFloat() function parses a string argument and returns a floating point number.
parseInt() The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
decodeURI() The decodeURI() function decodes a Uniform Resource Identifier (URI) previously created by encodeURI or by a similar routine.
decodeURIComponent() The decodeURIComponent() method decodes a Uniform Resource Identifier (URI) component previously created by encodeURIComponent or by a similar routine.
encodeURI() The encodeURI() method encodes a Uniform Resource Identifier (URI) by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).
encodeURIComponent() The encodeURIComponent() method encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).
escape() The deprecated escape() method computes a new string in which certain characters have been replaced by a hexadecimal escape sequence. Use encodeURI or encodeURIComponent instead.
unescape() The deprecated unescape() method computes a new string in which hexadecimal escape sequences are replaced with the character that it represents. The escape sequences might be introduced by a function like escape. Because unescape() is deprecated, use decodeURI() or decodeURIComponent instead.