Functions Flashcards
Declare a function that returns Hello and concatenate using +
function greet(firstName, lastName){ return 'Hello' + ' ' + firstName + ' ' + lastName; } console.log(greet('John', 'Doe'));
What would look like this function if it didn’t have attributes in the console? and what will it return?
function greet(firstName, lastName){ return 'Hello' + ' ' + firstName + ' ' + lastName; } console.log(greet('John', 'Doe'));
function greet(firstName, lastName){ return 'Hello' + ' ' + firstName + ' ' + lastName; } console.log(greet());
WILL RETURN
Hello undefined undefined
Study this function and tell what is happening in it.
function greet(firstName = 'John', lastName = 'Doe'){ return 'Hello ' + firstName + ' ' + lastName; } console.log(greet('cc', 'xx'));
function greet(firstName = 'John', lastName = 'Doe'){ return 'Hello' + ' ' + firstName + ' ' + lastName; } console.log(greet('cc', 'xx'));
In here we are assigning a default value to the parameters firstName and lastName, meaning that if we don’t call anything in our console.log, it will return such a value since it’s default however if we assign anything to our console.log it will write over the default and will show the value assign
What is a function expression?
It’s basically a variable that has become a function since the function it’s assigned to the variable and it will be executed every time the variable it’s called.
show a function expression.
const square = function(x){ return x*x; };
console.log(square(4));
// The reason why you have to console.log square(5) it’s because square it’s calling the function within it, but you have to assign a value to your parameter that it’s within your function and that value will be assign in the console.log by giving it to square
Assign a default value to x
const square = function(x){ return x*x; };
console.log(square(4));
const square = function(x = 4){ return x*x; };
console.log(square());
// In this case x = 4 because what X is looking for it’s a number to be multiplied by, we cannot assign a string to X as default because it will return NaN
What is IMMEDIATELY INVOKABLE FUNCTION EXPRESSIONS - IIFEs
These are functions that you declare and run at the same time.
What does an IMMEDIATELY INVOKABLE FUNCTION EXPRESSIONS - IIFEs look like?
(function(){
console.log(‘IIFE Ran..’)
})()
How are methods create?
Methods are created when a function its put inside of a object it’s called method.
Type a method
const todo = { add: function (){ console.log('Add todo..'); }, edit: function(id){ console.log(`Edit todo ${id}`); } }
todo.delete = function(){
console.log(‘Delete todo…’)
}
todo. add();
todo. edit(22);
todo. delete();