Functions in JavaScript
Functions:
Functions can help organize the code, avoid repetition and reduce the complexity of the code.
1. Function Declaration: the function in the main code flow
To declare a function, you use the "function" keyword, followed by the function name, a list of parameters, and the function body as follows:
let result = a + b;
return result;
}
2. Function Expression: the function in the context of an expression
"console.log()" is also a function to output a message to the console.
let result = a + b;
return result;
};
Parameters vs Arguments: The terms parameters and arguments are often used interchangeably. However, they are essentially different.
However, when calling a function, you pass the arguments.
3. Arrow functions
var welcomeStr = () => {
All these functions do the same thing:
return num % 2 === 0;
}
return num % 2 === 0;
}
return num % 2 === 0;
}
num % 2 === 0;
)
)
The code inside the function will execute when something invokes(calls) the function:
1. Invocation by event:
alert('this is function');
}
2. Invocation by calling:
function name(){
const = 'my name is function';
}
name();
3. Self-Invoking Functions:
A self-invoking expression is invoked (started) automatically, without being called. Function expressions will execute automatically if the expression is followed by ()
let x = "Hey!!";
})();
The Return Statement:
Our function is now dynamic but it's performing only one task: sending results to the console. This can be useful for testing purposes but not more than that. It would be good if our function could return the value so we could do anything we want with it.
The return statement should be the last in a function because the code after the return statement will be unreachable.
Comments
Post a Comment