JS-XI Functions Notes - 664874
JS-XI Functions Notes - 664874
Suppose , we have wrote the code for calculating the sum of two numbers, calculating
the difference of two numbers and calculating the multiplication of two numbers in single
file.
When I execute the code file, all the three code will execute but What if I want only to
run Addition code or subtraction code only.
I need some tool through which I able to control the different block of code.
For Example :
In Amazon , there are different functionalities implemented like Showing products,
Adding/Deleting to cart, Orders, perform payments, etc.
In Instagram, there are different functionalities like posting the image, commenting ,
chatting, etc.
Those code execution depends upon the button you are hitting
Functions
A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when "something" invokes it (calls it).
Functions 1
To solve above problem , we will create three functions of names addition,
subtraction and multiplication .
After creating the function, we will put the respective code inside them.
Now, we can control the code by calling it. It depends on us How we are calling it.
Whichever function will get called, it will run.
var a = 3;
var b = 5;
var sum = a + b;
console.log("Sum is ",sum);
var x = 4;
var y = 8;
var multiply = x*y;
console.log(x*y);
If I execute the above code, All the three code will get executed but I don’t want to run
all the code
function sheru(){
var name = "Shiro";
console.log(name);
console.log("length ",name.length);
}
Functions 2
// Sum of two numbers
function sum_of_two_numbers(){
var a = 2;
var b = 3;
console.log("Sum ",a+b);
}
function print_numbers(){
// printing from 1 to 10
for(var i = 1; i<10; i++){
console.log(i);
}
}
function square(x){
var y = x*x;
return y;
}
function cube(x){
var z = x*x*x;
return z;
}
Functions 3
Code 4 : Local Scope vs Global Scope
function sukhbeer_singh(){
var sukhbeer_child = "rahul"; // local Variables
console.log("My child name is ",sukhbeer_child);
}
function kalam_singh(){
var kalam_child = "rajat"; // local Variables
console.log("My child name is ",kalam_child);
}
function rajendra_singh(){
var rajendra_child = "rocky"; // local Variables
console.log("My child name is ",rajendra_child);
}
sukhbeer_singh();
console.log(outside_child);
Functions 4