JavaScript

Functions

Function have a function keyword, name of the function, parameters and statements.

function

A function is a fundamental building block in JavaScript. It can help you, so you dont need to write the same code multiple times.
It takes some input and returns an output, if you want to use the a function, you must define it somewhere in the scope.
A function name can not be JavaScripts reserved words
Functions is a code block performing a specific task.

function myFunc(x) {
return x * x - 10;
};
console.log(myFunc(100));

This is a function. It has one parameter called x, and consists of one statment that says to return the parameter of the function multiplied with itself and subtract 7.

Declared functions

function firstLastWord(str) { 
return str + "Script";
};
console.log(firstLastWord('Java'));

Function Expressions

const func = function(number) {
return number + number;
};
console.log(func(10));

This is a function expression. These functions do not need to have a name, instead they have a variable.

The code explained

const func = function(number) {
//this is a function
}

This is another way of making a function

return number + number;

We are returning some informations to the function, so it knows what to excute. the variables number are a number that we can declare

console.log(func(10));

This code show us the result in the console. We need to call the function, by writing the name of it and full out a number, to the vaiables

Arrow functions

const greeting = (name) => { 
console.log(`Greetings ${name}!`);
};
greeting("Rikke");
Example 3.3.4

This is a arrow function. These functions are a shortcut

The code explained

const greeting = (name) => { 
};

We have made a variable with a function, then assigned a paramtere to the function, called name. The arrow is the functions, that leads us the to code.

console.log(`Greetings ${name}!`);

Inside the function have we made a console.log() with the use of backtics.

greeting("Rikke");

To executed the function we must call it, and declare the parameters.

Scope

We will talk about something called variables. But first must we understand where they should be.
JavaScript has two types of scope locally scope and globally scope.
The scope determines the accessibility (visibility) of these variables

Local scope

// code here can NOT use carName 
function myFunction() {
var carName = "Volvo";
// code here CAN use carName
}

The local variable can only be used inside the function, and not outside.

Global scope

var carName = "Volvo";
// code here can use carName
function myFunction() {
// code here can use carName
}

The global variable can be used inside and outside a function.