KandZ – Tuts

We like to help…!

JavaScript 10 🧬 Functions

a - functions introduction
functions are blocks of code designed to perform a specific task
They can be defined using the function keyword or arrow syntax
they play a crucial role in organizing and structuring code
Functions are hoisted, meaning they can be called before they are defined in the code.
function greet(name) { } → greet function declaration
greet("Hello World") → function call
A function expression involves assigning a function to a variable.
This is different from a declaration because it does not get hoisted.
const greet2 = function(name) { } → function expression

b - function arguments and return value
functions can accept inputs known as arguments
Arguments are values that a function receives when it is invoked or called.
Parameters are the names listed in the function definition
arguments are the actual values passed when calling the function.
Arguments that must be provided when calling the function; otherwise, an error occurs (in strict mode).
function add(a, b) { } → Function definition with parameters (a, b)
let result = add(5, 3); → Calling the function with arguments 5 and 3
return "Hello, " + name; → function returns a value

c - function default arguments
Introduced in ES6, default arguments allow functions to have parameters with predefined values
those are used if no argument or undefined is used
function greet(name = "Guest") { } → function with default argument
console.log(greet()); → Output: Hello, Guest
console.log(greet("Bob")); → Output: Hello, Kronos
While JavaScript does not have built-in support for optional parameters...
you can simulate them by checking for undefined or defaulting values within the function.
if (name === undefined) { } → checks if undefined

Leave a Reply