DEV Community

front_end_shifu_2022
front_end_shifu_2022

Posted on

Functions

Functions

Functions are the main “building blocks” of the program. They allow the code to be called many times without repetition.
Function Declaration
To create a function we can use a function declaration.It looks like this:

function showText() {
alert( 'Hello everyone!' );
}

function goes first,then name of function then list of parameters between curly braces(separated by coma)and then main body of the function.
Our new function can be called by its name: showText().

e.g.
function showText() {
alert( 'Hello everyone!' );
}

showText();

Local variables
A variable declared inside a function can only be accesd inside that function.we can't acces it from outside .
e.g.
function showMessage() {
let message = "Hello, I'm JavaScript!"; // local variable
alert( message );
}
showMessage(); // Hello, I'm JavaScript!
alert( message ); // <-- Error! The variable is local to the function

Outer variables
A function can access an outer variable as well.
e.g.
userName = 'Talha';
function showName() {
let message = 'Hello, ' + userName;
alert(message);
}
showName(); // Hello, Talha

The function has full access to the outer variable. It can edit modify it as well.
e.g.
let userName = 'Talha';
function showName() {
let userName = 'cagebreaker';
let message = 'Hello, ' + userName;
alert(message);
}
showName(); // Hello, cagebreaker

note:The outer variable is only used if there’s no local one.

If a same-named variable is declared inside the function then it ignore the outer one and use local variable.
e.g.
let userName = 'Talha';
function showName() {
let userName = 'cagebreaker';
let message = 'Hello, ' + userName;
alert(message);
}
showName(); // Hello, cagebreaker
alert( userName ); // Talha, unchanged, the function did not access the outer variable.

Global variables
Variables declared outside of any function, such as the outer userName in the code above, are called global.
Global variables are visible from any function (unless shadowed by locals).
Note:It’s a good practice to minimize the use of global variables. Modern code has few or no globals. Most variables reside in their functions. Sometimes though, they can be useful to store project-level data.

Parameters
It's also called function argument.
We can pass arbitrary(any) data to functions using parameters.
e.g. look at the example below the function has two parameters: fullName and LastName:

function showMessage(fullname, lastName) { // arguments: fullName, LastName
alert(fullName + ': ' + LastName);
}
showMessage('Talha', 'Khan'); // Talha: Khan! ()
showMessage('Hasnian', "Afridi:)>"); // Hasnain:Afridi (
)
When the function is called in lines (
) and (**), the given values are copied to local variables from and text. Then the function uses them.
this is all for now I will share more in my upcomming posts

Top comments (0)