JavaScript L-2
Functions in javascript.
Functions are used to execute any task that repeats itself.
//Declare Function
function singHppyB(){
console.log("Happy Birthday!")
}
// Call Function
singHppyB();
//Storing return value in new variable and calling it
function twoPlus(){
return 2+5;
}
twoPlus();
const returenedValue=twoPlus();
console.log(returenedValue);
Function with parameters.
Function parameters are the names listed in the function definition.
Function arguments are the real values passed to (and received by) the function.
// adding parameters
function sum(num1,num2){
return num1+num2;
}
//arguments passed
const returnV=sum(3,5);
console.log(returnV);
Function Expression.
Storing the function in the variable.
//const ,let , var ; anything can be used for declaration
const happy=function(){
console.log("BJKs hxdjK")
}
happy();
Arrow Functions.
const name=(num1,num2,num3)=>{
return num1+num2+num3
}
const numbers=name(2,3,4);
console.log(numbers);
Another way to represent Arrow Function.
//it means a variable named "Number" takes "num" as parameter and returns num%2===0
const Number= num => num % 2 === 0;
console.log(Number(20));
Hoisting.
Hoisting means "calling of a function or variable "before declaring it. However, we can do it with variable declaration or function, not with function expression.
hello();
function hello(){
console.log("hello");
}
//function expression(it will not give output through this.)
const hello = function(){
console.log("helloo");
}
Nested Functions.
function app(){
const myfunc=()=>{
console.log("Hey");
}
const add=(num1,num2)=>{
return num1+num2;
}
console.log("inside app");
myfunc();
}
app();
Lexical Scope.
Lexical scope is the set of rules for how the JavaScript engine finds variables and functions when executing code, relative to where you've defined them at author-time.
//here myVar is found using lexical scope.
const myVar="VALUE1"
function myApp(){
function myFunc(){
const myFunc2 =()=>{
console.log("Inside loop",myVar);
}
myFunc2();
}
console.log(myVar);
myFunc();
}
myApp();