Kaunia
Functions are core to JavaScript — they encapsulate logic, allow reuse, and form the building blocks of modular code. This guide covers:
There are several ways to define a function in JavaScript:
1.1 Function Declaration
This form is hoisted, meaning you can call it before its declaration in the code.
1.2 Function Expression
Function expressions are not hoisted in the same way; the variable must be defined before being invoked.
1.3 Named vs Anonymous Functions
Arrow functions provide a shorter syntax and lexical this binding.
Variants:
Key Characteristics:
Parameters are the names listed in function definitions; arguments are the values passed when the function is invoked.
Default Parameters
You can set defaults:
If no argument or undefined is passed, the default is used.
Rest Parameters
You can capture an indefinite number of arguments:
Here numbers is an array of all passed arguments.
Parameter vs Arguments Behavior
How you call a function impacts its behavior, including the this context.
4.1 Simple Invocation
Here this refers to the global object (or undefined in strict mode).
4.2 Method Invocation
When a function is called as a method of an object:
4.3 Constructor Invocation (with new)
When you use new, a new object is created, and this refers to that new object:
Arrow functions can’t be used as constructors.
4.4 call, apply, bind
You can explicitly set this using:
Understanding this is essential to mastering functions.
5.1 In Function Declarations / Expressions
5.2 In Method Calls
When a function is called as a property of an object, this refers to that object.
5.3 In Constructor Calls
Inside a constructor function, this refers to the newly created object.
5.4 In Arrow Functions
Arrow functions do not have their own this. Instead, this is inherited lexically from the surrounding scope.
Example:
Here, the arrow function in setTimeout uses the this from sayLater’s context (the obj), not the global object.
Functions in JavaScript are versatile. By mastering:
you build a strong foundation for writing cleaner, more predictable JavaScript.
Type the number that you see in image.
IT Services for Businesses Reliable Tech Solutions and Support
it-service-0
Learn Money Get Rich - Personal Finance & Wealth Building Blog
learn-money-get-rich
Electronics
electronics
TechScout Daily
tech-scout-0