Js in Functions
Js in Functions
Js in Functions
Function Declarations
Syntax:
Example:
function greet(name) {
return `Hello, ${name}!`;
}
1. Hoisting: Function declarations are hoisted to the top of their scope. This means you
can call the function before it is declared in the code.
console.log(square(5)); // Output: 25
function square(number) {
return number * number;
}
Function Expressions
A function expression defines a function inside an expression and can be either named or
anonymous. It can be assigned to a variable, passed as an argument to another function, or
immediately invoked.
Syntax:
1. Not Hoisted: Function expressions are not hoisted. You cannot call the function
before the expression is evaluated.
2. Anonymous: The function does not necessarily need to have a name. When
anonymous, it is typically assigned to a variable.
3. Use in Callbacks: Function expressions are often used as arguments to other
functions, particularly in callbacks.
setTimeout(function() {
console.log('This runs after 2 seconds');
}, 2000);
Arrow Functions
Arrow functions are a concise way to write function expressions and were introduced in ES6.
They do not have their own this context and are always anonymous.
Syntax:
Example:
If the function body contains only a single expression, you can omit the curly braces and the
return keyword.
console.log(square(4)); // Output: 16
Summary
Function Declarations: Named functions, hoisted to the top of their scope, can be
called before they are defined.
Function Expressions: Functions defined within an expression, not hoisted, can be
anonymous or named, used in callbacks and other expressions.
Arrow Functions: A more concise syntax for function expressions, always
anonymous, with no own this context.
Understanding these different ways to define functions helps in writing clear and efficient
JavaScript code.
Arrow Functions
Arrow functions, introduced in ECMAScript 6 (ES6), provide a concise syntax for writing
function expressions in JavaScript. They are particularly useful for writing short functions
and can help make your code more readable and maintainable. Here are some key features
and examples of arrow functions:
Syntax
Examples
2. Single Parameter:
1. this Binding:
Arrow functions do not have their own this context. Instead, they inherit this from
the surrounding code at the time they are defined. This makes arrow functions
particularly useful in scenarios like event handlers and callbacks.
function Person() {
this.age = 0;
setInterval(() => {
this.age++;
console.log(this.age);
}, 1000);
}
In this example, this.age correctly refers to the Person instance because the arrow
function does not have its own this binding.
2. arguments Object:
Arrow functions do not have their own arguments object. If you need to access the
arguments object, you must use a regular function.
3. Constructors:
Arrow functions cannot be used as constructors and will throw an error if you try to
use them with the new keyword.
Use Cases
Conclusion
Arrow functions provide a concise and more readable way to write function expressions in
JavaScript. However, they come with some differences in behavior compared to regular
functions, especially regarding the this binding and the arguments object. Understanding
these differences is crucial for using arrow functions effectively in your code.
Parameters
Parameters are the placeholders in the function definition that specify what kind of inputs the
function expects. They act as variables within the function, which are assigned values when
the function is called.
Example:
javascript
Copy code
function greet(name, message) {
console.log(message + ", " + name + "!");
}
In the example above, name and message are parameters of the greet function.
Arguments
Arguments are the actual values you pass to the function when you call it. These values are
assigned to the corresponding parameters in the function definition.
Example:
greet("Alice", "Hello");
Here, "Alice" and "Hello" are arguments passed to the greet function, which correspond
to the name and message parameters, respectively.
Detailed Example
Function Definition
function add(a, b) {
return a + b;
}
Function Call
Default Parameters
You can assign default values to parameters. If an argument is not provided, the default value
is used.
Example:
Rest Parameters
Example:
function sum(...numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
In this case, numbers is an array containing all the arguments passed to the function.
Arguments Object
Within a function, you can access the arguments object, an array-like object that contains all
the arguments passed to the function.
Example:
function showArguments() {
console.log(arguments);
}
Arrow functions provide a concise syntax for defining functions. They handle parameters
similarly to traditional functions but with a different syntax.
Example:
Summary
By understanding and utilizing parameters and arguments correctly, you can create flexible
and reusable functions in JavaScript.
Return Statement
In JavaScript, the return statement is used in functions to stop execution and return a value
to the caller. The syntax is straightforward, but its application is essential for controlling the
flow and outcome of functions.
Basic Syntax
function functionName(parameters) {
// code to be executed
return value;
}
Example Usage
1. Returning a value:
function add(a, b) {
return a + b;
}
function greet(name) {
console.log("Hello " + name);
}
function createMultiplier(multiplier) {
return function(x) {
return x * multiplier;
};
}
4. Conditional return: You can use conditions to control when and what is returned:
function checkAge(age) {
if (age >= 18) {
return "Adult";
} else {
return "Minor";
}
}
function test() {
return "done";
console.log("This will never be logged");
}
function max(a, b) {
if (a > b) {
return a;
} else {
return b;
}
}
Returning objects and arrays: Functions can return any type of value, including
objects and arrays.
Conclusion
The return statement is a powerful tool in JavaScript for controlling the output and flow of
functions. Understanding how and when to use return is fundamental for writing effective
and predictable code.
Structure of an IIFE
An IIFE is typically written in the following way:
(function() {
// Code to be executed immediately
})();
Alternatively, you might see it written with an exclamation mark or plus sign at the
beginning:
(function() {
// Code to be executed immediately
}());
or
!function() {
// Code to be executed immediately
}();
+function() {
// Code to be executed immediately
}();
Example Usage
Basic Example
(function() {
console.log("This function runs immediately!");
})();
With Parameters
(function(name) {
console.log("Hello, " + name + "!");
})("Alice");
Returning Values
console.log(result); // Output: 8
Use Cases
1. Avoiding Global Variables: IIFEs are often used to avoid polluting the global scope,
creating a local scope for variables.
(function() {
var localVariable = "I'm local";
console.log(localVariable); // Output: I'm local
})();
console.log(counter.increment()); // Output: 1
console.log(counter.increment()); // Output: 2
console.log(counter.decrement()); // Output: 1
3. Initial Setup Code: Running initialization code immediately without leaving global
variables behind.
(function() {
let settings = {
theme: "dark",
language: "en"
};
// Initialization code
console.log("App initialized with settings:", settings);
})();
Conclusion
IIFEs are a powerful and common pattern in JavaScript for creating isolated scopes,
managing private variables, and running initialization code immediately. They help in
maintaining clean and modular code by avoiding unnecessary global variables and creating
encapsulated functionality.
1. Scope:
o Global Scope: Variables declared outside any function are in the global scope
and can be accessed from anywhere in the code.
o Local Scope: Variables declared inside a function are in the local scope
(function scope) and can only be accessed within that function.
2. Variable Declarations:
o var: Function-scoped. Variables declared with var are scoped to the function
in which they are declared or globally if declared outside any function.
o let and const: Block-scoped. Variables declared with let and const are
scoped to the block in which they are declared (e.g., within {}).
function exampleFunction() {
var functionScoped = "I'm function scoped";
let blockScoped = "I'm block scoped";
const alsoBlockScoped = "I'm also block scoped";
if (true) {
var functionScopedInsideIf = "I'm still function scoped";
let blockScopedInsideIf = "I'm only accessible within this block";
const alsoBlockScopedInsideIf = "I'm also only accessible within
this block";
}
console.log(functionScoped); // Accessible
console.log(blockScoped); // Accessible
console.log(alsoBlockScoped); // Accessible
console.log(functionScopedInsideIf); // Accessible
// console.log(blockScopedInsideIf); // Error: not defined
// console.log(alsoBlockScopedInsideIf); // Error: not defined
}
exampleFunction();
Closures
A closure is a feature in JavaScript where an inner function has access to the outer
(enclosing) function’s variables and parameters, even after the outer function has returned.
Closures allow functions to retain access to their lexical scope.
function outerFunction(outerVariable) {
return function innerFunction(innerVariable) {
console.log('Outer Variable: ' + outerVariable);
console.log('Inner Variable: ' + innerVariable);
}
}
Closures are often used to create private variables and methods in JavaScript.
function createCounter() {
let count = 0;
return {
increment: function() {
count++;
return count;
},
decrement: function() {
count--;
return count;
},
getCount: function() {
return count;
}
};
}
In this example:
Summary
Function Scope: Determines where variables and functions are accessible in your
code.
o var is function-scoped.
o let and const are block-scoped.
Closures: Allow functions to access variables from their enclosing scope even after
the outer function has returned. They are powerful tools for creating private variables
and managing state in functions.
Understanding these concepts enables you to write more robust and maintainable JavaScript
code.