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:
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 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:
Function Expressions and Arrow Functions
Functions can also be defined as expressions and assigned to variables:
Arrow functions offer a shorter syntax:
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:
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
this
value and arguments.bind(): Creates a new function with a specified
this
value.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
In the global context, this
refers to the global object
2. Inside a Regular Function
Here, this
is the global object (or undefined
in strict mode)
3. As an Object Method
Within an object method, this
refers to the object itself
4. In a Constructor Function
Here, this
refers to the newly created object
5. In Event Handlers
In event handlers, this
refers to the DOM element that received the event
6. Arrow Functions
Arrow functions do not have their own this
; they inherit it from the outer (lexical) scope
7. Explicit Binding
Methods like call
, apply
, and bind
can explicitly set the value of this
Summary
The value of
this
is 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.
Understanding
this
is 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
this
are public.Scope: 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
, orconst
inside a function, but do not attach them tothis
.ES2022 Private Fields: Use
#
prefix in classes.
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.
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.
ES6 Classes: Use the
static
keyword.
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
try
block.catch: If an error occurs in the
try
block, control moves to thecatch
block, where you can handle the error.finally: The
finally
block always executes after thetry
andcatch
blocks, whether an error occurred or not. This is useful for cleanup code, like closing files or releasing resources.
Syntax
Both catch
and finally
are optional, but at least one must be present
Example
In this example:
The
try
block attempts to call a functionadd
that does not exist, causing an error.The
catch
block logs the error message.The
finally
block logs theresult
variable, which is always executed, regardless of the error
Another Example (No Error)
Key Points
The
finally
block always executes, even if thetry
orcatch
blocks contain areturn
statementUse the
finally
block for cleanup actions that must run regardless of success or error.You can nest
try...catch
blocks 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