DEV Community

ingaharutyunyan
ingaharutyunyan

Posted on

Javascript Functions

Functions are tools within the Javascript language that allow the user to create instruction within code in chronological order. You can declare variables within the code, which contain objects and other values, and you can manipulate the values using instructions specific to the language.

For example:

`function cake() {
console.log("i like eating cake");
}

cake();`

is a function that instructs the program to output the string "i like eating cake" in the console.

The first line declares the function's existence and name, with brackets to contain the code within.
The second line contains instructions to print the string.
The final line actually calls the function and tells the computer that the code within should be executed. Without it, the function would just stand as inactive code.

Functions should be handled carefully in terms of visibility scope. When a variable is declared outside of a function, it's got global scope, and can be called through console.log(var), if the variable's name is var. There is no problem to declaring a variable that way either, as the function searches line by line for the variable outside of itself. If it is declared within the function, then attempting to retrieve it outside of the function will result in an error message.

This is hopefully a good example of how to write a variable into a function without resulting in an error message:

`var gingerMan = "Ed Sheeran";

function badSinger() {
console.log(gingerMan)
}

badSinger();`

Top comments (0)