JavaScript - Scope, Functions, Type Conversion
Functions in JavaScript
A function in JavaScript is a reusable block of code designed to perform a specific task. Functions help organize code, avoid repetition, and make programs modular and easier to maintain. A function executes when it is invoked (called) in the program
Declaring a Function
The most common way to declare a function is using the function keyword:
function functionName(parameter1, parameter2) {
// code to be executed
return result;
}functionName: The name you give the function.
parameter1, parameter2: Input values (parameters) the function expects.
return: Sends a value back to where the function was called (optional)
Example:
function add(a, b) {
return a + b;
}
let sum = add(2, 3); // sum is 5Function Parameters and Arguments
Parameters are variables listed in the function definition.
Arguments are the actual values passed to the function when it is called.
Inside the function, parameters behave as local variables
Calling a Function
A function is executed when it is "invoked" by its name, followed by parentheses and any required arguments:
add(5, 7); // returns 12Function Expressions and Arrow Functions
Functions can also be defined as expressions and assigned to variables:
const multiply = function(x, y) {
return x * y;
};Arrow functions offer a shorter syntax:
const multiply = (x, y) => x * y;Arrow functions are especially useful for concise, one-line functions and cannot be used as constructors
Function Constructor
Functions can be created using the Function constructor, though this is less common:
const sum = new Function('a', 'b', 'return a + b');This approach is generally discouraged in favor of function declarations and expressions
Returning Values
A function can return a value using the return statement. If no return is specified, the function returns undefined by default
Anonymous Functions
Functions without a name are called anonymous functions. They are often used as arguments to other functions or assigned to variables
Function Methods
JavaScript provides several methods for functions:
call() and apply(): Invoke a function with a given
thisvalue and arguments.bind(): Creates a new function with a specified
thisvalue.toString(): Returns the function as a string
Summary Table
Declaration
Named, reusable code block
function greet() { ... }
Expression
Assigned to variable, can be anonymous
const fn = function() { ... }
Arrow Function
Short syntax, always anonymous
const fn = () => { ... }
Parameters
Input variables
function sum(a, b)
Arguments
Actual values passed to function
sum(2, 3)
Return Value
Value sent back by function
return a + b;
The this Keyword in JavaScript
this Keyword in JavaScriptThe this keyword in JavaScript is a special reference that points to the object that is currently executing the function or code block. The value of this depends on how and where a function is invoked, not how or where it is defined
How this Works in Different Contexts
this Works in Different ContextsContext
What this Refers To
Global scope (non-strict mode)
The global object (window in browsers)
Function (non-strict mode)
The global object
Function (strict mode)
undefined
Object method
The object the method is called on
Constructor function
The new object being created
Event handler
The DOM element that received the event
Arrow function
Inherits this from the enclosing (lexical) scope
Using call, apply, bind
The explicitly specified object
Examples
1. Global Scope
console.log(this); // In browser: windowIn the global context, this refers to the global object
2. Inside a Regular Function
function show() {
console.log(this);
}
show(); // In browser: window (non-strict mode)Here, this is the global object (or undefined in strict mode)
3. As an Object Method
const person = {
name: "Alice",
greet: function() {
console.log(this.name);
}
};
person.greet(); // "Alice"Within an object method, this refers to the object itself
4. In a Constructor Function
function Car(brand) {
this.brand = brand;
}
const myCar = new Car("Toyota");
console.log(myCar.brand); // "Toyota"Here, this refers to the newly created object
5. In Event Handlers
button.onclick = function() {
console.log(this); // The button element
}In event handlers, this refers to the DOM element that received the event
6. Arrow Functions
const obj = {
value: 42,
show: () => {
console.log(this.value);
}
};
obj.show(); // `this` does NOT refer to `obj`, but to the enclosing scopeArrow functions do not have their own this; they inherit it from the outer (lexical) scope
7. Explicit Binding
function show() {
console.log(this.name);
}
const user = { name: "Bob" };
show.call(user); // "Bob"Methods like call, apply, and bind can explicitly set the value of this
Summary
The value of
thisis determined by how a function is called, not where it is defined.It is used for accessing properties and methods of the object that is currently executing the function.
Arrow functions inherit
thisfrom their enclosing context, while regular functions’thisdepends on the call site6.Understanding
thisis crucial for writing correct and maintainable JavaScript code
Variable Scope in JavaScript
JavaScript does not have built-in keywords for public, private, privileged, or static variables as seen in some other languages (like Java or C++), but these concepts can be implemented using JavaScript's scope rules, closures, and ES6 class features.
Public Variables
Definition: Variables that are accessible from anywhere the object or function is accessible.
How to Implement: In objects or classes, properties assigned with
thisare public.function Person(name) { this.name = name; // public } const p = new Person('Alice'); console.log(p.name); // AccessibleScope: Global, function, or block, depending on where declared
Private Variables
Definition: Variables that are not accessible from outside the function or object where they are defined.
How to Implement:
Closure: Declare variables with
var,let, orconstinside a function, but do not attach them tothis.function Person(name) { let age = 30; // private this.name = name; // public this.getAge = function() { return age; }; // privileged } const p = new Person('Alice'); console.log(p.name); // Accessible console.log(p.age); // Undefined (private)ES2022 Private Fields: Use
#prefix in classes.class Person { #age = 30; // private constructor(name) { this.name = name; } getAge() { return this.#age; } }
Scope: Only accessible within the function or class where defined
Privileged Variables/Methods
Definition: Methods that are public but have access to private variables via closure.
How to Implement: Define a method inside the constructor that accesses private variables.
function Person(name) { let age = 30; // private this.name = name; // public this.getAge = function() { return age; }; // privileged }Scope: Publicly accessible, but can access private data.
Static Variables
Definition: Variables that are shared among all instances of a class or constructor function, not tied to any one instance.
How to Implement:
Function/Constructor: Attach to the function itself.
function Person(name) { this.name = name; } Person.count = 0; // staticES6 Classes: Use the
statickeyword.class Person { static count = 0; // static constructor(name) { this.name = name; Person.count++; } }
Scope: Belongs to the class or constructor, not to instances.
Summary Table
Public
this.variable or class field
Accessible everywhere the object is accessible
Private
Closure variable or #field in class
Only within function/class
Privileged
Method accessing closure/private field
Public method, accesses private data
Static
Class.staticVar or Constructor.staticVar
Shared across all instances, accessed via class/constructor
In summary:
Public: Accessible everywhere.
Private: Accessible only inside the function/class.
Privileged: Public methods with access to private variables.
Static: Shared across all instances, accessed via the class or constructor.
Try Catch Finally in JavaScript
The try...catch...finally statement in JavaScript is used for error handling. It allows you to test a block of code for errors, handle those errors gracefully, and execute code regardless of whether an error occurred.
How It Works
try: The code that may throw an error is placed inside the
tryblock.catch: If an error occurs in the
tryblock, control moves to thecatchblock, where you can handle the error.finally: The
finallyblock always executes after thetryandcatchblocks, whether an error occurred or not. This is useful for cleanup code, like closing files or releasing resources.
Syntax
try {
// Code that may throw an error
} catch (error) {
// Code to handle the error
} finally {
// Code that always runs
}Both catch and finally are optional, but at least one must be present
Example
let result = 0;
try {
result = add(10, 20); // add is not defined, will throw an error
} catch (e) {
console.log(e.message); // Output: add is not defined
} finally {
console.log({ result }); // Output: { result: 0 }
}In this example:
The
tryblock attempts to call a functionaddthat does not exist, causing an error.The
catchblock logs the error message.The
finallyblock logs theresultvariable, which is always executed, regardless of the error
Another Example (No Error)
const add = (x, y) => x + y;
let result = 0;
try {
result = add(10, 20);
} catch (e) {
console.log(e.message);
} finally {
console.log({ result }); // Output: { result: 30 }
}Here, since add is defined, no error occurs, and the finally block still runs2.
Key Points
The
finallyblock always executes, even if thetryorcatchblocks contain areturnstatementUse the
finallyblock for cleanup actions that must run regardless of success or error.You can nest
try...catchblocks for more complex error handling
Summary Table
try
Code that may throw an error
Always (first)
catch
Handle errors from try block
If an error occurs in try
finally
Cleanup or final code
Always, after try/catch
Last updated