Skip to content

Latest commit

 

History

History
156 lines (142 loc) · 2.03 KB

16. Global and local scope.md

File metadata and controls

156 lines (142 loc) · 2.03 KB

Scope

let number = 5;
console.log(number);

Output

5

Local Scope

Example 1

function addNumbers (n1, n2) {
    let result = n1 + n2;
    console.log(result);
}

addNumbers(4, 9);

Output

13

Example 2

function addNumbers (n1, n2) {
    let result = n1 + n2;
    console.log(result);
}

addNumbers(4, 9);
console.log(result);

Output

ReferenceError: Can't find variable: result

Example 3

function addNumbers (n1, n2) {
    let result = n1 + n2;
    console.log(result);
}

addNumbers(4, 9);

let result = 123;
console.log(result);

Output

13
123

Global Scope

Example 1

let result;

function addNumbers (n1, n2) {
    result = n1 + n2;
}

addNumbers(4, 9);
console.log(result);

Output

13

Change the value of Global Variable

let message = "hello";

function greet() {
    message = "How are you?"

}

// before the function call
console.log(message);

greet();

//after the function call
console.log(message);

Output

hello
How are you?

Block Scoped

Example 1

const addNumbers = (n1, n2) => {
    let result = n1 + n2;
    console.log(result);
    if (result > 10) {
        let result1 = "Positive";
        console.log(result1)
    }
}

addNumbers(4, 9);

Output

13
Positive

Example 2

const addNumbers = (n1, n2) => {
    let result = n1 + n2;
    console.log(result);
    if (result > 10) {
        let result1 = "Positive";
        console.log(result1)
    }
    console.log(result1);
}

addNumbers(4, 9);

Output

13
Positive
ReferenceError: Can't find variable: result1

Programiz Quiz

Q. What is the output of the program?

let a = 88;
function checkValue() {
    let a = 77;
    a = a - 57;
}
checkValue();
console.log(a);
  1. 88
  2. 77
  3. 20
  4. 31

Answer: 1