Functions in JavaScript
Declaring Functions in Different Ways
Standard Function Declaration
function name() {}
Function Expression
var name = function () {};
Anonymous Function
- Functions without a name, often used in callbacks.
setTimeout(function () {
console.log("This is an anonymous function.");
}, 1000);
Named Function Expression
var name = function funcName() {};
Inline Function with Function Constructor
var func = new Function("a", "b", "return a + b");
console.log(func(1, 2)); // 3
Function Parameters
Passing Function Parameters
- Parameters are passed to functions as arguments.
Local Scope of Arguments
- Arguments passed to a function are local to that function.
function test(a) {
console.log(a); // Local to the function
}
Pass by Value vs Pass by Reference
- Primitive values: Passed by value.
- Objects: Passed by reference.
Passing Functions as Parameters (Callbacks)
- Functions can be passed as arguments.
function greet(callback) {
callback();
}
greet(function () {
console.log("Hello!");
});
Function Behavior Based on Number of Arguments
- Functions can behave differently based on the number or type of arguments passed.
function sum(a, b) {
if (b === undefined) return a;
return a + b;
}
Rest Parameters
- Collects all remaining arguments into an array.
function sum(...args) {
return args.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3)); // 6
arguments
in Functions
- Array-like object containing all arguments passed to the function.
function example() {
console.log(arguments[0]); // First argument
}
example(1, 2); // 1
Breaking Function Execution with return
- Functions can be exited early with
return
.
function test(a) {
if (a > 10) return;
console.log("a is less than or equal to 10");
}
Default Parameters
- Provides default values for parameters.
function greet(name = "Guest") {
console.log(`Hello, ${name}!`);
}
greet(); // Hello, Guest!
Immediate Invoking Functions (IIF)
- Functions executed immediately after their declaration.
(function () {
console.log("I am invoked immediately!");
})();
Closures
- Functions that remember the scope in which they were created.
function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}
const counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2
Currying
- Transforming a function with multiple arguments into a series of functions with a single argument.
function curry(func) {
return function curried(...args) {
if (args.length >= func.length) {
return func(...args);
} else {
return (...nextArgs) => curried(...args, ...nextArgs);
}
};
}
const sum = (a, b, c) => a + b + c;
const curriedSum = curry(sum);
console.log(curriedSum(1)(2)(3)); // 6
Predefined Methods in JavaScript
eval()
- Evaluates a string as JavaScript code.
Note: Use with caution due to security concerns.
eval("console.log(2 + 2)"); // 4
isFinite()
- Checks if a value is a finite number.
isFinite(10); // true
isFinite(Infinity); // false
isNaN()
- Checks if a value is
NaN
.
isNaN("abc"); // true
parseFloat()
- Parses a string and returns a floating-point number.
parseFloat("3.14"); // 3.14
parseInt()
- Parses a string and returns an integer.
parseInt("42px", 10); // 42
decodeURI()
- Decodes a Uniform Resource Identifier (URI).
decodeURI("https%3A%2F%2Fexample.com"); // "https://example.com"
decodeURIComponent()
- Decodes a URI component.
decodeURIComponent("example%20space"); // "example space"
encodeURI()
- Encodes a URI, allowing certain characters:
A-Z
,a-z
,0-9
,; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #
encodeURI("https://example.com?name=John&age=30");
encodeURIComponent()
- Encodes a URI component, escaping additional characters such as
; / ? : @ & = + $ , #
.
encodeURIComponent("John & Jane"); // "John%20%26%20Jane"
escape()
- Encodes a string, but is deprecated.
unescape()
- Decodes a string encoded with
escape()
.