A JavaScript function is a block of code designed to perform a particular task.

It is executed when something invokes it (calls it)

It is defined with a function key world followed by a name followed by parentheses ()

Function myFunction (s1,s2) {return s1*s2 //the function}

Function names can contain letters , digits , underscore, and dollar signs (same rules as variables)

The parentheses may include parameter names separated by commas so the code to be executed by the function, is placed inside curly brackets : {}

Invoking function

The code inside the function will execute when “something” invokes the function

  • When an event occurs exemple , on button click
  • When it is called from javascritp code
  • Automatically , self invoked

Function Return

When JavaScript reaches a return statement , the function will stop executing.

If the Function was invoked from a statement , JavaScript will “return” to execute the code after the invoking statement .

Functions often compute  a return value . The return value is “returned” back to the “caller”

Functions can be used as Variable Values

Function can be used the same way as you use variables , in all types of formulas , assignements and calculations .

Instead of using a variable to store the return of a function :

var x = toCelsius(88); 

var text = "the temperature is "+ x + "Celsius"; 

Or you can use the function directly , as a variable value :

var text = "the temperature is "+ toCelsius(88)+ "Celsius"; 

Local & Global variables

The scope of a variable is the region of your program in which it is defined

JavaScript Variables have only two scopes : Local Variable or Global Variable

Global variable

Local Variable

That’s all you need to know to get started with JavaScript function !