Functions

Estimated reading: 1 minute 105 views

Functions contain blocks of code that need to be executed repeatedly. Functions can take zero or more arguments, and can optionally return a value. Functions can be created in a variety of ways

Function Declaration

				
					 function foo() { /* do something */ }

				
			

Named Function Expression

				
					 var foo = function() { /* do something */ }

				
			

Using Functions

Asimple function

				
					var greet = function(person, greeting) {
 var text = greeting + ’, ’ + person;
 console.log(text);
 };
 greet(’Rebecca’, ’Hello’);
				
			

Afunction that returns a value

				
					 var greet = function(person, greeting) {
 var text = greeting + ’, ’ + person;
 return text;
 };
 console.log(greet(’Rebecca’,’hello’));
				
			

Afunction that returns another function

				
					var greet = function(person, greeting) {
 var text = greeting + ’, ’ + person;
 return function() { console.log(text); };
 };
 var greeting = greet(’Rebecca’, ’Hello’);
 greeting();
				
			

Variables with the same name can exist in different scopes with different values

				
					var foo = ’world’;
 var sayHello = function() {
 var foo = ’hello’;
 console.log(foo);
 };
 sayHello(); // logs ’hello’
 console.log(foo); // logs ’world’
				
			
Share this Doc

Functions

Or copy link